Skip to content

Instantly share code, notes, and snippets.

@RichardD2
Forked from mattbenic/SmtpClientExtensions.cs
Last active January 28, 2019 10:35
Show Gist options
  • Save RichardD2/27ce7cfd57bc5e3f2b904a8cdc855a5a to your computer and use it in GitHub Desktop.
Save RichardD2/27ce7cfd57bc5e3f2b904a8cdc855a5a to your computer and use it in GitHub Desktop.
Extension method to have SmtpClient's SendMailAsync respond to a CancellationToken
using System;
using System.ComponentModel;
using System.Net.Mail;
using System.Threading;
using System.Threading.Tasks;
public static class SmtpClientExtensions
{
/// <summary>
/// Sends the specified message to an SMTP server for delivery as an asynchronous operation.
/// </summary>
/// <param name="client">
/// The <see cref="SmtpClient"/> instance.
/// </param>
/// <param name="message">
/// The <see cref="MailMessage"/> to send.
/// </param>
/// <param name="cancellationToken">
/// The <see cref="CancellationToken"/> to monitor for cancellation requests.
/// </para>
/// <returns>
/// A <see cref="Task"/> representing the asynchronous operation.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="client"/> is <see langword="null"/>.</para>
/// <para>-or-</para>
/// <para><paramref name="message"/> is <see langword="null"/>.</para>
/// </exception>
public static Task SendMailAsync(this SmtpClient client, MailMessage message, CancellationToken cancellationToken)
{
if (client == null) throw new ArgumentNullException(nameof(client));
if (message == null) throw new ArgumentNullException(nameof(message));
if (!cancellationToken.CanBeCanceled) return client.SendMailAsync(message);
var tcs = new TaskCompletionSource<object>();
var registration = default(CancellationTokenRegistration);
SendCompletedEventHandler handler = null;
handler = SendCompleted;
client.SendCompleted += handler;
try
{
client.SendAsync(message, tcs);
registration = cancellationToken.Register(client.SendAsyncCancel);
}
catch
{
client.SendCompleted -= handler;
registration.Dispose();
throw;
}
return tcs.Task;
void SendCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.UserState == tcs)
{
try
{
if (handler != null)
{
client.SendCompleted -= handler;
handler = null;
}
}
finally
{
registration.Dispose();
if (e.Error != null)
{
tcs.TrySetException(e.Error);
}
else if (e.Cancelled)
{
tcs.TrySetCanceled();
}
else
{
tcs.TrySetResult(null);
}
}
}
}
}
}
@RichardD2
Copy link
Author

This should really be baked in to the BCL.

UserVoice suggestion

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment