检查电子邮件发送失败asp.net c#

时间:2014-09-01 09:28:36

标签: c# asp.net

这是我的C#代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
        client.EnableSsl = true;
        client.Credentials = new System.Net.NetworkCredential("xyz@gmail.com", "password");
        MailMessage msg = new MailMessage();
        msg.From = new MailAddress("xyz@gmail.com");
        msg.To.Add(new MailAddress(TextBox1.Text));
        msg.Subject = "Testing Email";
        String Body = "This is Testing Email.";
        msg.Body = Body;
        msg.IsBodyHtml = true;
        try
        {
            client.Send(msg);
            MsgBox("Send Successfully");
        }
        catch (Exception ex)
        {
            MsgBox("deleivery failed" + ex.ToString());
        }
    }
}

问题在于,当我在TextBox1中输入正确的电子邮件ID时,会出现“成功发送”警报,并且没有错误消息 当我在TextBox1中输入错误的电子邮件ID(如12345xyz@gmail.com)时,还会显示发送成功的警报,并且没有错误消息,我收到一封电子邮件,电子邮件在xyz@gmail.com收件箱中发送失败。

我如何检查电子邮件是发送还是传递失败。 我正在使用ASP.Net和C#。

2 个答案:

答案 0 :(得分:0)

将您的catch块异常类型更改为

 catch (SmtpFailedRecipientsException ex)
        {
           //Show error msg
        }
  

使用。发送电子邮件时抛出SmtpFailedRecipientsException   SmtpClient并且无法发送给所有收件人

添加Using System.Net.Mail

。还要看SmtpException

答案 1 :(得分:0)

   try
{
    client.Send(msg);
    Page.RegisterStartupScript("UserMsg", "<script>alert('Successfully Send...');if(alert){ window.location='SendMail.aspx';}</script>");
}
catch (Exception ex)
{
    Exception ex2 = ex;
    string errorMessage = string.Empty;
    while (ex2 != null)
    {
        errorMessage += ex2.ToString();
        ex2 = ex2.InnerException;
    }
    Page.RegisterStartupScript("UserMsg", "<script>alert('Sending Failed...');if(alert){ window.location='SendMail.aspx';}</script>");
}

也许这会对你有帮助吗?