Sending Email to SpecifiedPickupDirectory with MailKit

I have used SmtpClient so far with ASP.NET MVC 5. To test the email sending function on the local system, I used client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;

Now I want to do the same in ASP.NET Core, which still does not have the SmtpClient class. All his search ended with MailKit . I used my send mail code, which works fine with gmail.

I don’t want to send test emails every time, and there may be many scenarios in my project where I need to send emails. How can I use the local email sending feature using MailKit. Any links or small source code will help. Thanks

+5
source share
1 answer

I'm not sure about the details of how SmtpDeliveryMethod.SpecifiedPickupDirectory works and what it does for sure, but I suspect that it could just save the message in a directory where the on-premises Exchange server periodically checks the mail for sending.

Assuming a 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 code snippet above uses Guid.NewGuid () as a way to generate a temporary file name, but you can use whatever method you want (for example, you can also use message.MessageId + ".eml" ).

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

+9
source

Source: https://habr.com/ru/post/1257886/


All Articles