This question already has an answer here:
- How to confirm that mail has been delivered or not? 6 answers
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();
}
}