Hughgo
Hughgo

Reputation: 1339

Mailkit How to send and check aysynchronous SMTP

So there are some great examples on the net of how to use Mailkit to send an email via SMTP.

Typically ending with :

client.Authenticate(theSMTPUsername,theSMTPPassword);
client.Send(emailMessage);
client.Disconnect(true);

However this is no good if async is needed :

client.Authenticate(theSMTPUsername,theSMTPPassword);
client.SendAsync(emailMessage);
client.Disconnect(true);

However, what I would like to know is when an async Send has completed, or if it does not succeed. Under .Net native libraries this is achieved with a callback (event handler).

Is it possible to define a 'Completed' callback handler for a MailKit SendAsync, and if not what is best practise to discover if it succeeded or not.

Thanks

Upvotes: 2

Views: 7142

Answers (1)

jstedfast
jstedfast

Reputation: 38618

You don't want to have code like this:

client.Authenticate(theSMTPUsername,theSMTPPassword);
client.SendAsync(emailMessage);
client.Disconnect(true);

This will disconnect before the async send operation completes.

Instead, you want to do this:

client.Authenticate(theSMTPUsername,theSMTPPassword);
await client.SendAsync(emailMessage);
client.Disconnect(true);

Of course, once you await an async task... now you don't need a Completed event :)

That said, there is a MessageSent event that you can connect to:

http://www.mimekit.org/docs/html/E_MailKit_MailTransport_MessageSent.htm

Upvotes: 8

Related Questions