检查电子邮件的失败响应

时间:2016-03-31 07:34:32

标签: asp.net email smtp

如何使用Asp.Net检查电子邮件发送方法中的失败响应。 问题是我没有得到失败的例外。
请提出更好的建议。

这是我的代码,我正在尝试访问电子邮件失败例外...

public static bool sendMail(string strTo, string strSubject, string strName, string strbody)
{
    try
    {
        strName = strName == "" ? "Sir/Madam" : ("Dear " + strName + ",");
        StringBuilder mailbody = new StringBuilder();
        SmtpClient mailClient = null;
        MailMessage message = null;
        mailClient = new SmtpClient();
        message = new MailMessage();

        mailClient.Host = ConfigurationManager.AppSettings["SMTP_MAIL_SERVER"];
        mailClient.Port = int.Parse(ConfigurationManager.AppSettings["PORT"]);
        //network credentials
        string strMailUserName = ConfigurationManager.AppSettings["FROM_ADDR"];
        string strMailPassword = ConfigurationManager.AppSettings["FROM_ADDR_PASS"];
        string strWebSiteURL = ConfigurationManager.AppSettings["LinkTosite"];

        mailClient.EnableSsl = true;
        System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(strMailUserName, strMailPassword);
        mailClient.UseDefaultCredentials = true;
        mailClient.Credentials = SMTPUserInfo;

        string strFromMail = ConfigurationManager.AppSettings["FROM_ADDR"];
        MailAddress fromAddress = new MailAddress(strFromMail, "TEST (Administrator)");
        message.From = fromAddress;

        message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.OnSuccess;

        //to mail address
        message.To.Add(strTo);
        message.Subject = "ChatOnGo : " + strSubject;

        //mailbody.AppendFormat("<link href='" + strWebSiteURL + "admin/css/bestlogin.css' rel='stylesheet' type='text/css' />");
        mailbody.AppendFormat("<div class='dlogin_bg'><div class='dlogin_bg_top'></div><div class='dlogin_bg_bottom'><h2>" + strName + "</h2>");
        mailbody.AppendFormat(strbody);
        mailbody.AppendFormat("<br/><br/><span>Regards,<br /><a href='" + strWebSiteURL + "'>ChatOnGo Admin</a></span></div></div>");

        message.Body = mailbody.ToString();
        message.IsBodyHtml = true;
        mailClient.SendMailAsync(message);


        message = null;
        mailClient = null;

        return true;
    }
    catch (SmtpFailedRecipientsException ep)
    {
        Console.WriteLine(ep.Message);
        return false;
    }
    catch (Exception ep)
    {
        Console.WriteLine(ep.Message);
        return false;
    }
}

2 个答案:

答案 0 :(得分:0)

我不确定但您可以尝试在没有Async(SendMailAsync)的情况下发送邮件,只是尝试调用普通的send方法,可能会获得异常详细信息。

答案 1 :(得分:0)

我假设你使用gmail发送电子邮件。 您应该至少发送一次电子邮件,如果电子邮件无效,您将收到失败通知。 您可以创建每晚/每小时的作业来检查这些失败的电子邮件,并在数据库中将其标记为无效。

以下是以编程方式阅读电子邮件的链接:

http://www.aspsnippets.com/Articles/Fetch-and-read-email-messages-with-attachments-from-GMAIL-POP3-mail-server-in-ASPNet.aspx

我希望这有帮助!