From e7da8558e55fe297e7156691a79a87df2d211ea4 Mon Sep 17 00:00:00 2001 From: Louis JR <17555062+louisjrdev@users.noreply.github.com> Date: Sat, 9 Oct 2021 02:30:58 +0100 Subject: [PATCH] Added support for Smtp PickupDirectory (#11253) * Added support for Smtp PickupDirectory * Add reference to the implementation outline by MailKit Co-authored-by: Bjarke Berg Co-authored-by: Bjarke Berg --- .../Mail/EmailSender.cs | 51 ++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/src/Umbraco.Infrastructure/Mail/EmailSender.cs b/src/Umbraco.Infrastructure/Mail/EmailSender.cs index e5fbde2aacf0..4ca3506fa97c 100644 --- a/src/Umbraco.Infrastructure/Mail/EmailSender.cs +++ b/src/Umbraco.Infrastructure/Mail/EmailSender.cs @@ -1,10 +1,15 @@ // Copyright (c) Umbraco. // See LICENSE for more details. +using System; +using System.IO; using System.Net.Mail; using System.Threading.Tasks; +using MailKit.Net.Smtp; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using MimeKit; +using MimeKit.IO; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Events; using Umbraco.Cms.Core.Mail; @@ -70,12 +75,56 @@ private async Task SendAsyncInternal(EmailMessage message, string emailType, boo } } - if (_globalSettings.IsSmtpServerConfigured == false) + var isPickupDirectoryConfigured = !string.IsNullOrWhiteSpace(_globalSettings.Smtp?.PickupDirectoryLocation); + + if (_globalSettings.IsSmtpServerConfigured == false && !isPickupDirectoryConfigured) { _logger.LogDebug("Could not send email for {Subject}. It was not handled by a notification handler and there is no SMTP configured.", message.Subject); return; } + if (isPickupDirectoryConfigured && !string.IsNullOrWhiteSpace(_globalSettings.Smtp?.From)) + { + // The following code snippet is the recommended way to handle PickupDirectoryLocation. + // See more https://github.com/jstedfast/MailKit/blob/master/FAQ.md#q-how-can-i-send-email-to-a-specifiedpickupdirectory + do { + var path = Path.Combine(_globalSettings.Smtp?.PickupDirectoryLocation, Guid.NewGuid () + ".eml"); + Stream stream; + + try + { + stream = File.Open(path, FileMode.CreateNew); + } + catch (IOException) + { + if (File.Exists(path)) + { + continue; + } + throw; + } + + try { + using (stream) + { + using var filtered = new FilteredStream(stream); + filtered.Add(new SmtpDataFilter()); + + FormatOptions options = FormatOptions.Default.Clone(); + options.NewLineFormat = NewLineFormat.Dos; + + await message.ToMimeMessage(_globalSettings.Smtp?.From).WriteToAsync(options, filtered); + filtered.Flush(); + return; + + } + } catch { + File.Delete(path); + throw; + } + } while (true); + } + using var client = new SmtpClient(); await client.ConnectAsync(_globalSettings.Smtp.Host,