private static async Task SendMailExImplAsync( System.Net.Mail.SmtpClient client, System.Net.Mail.MailMessage message, CancellationToken token) { token.ThrowIfCancellationRequested(); var tcs = new TaskCompletionSource <bool>(); System.Net.Mail.SendCompletedEventHandler handler = null; Action unsubscribe = () => client.SendCompleted -= handler; handler = async(s, e) => { unsubscribe(); // a hack to complete the handler asynchronously await Task.Yield(); if (e.UserState != tcs) { tcs.TrySetException(new InvalidOperationException("Unexpected UserState")); } else if (e.Cancelled) { tcs.TrySetCanceled(); } else if (e.Error != null) { tcs.TrySetException(e.Error); } else { tcs.TrySetResult(true); } }; client.SendCompleted += handler; try { client.SendAsync(message, tcs); using (token.Register(() => client.SendAsyncCancel(), useSynchronizationContext: false)) { await tcs.Task; } } finally { unsubscribe(); } }
public void SendAsync(System.Net.Mail.SendCompletedEventHandler ac) { //使用指定的邮件地址初始化MailAddress实例 MailAddress maddr = new MailAddress(mailFrom); //初始化MailMessage实例 MailMessage myMail = new MailMessage(); //向收件人地址集合添加邮件地址 if (mailToArray != null) { for (int i = 0; i < mailToArray.Length; i++) { myMail.To.Add(mailToArray[i].ToString()); } } //向抄送收件人地址集合添加邮件地址 if (mailCcArray != null) { for (int i = 0; i < mailCcArray.Length; i++) { myMail.CC.Add(mailCcArray[i].ToString()); } } //发件人地址 myMail.From = maddr; //电子邮件的标题 myMail.Subject = mailSubject; //电子邮件的主题内容使用的编码 myMail.SubjectEncoding = Encoding.UTF8; //电子邮件正文 myMail.Body = mailBody; //电子邮件正文的编码 myMail.BodyEncoding = Encoding.Default; myMail.Priority = MailPriority.High; myMail.IsBodyHtml = isbodyHtml; //在有附件的情况下添加附件 try { if (attachmentsPath != null && attachmentsPath.Length > 0) { Attachment attachFile = null; foreach (string path in attachmentsPath) { attachFile = new Attachment(path); myMail.Attachments.Add(attachFile); } } } catch (Exception err) { throw new Exception("在添加附件时有错误:" + err); } SmtpClient smtp = new SmtpClient(); //指定发件人的邮件地址和密码以验证发件人身份 smtp.Credentials = new System.Net.NetworkCredential(mailFrom, mailPwd); //设置SMTP邮件服务器 smtp.Host = host; smtp.Port = port; smtp.EnableSsl = true; smtp.SendCompleted += ac; smtp.SendAsync(myMail, null); }