using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

namespace TaskExamples
{
    // Listing 17-22
    public static class SmtpAsyncExtensions
    {
        public static Task SendTaskAsync(this SmtpClient mailClient, string from,
                                   string recipients, string subject, string body)
        {
            var tcs = new TaskCompletionSource<object>();

            SendCompletedEventHandler completionHandler = null;
            completionHandler = (s, e) =>
            {
                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, null);

            return tcs.Task;
        }
    }

}
