Sending a list of emails using SmtpClient
I am using SendCompletedEventHandler from SmtpClient when sending a list of emails.
SendCompletedEventHandler is only called when all emails in the list have already been sent.
I have expexted that SendCompletedEventHandler is called when an email is sent.
Is there something wrong with my code?
public void SendAllNewsletters(List<string> recipients)
{
string mailText = "My Text";
foreach(string recipient in recipients)
{
//if this loop takes 10min then the first call to
//SendCompletedCallback is after 10min
SendNewsletter(mailText,recipient);
}
}
public bool SendNewsletter(string mailText , string emailaddress)
{
SmtpClient sc = new SmtpClient(_smtpServer, _smtpPort);
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(_smtpuser, _smtppassword);
sc.Credentials = SMTPUserInfo;
sc.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
MailMessage mm = null;
mm = new MailMessage(_senderemail, emailaddress );
mm.IsBodyHtml = true;
mm.Priority = MailPriority.Normal;
mm.Subject = "Something";
mm.Body = mailText ;
mm.SubjectEncoding = Encoding.UTF8;
mm.BodyEncoding = Encoding.UTF8;
//Mail
string userState = emailaddress;
sc.SendAsync(mm, userState);
return true;
}
public void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
// Get the unique identifier for this asynchronous operation.
String token = (string)e.UserState;
if (e.Error != null)
{
_news.SetNewsletterEmailsisSent(e.UserState.ToString(), _newslettername, false, e.Error.Message);
}
else
{
_news.SetNewsletterEmailsisSent(e.UserState.ToString(), _newslettername, true, string.Empty);
}
}
a source to share
It works as expected on my machine, except that the MailMessage constructor throws a format exception because "My Tex"
it is not a valid email address. The first argument is the sender's email address.
As Josh Stodola points out, you should cache SmtpClient
for the life of this class, not create another one for each call. If you are not caching SmtpClient
, then you should add the following line to the end of your SendCompletedCallback (preferably in a finally block):
((SmtpClient)sender).SendCompleted -= SendCompletedCallback;
If that doesn't help you, perhaps you can post more details - for example, what data in the event arguments is being called?
a source to share