Reputation: 1020
I want to get- and handle exceptions when the MailKit SmtpClient.Send() fails to send to an invalid email. But it doesn't throw any exceptions.
I have tried sending to an invalid email on purpose to see if I can catch any exceptions. Does the MailKit SmtpClient simply not throw any exceptions when failing to send? In case you wonder why I need this, is that I want to return an error message to a client application that some emails were invalid.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using MyProject.Backend.Models;
using MailKit.Net.Smtp;
using MimeKit;
using MimeKit.Text;
namespace MyProject.Backend.Helpers
{
public class SMTPHelper
{
SMTPSettings smtpSettings;
public SMTPHelper(SMTPSettings smtpSettings)
{
this.smtpSettings = smtpSettings;
}
public List<string> Send(List<PreparedEmailModel> preparedEmails)
{
using (var emailClient = new SmtpClient())
{
var failedEmails = new List<string>();
//The last parameter here is to use SSL (Which you should!)
emailClient.Connect(smtpSettings.Host, 587);
//Remove any OAuth functionality as we won't be using it.
emailClient.AuthenticationMechanisms.Remove("XOAUTH2");
emailClient.Authenticate(smtpSettings.CredentialsUser, smtpSettings.CredentialsPassword);
foreach (var preparedEmail in preparedEmails)
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress(preparedEmail.FromEmail));
message.To.Add(new MailboxAddress(preparedEmail.ToEmail));
message.Subject = preparedEmail.Subject;
//We will say we are sending HTML. But there are options for plaintext etc.
message.Body = new TextPart(TextFormat.Html)
{
Text = preparedEmail.Body
};
try
{
emailClient.Send(message);
}
catch (Exception e)
{
failedEmails.Add(preparedEmail.ToEmail);
}
}
emailClient.Disconnect(true);
return failedEmails;
}
}
}
}
Expected: MailKit SmtpClient.Send() should generate an exception when sending to an invalid email address.
Result: No exceptions are thrown even when trying with an invalid made-up email address.
Upvotes: 0
Views: 3597
Reputation: 23820
Let's say you go to the post office. You put an envelope in the mailbox, addressed to a non-existent address.
Does the mailbox shoot it back at you, and say it doesn't exist? No.
The post office sends it somewhere, they try and deliver it, they fail and eventually it comes back to you.
Email works basically the same way. You don't know at send time if the target email address is legitimate or not.
As such, your code is working as expected.
If you care deeply about this stuff, you need to do bounce processing - but the bounce might arrive days later, or never. This is not a small job (I work at a company that specialises in that kind of thing).
Upvotes: 5