C#从ListBox读取邮箱列表批量发邮件遇格式异常如何解决
错误原因
- 你当前使用
string emails = email_c.GetItemText(email_c.Items);获取邮箱的逻辑完全错误:GetItemText()方法传入单个Item对象时才会返回对应项的文本,传入整个Items集合时,返回的是集合的类型名而非所有邮箱拼接结果,因此生成的字符串完全不符合邮箱格式规范,触发格式异常。 - 额外注意:如果你的
txtuser.Text本身已经带有@域名后缀,发件人地址拼接逻辑也会重复生成@导致格式错误。
修正后的代码
login = new NetworkCredential(txtuser.Text, txtPassword.Text); client1 = new SmtpClient(txtSmtp.Text); client1.Port = Convert.ToInt32(txtPort.Text); client1.Credentials = login; msg = new MailMessage { // 建议这里先校验拼接后的发件人地址是否符合格式 From = new MailAddress(txtuser.Text + txtSmtp.Text.Replace("smtp.", "@"), "Sesizare", Encoding.UTF8) }; // 遍历ListBox所有项逐个添加收件人 foreach (var item in email_c.Items) { string email = email_c.GetItemText(item).Trim(); // 跳过空项 if (!string.IsNullOrEmpty(email)) { // 可选:加格式校验逻辑,避免单个无效邮箱报错 msg.To.Add(new MailAddress(email)); } } if (!string.IsNullOrEmpty(txtCC.Text)) msg.To.Add(new MailAddress(txtCC.Text)); msg.Subject = txtSubject.Text; msg.Body = "Abonamentul dumneavoastra a fost activat"; msg.BodyEncoding = Encoding.UTF8; msg.IsBodyHtml = true; msg.Priority = MailPriority.Normal; msg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; client1.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback); string userstate = "Ttimite..."; client1.SendAsync(msg, userstate);
可选优化建议
- 可提前用正则表达式校验每个邮箱的格式,过滤无效地址避免发送失败
- 发件人地址拼接完成后可先做一次格式校验,避免发件人地址错误导致的异常
- 如果要批量发送给大量邮箱,建议拆分单个邮件的收件人数量,避免被SMTP服务器判定为垃圾邮件拦截
内容的提问来源于stack exchange,提问作者Moldoveanu Marius
相关产品推荐
相关产品推荐

