SecureMail async send example

0 votes
asked Dec 18, 2015 by mrblint (340 points)

I'm new at async coding in C#, so I was wondering if there's an AsyncSend example for SecureMail? I've looked here, but I'm not sure how to adapt those code examples to the Send method. With the System.Net.Mail library, I listened for a SendCompleted event with an anonymous handler:

object userState = myMail;
  smtp.SendCompleted += (sender, e) => {

     MailMessage email = (MailMessage) e.UserState;
     if (e.Cancelled)...
      {}
     else
      {
       if  (e.Error != null) ...
      }
      else
      {
           //success
       }

}
Applies to: Rebex Secure Mail

1 Answer

0 votes
answered Dec 21, 2015 by Martin Vobr (12,900 points)

The most convenient way is to use await keyword from .NET 4.5 or later. See following code:

static void Main(string[] args)
{
    SendMail().Wait();
}
private static async Task SendMail()
{
    var message = new MailMessage();
    message.From = "from@example.com"; 
    message.To = "to@example.com";
    message.Subject = "Async hello";

    using (var smtp = new Smtp())
    {
        await smtp.ConnectAsync("smtp.example.com");
        await smtp.SendAsync(message);
    }
}

You can also check source code of WinForm Mail Sender app for other ways how to asynchronously send email.

commented Dec 21, 2015 by Martin Vobr (12,900 points)
If you cannot use 'await' keyword and need a sample code for older framework version just let me know.
commented Dec 22, 2015 by mrblint (340 points)
Thank you.  I will look at the source of the WinForm Mail Sender app. My task is to write an automated event-attendance reminder app. The main requirements are 1)  send  recipient-specific content  to as many as 100 different recipients, in a batch in the background so the user's GUI is not blocked) and 2) after each email has been sent, grab its recipient and a few other details and note the send date-time  in a database .
commented Dec 23, 2015 by Martin Vobr (12,900 points)
Source code for the WinForm  MailSender application is included in the trial installation package. Just download installer from http://www.rebex.net/secure-mail.net/download.aspx and run it. The default target folder for samples is "c:\Users\yourUserName\Documents\Rebex Components 2015 R4.1 - Samples\vs2012-net-4.5\Mail\MailSendWinForm_CS"
...