用c#发送批量电子邮件
本文关键字:电子邮件 | 更新日期: 2023-09-27 18:12:22
EDIT我使用以下代码在c#中发送批量电子邮件。但是,当其中一个收件人的电子邮件地址无效时,电子邮件甚至不会发送给其他电子邮件地址有效的收件人,并且我得到一个异常:
system.net.mail.smtpfailedrecipientexception接收失败
如果其中一个电子邮件地址无效,我是否可以将电子邮件发送给其他有效的收件人?
public void SendMailMessage (string[] to,string message,string subject)
{
MailMessage mMailMessage = new MailMessage ();
int lenght = to.GetLength(0);
if (lenght > 1) {
foreach (string email in to) {
mMailMessage.Bcc.Add ( email );
}
}
else {
mMailMessage.To.Add ( to[0] );
}
mMailMessage.From = new MailAddress ("no-replay@mycompany.net");
SmtpClient mSmtpClient = new SmtpClient ();
mMailMessage.Body = message;
mMailMessage.IsBodyHtml = true;
mMailMessage.Priority = MailPriority.Normal;
mMailMessage.Subject = subject;
mSmtpClient.EnableSsl = true;
ServicePointManager.ServerCertificateValidationCallback = delegate(object s,X509Certificate certificate,X509Chain chain, SslPolicyErrors sslPolicyErrors) {return true;};
try {
mSmtpClient.Send (mMailMessage);
}
catch (SmtpFailedRecipientsException ex){
for (int i = 0; i < ex.InnerExceptions.Length; i++)
{
SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
if (status == SmtpStatusCode.MailboxBusy ||
status == SmtpStatusCode.MailboxUnavailable)
{
Logger.Debug("Delivery failed - retrying in 5 seconds.");
System.Threading.Thread.Sleep(5000);
//client.Send(message);
mSmtpClient.Send (mMailMessage);
}
else
{
Logger.Debug (string.Format ("Failed to deliver message to {0},{1}", ex.InnerExceptions[i].FailedRecipient, i));
}
}
}
catch (Exception ex)
{
Logger.Debug (string.Format("Exception caught in RetryIfBusy(): {0}", ex.ToString() ));
}
}
此外,在我将字符串电子邮件地址发送到SendMailMessage方法之前,我通过这个方法检查它们是否有效:
public bool IsValidEmail(string emailaddress)
{
try
{
MailAddress m = new MailAddress(emailaddress);
return true;
}
catch (FormatException)
{
return false;
}
}
当使用"发送到多个收件人"发送电子邮件时,SMTP服务器接受某些收件人为有效收件人而拒绝其他收件人时,Send向接受的收件人发送电子邮件,然后抛出SmtpFailedRecipientsException异常。该异常将包含被拒绝的收件人列表。
来自文档:http://msdn.microsoft.com/en-us/library/swas0fwc.aspx
听起来就像你想要它做的,试着把它发送到一个你可以访问的电子邮件,看看你是否收到了电子邮件。
我个人会多次循环并调用Send(每个地址一次)。如果密件抄送到很多地址,有很多事情可能会出错,包括邮件服务器因为地址太多而拒绝它。