1

We have implemented our own customized bulk email software. For three years we used it with a local Exchange server and never had any issues. A few months ago we switched to Office 365 and now have the problem that every now and then the email sending suddenly stops.

I have copied a sketch of the code below. We use SmtpClient.SendMailAsync from System.Net.Mail. Since we need to be able to throttle the amount of emails per minute, we have a timer that is enabled after each successfully sent email and triggers the next email. At random times the process stops with the log output of the line marked with ***. So it looks as if SendMailAsync never returns and the lines after never get executed. No error message, nothing. The program itself does not look crashed or deadlocked, though.

Any idea if there could be something wrong with our code? How could it be that SendMailAsync never returns?

private async Task SendEmailAsync(Recipient recipient)
{
    MailMessage mm = new MailMessage();
    ...
    System.Net.NetworkCredential creds = new System.Net.NetworkCredential();
    ...

    using (SmtpClient sc = new SmtpClient(Host, Port))
    {
        sc.EnableSsl = UseSSL;
        sc.UseDefaultCredentials = false;
        sc.Credentials = creds;

        mm.Body = ...
        mm.To.Add(recipient.Adress);

        progressViewModel.Log($"Sending e-mail to: {recipient.Adress} ..."); ***

        await sc.SendMailAsync(mm);

        progressViewModel.Log($"... Sent e-mail to: {recipient.Adress}");
    }
}


private async void StartNextEmail()
{
    try
    {
        timer.IsEnabled = false;

        //check aborted or completed
        ...

        Recipient currentRecipient = ...

        await SendEmailAsync(currentRecipient);

        timer.IsEnabled = true;
    }
    catch (SmtpException ex)
    {
        //failed, implement retry logic
        ...
        timer.IsEnabled = true;
    }
    catch (Exception ex)
    {
        //unexpected error, abort 
        ...
    }
}


private void timer_Tick(object sender, EventArgs e)
{
    StartNextEmail();
}
NicolasR
  • 2,222
  • 3
  • 23
  • 38
  • 1
    see if [this](https://stackoverflow.com/a/28445791/1768303) helps – noseratio Jan 30 '18 at 12:25
  • Thanks, I will try it in three weeks when we send our next newsletter. It's hard to test because for 8000 recipients it happens on average between 2 and 5 times. Just one question: is your solution valid for desktop apps in the same way? – NicolasR Jan 30 '18 at 16:10
  • You should be able to use it in a desktop app the same way as the underlying `SmtpClient.SendAsync` API is the same. – noseratio Jan 30 '18 at 21:10

0 Answers0