My method for sending emails with Send()
is getting very slow when I send more than ten messages.
Sample
1 (1 sec)
2 (2 sec)
3 (4 sec)
4 (8 sec) and so on...
so I started to try SendAsync()
public Boolean sendSMTPMail(string subject, string body, customer[] recipients, string attachmentFileName = null)
{
string css = "<style>*{font-family: Arial, Helvetica, sans-serif;}</style>";
SmtpClient client = new SmtpClient();
//some client settings..
MailMessage mm = new MailMessage();
mm.IsBodyHtml = true;
mm.From = new MailAddress(MainForm.from, MainForm.fromName, Encoding.UTF8);
mm.Subject = subject;
foreach (var recipient in recipients)
{
Application.DoEvents();
mm.To.Clear();
mm.To.Add(new MailAddress(recipient.getEmail()));
mm.AlternateViews.Add(getEmbeddedImages(css + doReplacements(body, recipient)));
try
{
//client.Send(mm);
client.SendAsync(mm, "userToken");
//client.SendMailAsync(mm);
}
catch (Exception)
{
return false;
}
}
return true;
}
Additional Information about my methods:
getEmbeddedImages
replaces imagePath
with needed cid:xxxx
and adds the image so it can be sent as a part of the email and not only as attachment.
doReplacements
replaces strings in my body to get the email text more recipient specific:
Hello my name is %name%,
I am %age% years old.
will be translated to
Hello my name is John Doe,
I am 100 years old.
Questions:
- Is this the right way to do it?
- Is it important to send different userTokens?
- For what is this token needed anyway? Obviously it doesn't matter what I fill in there.