如何检查是否电子邮件是使用C#提供MAILMESSAGE [英] How to check if email was delivered using C# MailMessage

查看:207
本文介绍了如何检查是否电子邮件是使用C#提供MAILMESSAGE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用低于code发送电子邮件,它工作正常大部分的时间和放大器;测试过程中,我们发现有时不提供电子邮件。我怎样才能改变这种code,检查电子邮件传送状态或字体的任何其它故障。

 公共静态无效SendEmail(字符串,字符串主题,字符串消息,布尔isHtml)
        {
            尝试
            {
            VAR邮件= MAILMESSAGE新();            //设置收件人和发件人地址。
            //将地址必须是您的Gmail帐户
            mail.From =新的MailAddress(noreplyXYZ@gmail.com);
            mail.To.Add(新MailAddress(到));            //定义消息
            mail.Subject =主体;
            mail.IsBodyHtml = isHtml;
            mail.Body =消息;            //使用谷歌的服务器上创建一个新的客户端SMPT
            VAR的MailCli​​ent =新SmtpClient();
            mailclient.Host =smtp.gmail.com; // ForGmail
            mailclient.Port = 587; // ForGmail
            //这是关键的部分,必须启用SSL
            mailclient.EnableSsl = TRUE; // ForGmail
            //mailclient.EnableSsl = FALSE;
            mailclient.UseDefaultCredentials = TRUE;            //指定你的验证信息
            mailclient.Credentials =新System.Net.NetworkCredential(noreplyXYZ@gmail.com,xxxx123); // ForGmail
            mailclient.Send(邮件);
            mailclient.Dispose();
    }
                    赶上(异常前)
                    {
    扔恩;
                        }
    }

我知道SMTP负责发送电子邮件和放大器;它是不可能的传递状态,但是他们的周围的方式来检查电子邮件递送的状态

修订code (这是正确的)

 公共静态无效SendEmail(字符串,字符串主题,字符串消息,布尔isHtml)
{
    VAR邮件= MAILMESSAGE新();    //设置收件人和发件人地址。
    //将地址必须是您的Gmail帐户
    mail.From =新的MailAddress(noreplyXYZ@gmail.com);
    mail.To.Add(新MailAddress(到));    //定义消息
    mail.Subject =主体;
    mail.IsBodyHtml = isHtml;
    mail.Body =消息;    //使用谷歌的服务器上创建一个新的客户端SMPT
    VAR的MailCli​​ent =新SmtpClient();
    mailclient.Host =smtp.gmail.com; // ForGmail
    mailclient.Port = 587; // ForGmail    mailclient.EnableSsl = TRUE; // ForGmail
    //mailclient.EnableSsl = FALSE;
    mailclient.UseDefaultCredentials = TRUE;    //指定你的验证信息
    mailclient.Credentials =新System.Net.NetworkCredential(noreplyXYZ@gmail.com,xxxx123); // ForGmail
    mailclient.Send(邮件);
    mailclient.Dispose();
    尝试
    {
        mailclient.Send(邮件);
        mailclient.Dispose();
    }
    赶上(SmtpFailedRecipientsException前)
    {
        的for(int i = 0; I< ex.InnerExceptions.Length;我++)
        {
            SmtpStatus code状态= ex.InnerExceptions [I] .STATUS code;
            如果(状态== SmtpStatus code.MailboxBusy ||状态== SmtpStatus code.MailboxUnavailable)
            {
                ; - // Console.WriteLine(在5秒内重试传递失败。)
                System.Threading.Thread.Sleep(5000);
                mailclient.Send(邮件);
            }
            其他
            {
                // Console.WriteLine(无法传递消息给{0},ex.InnerExceptions [I] .FailedRecipient);
                扔恩;
            }
        }
    }
    赶上(异常前)
    {
        // Console.WriteLine(异常陷入RetryIfBusy(){0},ex.ToString());
        扔恩;
    }
    最后
    {
        mailclient.Dispose();
    }}


解决方案

好了,你有code的整个身体包裹在一个尝试与空封锁块。因此,如果消息无法发送不管什么原因,你将有不知道,因为你的函数将简单地返回。

如果你看一下MSDN文档 SmtpClient.Send 你会看到有一些不同的异常它可以抛出各种原因的。一对夫妇有趣的:


您的更新后,有两点要注意:

您可能并不想这样做:

  mailclient.Send(邮件);
mailclient.Dispose();
尝试
{
    mailclient.Send(邮件);
    mailclient.Dispose();
}

您正在处理的MailCli​​ent 之前试图再次使用它。

使用

MAILMESSAGE SmtpClient 都实现的 的IDisposable ,所以这将是最好的做法(也是最容易),以将它们放入一个的 使用 块:

 使用(VAR邮件= MAILMESSAGE新())
使用(VAR的MailCli​​ent =新SmtpClient())
{
    // ...
}

然后,你将不必担心调用的Dispose()最后块(你可能不需要他们在所有的话)。

罚球

您可能知道,但没有点:

 赶上(异常前)
{
    扔恩;
}

的foreach

 的for(int i = 0; I< ex.InnerExceptions.Length;我++)
{
    SmtpStatus code状态= ex.InnerExceptions [I] .STATUS code;
    // ...
}

可再写成:

 的foreach(在ex.InnerExceptions VAR innerEx)
{
    VAR状态= innerEx.Status code;
}

