I am working on an asp.net application for sending emails. I want to make sure that if something goes wrong, then it logs errors and move to next record. I am using SmtpClient class to send emails. but right now, If some email address is wrong, it just crashes. How to force it to move to next record ?
My code is like this:
var EmailsQueue = context.WC_EmailToolQueue.Where(t => t.EmailDate == null).ToList();
foreach (var email in EmailsQueue)
{
MailMessage message = new MailMessage();
message.From = new MailAddress(email.WC_EmailToolTemplates.SenderEmail);
message.To.Add(new MailAddress(email.Email));
message.Body = body;
message.IsBodyHtml = true;
message.Subject = subject;
using (SmtpClient smtp = new SmtpClient
{
Host = email.WC_EmailToolTemplates.Host,
Port = email.WC_EmailToolTemplates.Port,
Credentials = new NetworkCredential(email.WC_EmailToolTemplates.SMTPUser, email.WC_EmailToolTemplates.SMTPPass),
EnableSsl = email.WC_EmailToolTemplates.EnableSSL
})
try
{
smtp.Send(message);
}
catch (Exception ex) {
}
}
Regards,
Asif Hameed
You may use a
try catchblock. If the address is not valid format, theAddfunction will throw an error. If needed you may log it alsoEDIT : As per the OP’s question edit.
the below code will skip sending email to those items having a problem (bad address etc..) But executes the remaining items in loop