Reputation: 205
EDIT I use following code to send batch email in C#. However, when one of the recipients have invalid email address, email is not sent even to other recipients whose email address is valid and I am getting an exception:
system.net.mail.smtpfailedrecipientsexception failed recipients
Is there any way I can send the email to other valid recipients even if one of the email address is invalid?
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 ("[email protected]");
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() ));
}
}
Moreoever, before I send string email addresses to SendMailMessage method I check they are valid or not by this method:
public bool IsValidEmail(string emailaddress)
{
try
{
MailAddress m = new MailAddress(emailaddress);
return true;
}
catch (FormatException)
{
return false;
}
}
Upvotes: 2
Views: 4704
Reputation: 988
Personally I would loop through and call Send multiple times (one for each address). There are many things that can go wrong if sending BCC to many addresses, including the mail server rejecting it due to too many addresses.
Upvotes: 1
Reputation: 301
When sending e-mail using Send to multiple recipients and the SMTP server accepts some recipients as valid and rejects others, Send sends e-mail to the accepted recipients and then a SmtpFailedRecipientsException is thrown. The exception will contain a listing of the recipients that were rejected.
From Documentation: http://msdn.microsoft.com/en-us/library/swas0fwc.aspx
Sounds like it does exactly what you want it to do, try sending it to an e-mail you can access and see if you are sent the e-mail.
Upvotes: 1