TLDR; Which of the following (or otherwise) is most suitable for sending 300-500 emails quickly to an external mail server?
I'm amending code for sending emails to now use an external sender (e.g. MailGun, SendGrid etc.) instead of HMailServer which is currently installed on the same server as the application. This is obviously introducing latency.
I've read the documentation for all of the above, but am struggling to fully understand the implications (particularly the gotcha's) of each. There seems to be very differing opinions about whether the above are suitable or not, particularly:
- If I have to await each email, then is that not simulating the current sync approach?
- I'm trying to use a single instance of the SmptClient object, for speed and efficiency
- Based on extensive reading today, many examples I've seen are old, and may not use the latest .Net capabilities
I'd welcome input please from people who have actually achieved this successfully. Naturally I can go write code for each, but I'm looking for experienced people to guide me on the right path to begin with here.
My simplified (existing sync) code is as follows:
var sb = new StringBuilder();
using (var mc = new SmtpClient() {
Host = "127.0.0.1", // Current HMailServer installation - will be changed to external API
DeliveryMethod = SmtpDeliveryMethod.Network,
Port = 25,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("Username", "Password")
})
{
foreach(var result in GetData())
{
using(var mm = new MailMessage())
{
mm.To.Add(new MailAddress(result.Email, result.FirstName + " " + result.Surname));
mm.Subject = "Your monthly report";
mm.From = new MailAddress("noreply@example.com");
mm.ReplyToList.Add(new MailAddress(result.Email));
// Email body constructed here for each individual recipient
mm.Body = sb.ToString();
sb.Clear();
mc.Send(mm);
}
}
}