我正在使用下面的代码发送电子邮件,它在大多数情况下都可以正常工作,并且在测试期间我们发现有时它不会发送电子邮件。我如何更改此代码以检查电子邮件传递状态或字体任何其他故障。
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();
}
}