Skip to content

Commit

Permalink
Added support for Smtp PickupDirectory (#11253)
Browse files Browse the repository at this point in the history
* Added support for Smtp PickupDirectory

* Add reference to the implementation outline by MailKit

Co-authored-by: Bjarke Berg <[email protected]>

Co-authored-by: Bjarke Berg <[email protected]>
  • Loading branch information
louisjrdev and bergmania authored Oct 9, 2021
1 parent 79fdb9a commit e7da855
Showing 1 changed file with 50 additions and 1 deletion.
51 changes: 50 additions & 1 deletion src/Umbraco.Infrastructure/Mail/EmailSender.cs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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,
Expand Down

0 comments on commit e7da855

Please sign in to comment.