这个问题已经在这里有一个答案:
- 如何确认邮件已送达或不? 6个回答
我使用下面的代码来发送电子邮件,它工作正常的大部分时间和测试过程中,我们发现有时不提供电子邮件。 我怎样才能改变这种代码来检查电子邮件传递状态或字体的任何其他故障。
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;
}
}
我知道SMTP是负责发送电子邮件和它是不可能到交货状态,但他们是围绕一个方法来检查电子邮件传递的状态
更新后的代码 (这是正确的)
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();
}
}