Thread.sleep代码()

如果这个code是面向用户的,你可能真的不希望这样做,因为它会导致页面挂5秒等待发送。在我看来,你不应该处理直接在网页code发送邮件,无论如何,你应该排队它为一个后台任务发送。但是,这是一个完全不同的问题。

只是几件事情让您有一个更好的C#codeR。

I am using below code to send email it works fine most of the time & during test we found sometimes it doesn't deliver email. How can i alter this code to check the email delivery status or font any other failure.

        public static void SendEmail(string to, string subject, string message, bool isHtml)
        {
            try
            {
            var mail = new MailMessage();

            // Set the to and from addresses.
            // The from address must be your GMail account
            mail.From = new MailAddress("noreplyXYZ@gmail.com");
            mail.To.Add(new MailAddress(to));

            // Define the message
            mail.Subject = subject;
            mail.IsBodyHtml = isHtml;
            mail.Body = message;

            // Create a new Smpt Client using Google's servers
            var mailclient = new SmtpClient();
            mailclient.Host = "smtp.gmail.com";//ForGmail
            mailclient.Port = 587; //ForGmail


            // This is the critical part, you must enable SSL
            mailclient.EnableSsl = true;//ForGmail
            //mailclient.EnableSsl = false;
            mailclient.UseDefaultCredentials = true;

            // Specify your authentication details
            mailclient.Credentials = new System.Net.NetworkCredential("noreplyXYZ@gmail.com", "xxxx123");//ForGmail
            mailclient.Send(mail);
            mailclient.Dispose();
    }
                    catch (Exception ex)
                    {
    throw ex;
                        }
    }

I know SMTP is responsible for sending email & it is not possible to delivery status but is their a way around to check the status of the email delivery

UPDATED CODE (is this correct)

public static void SendEmail(string to, string subject, string message, bool isHtml)
{
    var mail = new MailMessage();

    // Set the to and from addresses.
    // The from address must be your GMail account
    mail.From = new MailAddress("noreplyXYZ@gmail.com");
    mail.To.Add(new MailAddress(to));

    // Define the message
    mail.Subject = subject;
    mail.IsBodyHtml = isHtml;
    mail.Body = message;

    // Create a new Smpt Client using Google's servers
    var mailclient = new SmtpClient();
    mailclient.Host = "smtp.gmail.com";//ForGmail
    mailclient.Port = 587; //ForGmail

    mailclient.EnableSsl = true;//ForGmail
    //mailclient.EnableSsl = false;
    mailclient.UseDefaultCredentials = true;

    // Specify your authentication details
    mailclient.Credentials = new System.Net.NetworkCredential("noreplyXYZ@gmail.com", "xxxx123");//ForGmail
    mailclient.Send(mail);
    mailclient.Dispose();
    try
    {
        mailclient.Send(mail);
        mailclient.Dispose();
    }
    catch (SmtpFailedRecipientsException ex)
    {
        for (int i = 0; i < ex.InnerExceptions.Length; i++)
        {
            SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
            if (status == SmtpStatusCode.MailboxBusy ||status == SmtpStatusCode.MailboxUnavailable)
            {
                // Console.WriteLine("Delivery failed - retrying in 5 seconds.");
                System.Threading.Thread.Sleep(5000);
                mailclient.Send(mail);
            }
            else
            {
                //  Console.WriteLine("Failed to deliver message to {0}", ex.InnerExceptions[i].FailedRecipient);
                throw ex;
            }
        }
    }
    catch (Exception ex)
    {
        //  Console.WriteLine("Exception caught in RetryIfBusy(): {0}",ex.ToString());
        throw ex;
    }
    finally
    {
        mailclient.Dispose();
    }

}

解决方案

Well, you have the entire body of code wrapped in a try block with an empty catch block. So, if the message fails to send for whatever reason, you will have no idea because your function will simply return.

If you look at the MSDN documentation for SmtpClient.Send you'll see that there are a number of different exceptions it can throw for various reasons. A couple interesting ones:


A couple of notes after your update:

You probably don't mean to do this:

mailclient.Send(mail);
mailclient.Dispose();
try
{
    mailclient.Send(mail);
    mailclient.Dispose();
}

You're disposing mailclient before trying to use it again.

using

MailMessage and SmtpClient both implement IDisposable, so it would be best practice (and easiest) to put them in a using block:

using (var mail = new MailMessage())
using (var mailclient = new SmtpClient())
{
    // ...
}

Then you won't have to worry about calling Dispose() in your finally blocks (you may not need them at all then).

throw

You're probably aware, but there's no point in:

catch (Exception ex)
{
    throw ex; 
}

foreach

for (int i = 0; i < ex.InnerExceptions.Length; i++)
{
    SmtpStatusCode status = ex.InnerExceptions[i].StatusCode;
    // ... 
}

Can be re-written as:

foreach (var innerEx in ex.InnerExceptions)
{
    var status = innerEx.StatusCode;
}

Thread.Sleep()

If this code is user-facing, you probably don't really want to do this, as it is going to cause the page to hang for 5 seconds waiting to send. In my opinion, you shouldn't handle sending mail directly in the web page code anyway, you should queue it up for a background task to send. But that's an entirely different issue.

Just a few things to help make you a better C# coder.

这篇关于如何检查是否电子邮件是使用C#提供MAILMESSAGE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