-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathSmtpAsyncExtensions.cs
37 lines (32 loc) · 1.03 KB
/
SmtpAsyncExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System.ComponentModel;
using System.Net.Mail;
namespace Tpl;
public static class SmtpAsyncExtensions
{
public static Task SendTaskAsync(this SmtpClient mailClient, string from,
string recipients, string subject, string body)
{
var tcs = new TaskCompletionSource<object?>();
void CompletionHandler(object s, AsyncCompletedEventArgs e)
{
// Check this is the notification for our send
if (!object.ReferenceEquals(e.UserState, tcs)) { return; }
mailClient.SendCompleted -= CompletionHandler;
if (e.Cancelled)
{
tcs.SetCanceled();
}
else if (e.Error != null)
{
tcs.SetException(e.Error);
}
else
{
tcs.SetResult(null);
}
};
mailClient.SendCompleted += CompletionHandler;
mailClient.SendAsync(from, recipients, subject, body, tcs);
return tcs.Task;
}
}