I'm implementing email server in asp.net core 2.0 with mailkit. About my scenario, I have to send email and need to return feedback with the email sent status.I have implemented email send part and it's working fine.
I know try catch is a one option.But it's not enough with my situation. Because exception will be occurred only when network error or authentication failure. But exception won't occur if some receiver email is invalid.
I have to return email sent status for each email in List.But If there is invalid email or another error I can't catch it.
I saw a event called MessageSent. But I don't know to implement that event and whether it's match with my condition.
This is my full code.
public void SendEmail(List<EmailMessage> emailMessages)
{
List<MimeMessage> emailQueue = new List<MimeMessage>();
foreach (EmailMessage emailMessage in emailMessages)
{
var message = new MimeMessage();
message.MessageId = emailMessage.MessageId;
message.To.AddRange(emailMessage.ToAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
message.From.AddRange(emailMessage.FromAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
message.Subject = emailMessage.Subject;
message.Body = new TextPart(TextFormat.Html)
{
Text = emailMessage.Content
};
emailQueue.Add(message);
}
using (var emailClient = new SmtpClient())
{
emailClient.Connect(_emailConfiguration.SmtpServer, _emailConfiguration.SmtpPort, _emailConfiguration.EnableSSL);
emailClient.AuthenticationMechanisms.Remove("XOAUTH2");
emailClient.Authenticate(_emailConfiguration.SmtpUsername, _emailConfiguration.SmtpPassword);
foreach (MimeMessage email in emailQueue)
{
try
{
emailClient.Send(email);
}
catch (Exception ex)
{
}
}
emailClient.Disconnect(true);
}
}