17
votes

I was using SmtpClient till now with ASP.NET MVC 5. For testing email send functionality on local system, I was using client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;

Now, I want to do the same things in ASP.NET Core which does not have SmtpClient class implemented till now. All search for this ended up on MailKit. I have used their send mail code which is working fine with gmail.

I do not want to send testing emails each time and there may be a lot of scenarios in my project where I need to send email. How can I use the local email sending functionality with MailKit. Any links or little source code will help. Thanks

1

1 Answers

23
votes

I'm not sure on the finer details of how SmtpDeliveryMethod.SpecifiedPickupDirectory works and what it does exactly, but I suspect it might just save the message in a directory where the local Exchange server periodically checks for mail to send out.

Assuming that's the case, you could do something like this:

void SaveToPickupDirectory (MimeMessage message, string pickupDirectory)
{
    do {
        // Note: this will require that you know where the specified pickup directory is.
        var path = Path.Combine (pickupDirectory, Guid.NewGuid ().ToString () + ".eml");

        if (File.Exists (path))
            continue;

        try {
            using (var stream = new FileStream (path, FileMode.CreateNew)) {
                message.WriteTo (stream);
                return;
            }
        } catch (IOException) {
            // The file may have been created between our File.Exists() check and
            // our attempt to create the stream.
        }
    } while (true);
}

The above code snippet uses Guid.NewGuid () as a way of generating a temporary filename, but you can use whatever method you want (e.g. you could also opt to use message.MessageId + ".eml").

Based on Microsoft's referencesource, when SpecifiedPickupDirectory is used, they actually also use Guid.NewGuid ().ToString () + ".eml", so that's probably the way to go.