发送电子邮件的任务中的BCC电子邮件地址异常处理

时间:2015-08-11 15:22:31

标签: c# task-parallel-library

我设置了一个异步发送电子邮件的任务,并尝试针对发送电子邮件失败的电子邮件地址处理异常。它成功注销了异常但我想知道我是否能够从密件抄送列表中注销电子邮件地址,导致异常发生。以下是我的代码,对此的任何建议都会有所帮助

public void SendEmail(string from, string copyToSender, List<string> bccRecipient, string subject, string body, SmtpSection smtpSection)
{
    var context = HttpContext.Current;

    if (smtpSection != null)
    {
        Task.Factory.StartNew(() =>
        {
            var mailMessage = new MailMessage();
            mailMessage.From = new MailAddress(from, smtpSection.Network.TargetName);
            mailMessage.Subject = subject;
            mailMessage.Body = body;
            mailMessage.IsBodyHtml = true;

            myMailMessage = mailMessage;

            //send emails to which to Bcc'd including the From Person Email
            myMailMessage.Bcc.Add(copyToSender);
            foreach (var r in bccRecipient)
            {
                myMailMessage.Bcc.Add(r);
            }
            //incorrect email address added to log out the exception against it 
            myMailMessage.Bcc.Add("foo");

            using (var client = new SmtpClient())
            {
                client.Host = smtpSection.Network.Host;
                client.EnableSsl = smtpSection.Network.EnableSsl;
                client.Port = Convert.ToInt32(smtpSection.Network.Port);
                client.Credentials = new NetworkCredential(smtpSection.Network.UserName,
                    smtpSection.Network.Password);
                client.Send(mailMessage);
            }

        }).ContinueWith(tsk =>
        {
            var recipientEmail=//how to figure this out??
            //something broke
            var flattened = tsk.Exception.Flatten();

            flattened.Handle(ex =>
            {
                _mailLogger.LogError
                  (recipientEmail, context.Request.UrlReferrer.OriginalString, ex.Message);
                return true;
            });
        }, TaskContinuationOptions.OnlyOnFaulted); ;
    }
}

0 个答案:

没有答案