From c74e9008b8aaad6ea0cfc9c07a333fe5a72519ba Mon Sep 17 00:00:00 2001 From: Riku Virtanen Date: Tue, 2 Jan 2024 13:59:17 +0200 Subject: [PATCH] Implemented changes --- Frends.SMTP.SendEmail/CHANGELOG.md | 4 + .../SendEmailTests.cs | 390 +++++++++--------- .../Frends.Smtp.SendEmail.csproj | 2 +- .../Frends.Smtp.SendEmail/SendEmailTask.cs | 13 +- 4 files changed, 206 insertions(+), 203 deletions(-) diff --git a/Frends.SMTP.SendEmail/CHANGELOG.md b/Frends.SMTP.SendEmail/CHANGELOG.md index 276afc3..984ac6d 100644 --- a/Frends.SMTP.SendEmail/CHANGELOG.md +++ b/Frends.SMTP.SendEmail/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## [1.2.1] - 2024-01-02 +### Fixed +- Fixed issue with connecting to SMTP servers which do not support authentication. + ## [1.2.0] - 2023-12-21 ### Changed - Changed Task to use MailKit library instead of deprecated System.Net.Mail. diff --git a/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail.Tests/SendEmailTests.cs b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail.Tests/SendEmailTests.cs index ff381f4..6d1b335 100644 --- a/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail.Tests/SendEmailTests.cs +++ b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail.Tests/SendEmailTests.cs @@ -1,197 +1,193 @@ -using NUnit.Framework; -using System; -using System.IO; -using System.Threading.Tasks; -using Frends.SMTP.SendEmail.Definitions; - -namespace Frends.SMTP.SendEmail.Tests; - -[TestFixture] -public class SendEmailTests -{ - // ****************************************** FILL THESE ****************************************************** - private static readonly string USERNAME = Environment.GetEnvironmentVariable("Frends_SMTP_Username"); - private static readonly string PASSWORD = Environment.GetEnvironmentVariable("Frends_SMTP_Password"); - private static readonly string SMTPADDRESS = Environment.GetEnvironmentVariable("Frends_SMTP_Address"); - private static readonly string TOEMAILADDRESS = Environment.GetEnvironmentVariable("Frends_SMTP_Email"); - private static readonly string FROMEMAILADDRESS = Environment.GetEnvironmentVariable("Frends_SMTP_Email"); - private const int PORT = 587; - // ************************************************************************************************************ - - - private const string TEMP_ATTACHMENT_SOURCE = "emailtestattachments"; - private const string TEST_FILE_NAME = "testattachment.txt"; - private const string TEST_FILE_NOT_EXISTING = "doesntexist.txt"; - - private string _localAttachmentFolder; - private string _filepath; - private Input _input; - private Input _input2; - private Options _options; - - [SetUp] - public void EmailTestSetup() - { - _localAttachmentFolder = Path.Combine(Path.GetTempPath(), TEMP_ATTACHMENT_SOURCE); - - if (!Directory.Exists(_localAttachmentFolder)) - Directory.CreateDirectory(_localAttachmentFolder); - - _filepath = Path.Combine(_localAttachmentFolder, TEST_FILE_NAME); - - if (!File.Exists(_filepath)) - { - File.Create(_filepath).Dispose(); - } - - _input = new Input() - { - From = FROMEMAILADDRESS, - To = TOEMAILADDRESS, - Cc = "", - Bcc = "", - Message = "testmsg", - IsMessageHtml = false, - SenderName = "EmailTestSender", - MessageEncoding = "utf-8" - }; - - _input2 = new Input() - { - From = FROMEMAILADDRESS, - To = TOEMAILADDRESS, - Cc = null, - Bcc = null, - Message = "testmsg", - IsMessageHtml = false, - SenderName = "EmailTestSender", - MessageEncoding = "utf-8" - }; - - _options = new Options() - { - UserName = USERNAME, - Password = PASSWORD, - SMTPServer = SMTPADDRESS, - Port = PORT, - UseOAuth2 = false, - SecureSocket = SecureSocketOption.None - }; - - } - - [TearDown] - public void EmailTestTearDown() - { - if (Directory.Exists(_localAttachmentFolder)) - Directory.Delete(_localAttachmentFolder, true); - } - - [Test] - public async Task SendEmailWithPlainText() - { - var input = _input; - input.Subject = "Email test - PlainText"; - - var result = await SMTP.SendEmail(input, null, _options, default); - Assert.IsTrue(result.EmailSent); - } - - [Test] - public async Task SendEmailWithFileAttachment() - { - var input = _input; - input.Subject = "Email test - FileAttachment"; - - var attachment = new Attachment - { - AttachmentType = AttachmentType.FileAttachment, - FilePath = _filepath, - SendIfNoAttachmentsFound = false, - ThrowExceptionIfAttachmentNotFound = true - }; - - - var Attachments = new AttachmentOptions { Attachments = new Attachment[] { attachment } }; - - var result = await SMTP.SendEmail(input, Attachments, _options, default); - Assert.IsTrue(result.EmailSent); - } - - [Test] - public async Task SendEmailWithStringAttachment() - { - var input = _input; - input.Subject = "Email test - AttachmentFromString"; - var fileAttachment = new AttachmentFromString() { FileContent = "teststring � �", FileName = "testfilefromstring.txt" }; - var attachment = new Attachment() - { - AttachmentType = AttachmentType.AttachmentFromString, - StringAttachment = fileAttachment - }; - var Attachments = new AttachmentOptions { Attachments = new Attachment[] { attachment } }; - - var result = await SMTP.SendEmail(input, Attachments, _options, default); - Assert.IsTrue(result.EmailSent); - } - - [Test] - public async Task TrySendingEmailWithNoFileAttachmentFound() - { - var input = _input; - input.Subject = "Email test"; - - var attachment = new Attachment - { - FilePath = Path.Combine(_localAttachmentFolder, TEST_FILE_NOT_EXISTING), - SendIfNoAttachmentsFound = false, - ThrowExceptionIfAttachmentNotFound = false - }; - - - var Attachments = new AttachmentOptions { Attachments = new Attachment[] { attachment } }; - - var result = await SMTP.SendEmail(input, Attachments, _options, default); - Assert.IsFalse(result.EmailSent); - } - - [Test] - public async Task TrySendingEmailWithNoCcAndBcc() - { - var input = _input2; - input.Subject = "Email test"; - - var attachment = new Attachment - { - FilePath = Path.Combine(_localAttachmentFolder, TEST_FILE_NOT_EXISTING), - SendIfNoAttachmentsFound = false, - ThrowExceptionIfAttachmentNotFound = false - }; - - - var Attachments = new AttachmentOptions { Attachments = new Attachment[] { attachment } }; - - var result = await SMTP.SendEmail(input, Attachments, _options, default); - Assert.IsFalse(result.EmailSent); - } - - [Test] - public void TrySendingEmailWithNoFileAttachmentFoundException() - { - var input = _input; - input.Subject = "Email test"; - - var attachment = new Attachment - { - FilePath = Path.Combine(_localAttachmentFolder, TEST_FILE_NOT_EXISTING), - SendIfNoAttachmentsFound = false, - ThrowExceptionIfAttachmentNotFound = true - }; - - - var Attachments = new AttachmentOptions { Attachments = new Attachment[] { attachment } }; - - var ex = Assert.ThrowsAsync(async () => await SMTP.SendEmail(input, Attachments, _options, default)); - Assert.AreEqual(@$"The given filepath '{attachment.FilePath}' had no matching files", ex.Message); - } -} +using NUnit.Framework; +using System; +using System.IO; +using System.Threading.Tasks; +using Frends.SMTP.SendEmail.Definitions; + +namespace Frends.SMTP.SendEmail.Tests; + +[TestFixture] +public class SendEmailTests +{ + // ****************************************** FILL THESE ****************************************************** + private static readonly string USERNAME = Environment.GetEnvironmentVariable("Frends_SMTP_Username"); + private static readonly string PASSWORD = Environment.GetEnvironmentVariable("Frends_SMTP_Password"); + private static readonly string SMTPADDRESS = Environment.GetEnvironmentVariable("Frends_SMTP_Address"); + private static readonly string TOEMAILADDRESS = Environment.GetEnvironmentVariable("Frends_SMTP_Email"); + private static readonly string FROMEMAILADDRESS = Environment.GetEnvironmentVariable("Frends_SMTP_Email"); + private const int PORT = 587; + // ************************************************************************************************************ + + + private const string TEMP_ATTACHMENT_SOURCE = "emailtestattachments"; + private const string TEST_FILE_NAME = "testattachment.txt"; + private const string TEST_FILE_NOT_EXISTING = "doesntexist.txt"; + + private string _localAttachmentFolder; + private string _filepath; + private Input _input; + private Input _input2; + private Options _options; + + [SetUp] + public void EmailTestSetup() + { + _localAttachmentFolder = Path.Combine(Path.GetTempPath(), TEMP_ATTACHMENT_SOURCE); + + if (!Directory.Exists(_localAttachmentFolder)) + Directory.CreateDirectory(_localAttachmentFolder); + + _filepath = Path.Combine(_localAttachmentFolder, TEST_FILE_NAME); + + if (!File.Exists(_filepath)) + { + File.Create(_filepath).Dispose(); + } + + _input = new Input() + { + From = FROMEMAILADDRESS, + To = TOEMAILADDRESS, + Cc = "", + Bcc = "", + Message = "testmsg", + IsMessageHtml = false, + SenderName = "EmailTestSender", + MessageEncoding = "utf-8" + }; + + _input2 = new Input() + { + From = FROMEMAILADDRESS, + To = TOEMAILADDRESS, + Cc = null, + Bcc = null, + Message = "testmsg", + IsMessageHtml = false, + SenderName = "EmailTestSender", + MessageEncoding = "utf-8" + }; + + _options = new Options() + { + UserName = USERNAME, + Password = PASSWORD, + SMTPServer = SMTPADDRESS, + Port = PORT, + UseOAuth2 = false, + SecureSocket = SecureSocketOption.None + }; + + } + + [TearDown] + public void EmailTestTearDown() + { + if (Directory.Exists(_localAttachmentFolder)) + Directory.Delete(_localAttachmentFolder, true); + } + + [Test] + public async Task SendEmailWithPlainText() + { + var input = _input; + input.Subject = "Email test - PlainText"; + + var result = await SMTP.SendEmail(input, null, _options, default); + Assert.IsTrue(result.EmailSent); + } + + [Test] + public async Task SendEmailWithFileAttachment() + { + var input = _input; + input.Subject = "Email test - FileAttachment"; + + var attachment = new Attachment + { + AttachmentType = AttachmentType.FileAttachment, + FilePath = _filepath, + SendIfNoAttachmentsFound = false, + ThrowExceptionIfAttachmentNotFound = true + }; + + var Attachments = new AttachmentOptions { Attachments = new Attachment[] { attachment } }; + + var result = await SMTP.SendEmail(input, Attachments, _options, default); + Assert.IsTrue(result.EmailSent); + } + + [Test] + public async Task SendEmailWithStringAttachment() + { + var input = _input; + input.Subject = "Email test - AttachmentFromString"; + var fileAttachment = new AttachmentFromString() { FileContent = "teststring � �", FileName = "testfilefromstring.txt" }; + var attachment = new Attachment() + { + AttachmentType = AttachmentType.AttachmentFromString, + StringAttachment = fileAttachment + }; + var Attachments = new AttachmentOptions { Attachments = new Attachment[] { attachment } }; + + var result = await SMTP.SendEmail(input, Attachments, _options, default); + Assert.IsTrue(result.EmailSent); + } + + [Test] + public async Task TrySendingEmailWithNoFileAttachmentFound() + { + var input = _input; + input.Subject = "Email test"; + + var attachment = new Attachment + { + FilePath = Path.Combine(_localAttachmentFolder, TEST_FILE_NOT_EXISTING), + SendIfNoAttachmentsFound = false, + ThrowExceptionIfAttachmentNotFound = false + }; + + var Attachments = new AttachmentOptions { Attachments = new Attachment[] { attachment } }; + + var result = await SMTP.SendEmail(input, Attachments, _options, default); + Assert.IsFalse(result.EmailSent); + } + + [Test] + public async Task TrySendingEmailWithNoCcAndBcc() + { + var input = _input2; + input.Subject = "Email test"; + + var attachment = new Attachment + { + FilePath = Path.Combine(_localAttachmentFolder, TEST_FILE_NOT_EXISTING), + SendIfNoAttachmentsFound = false, + ThrowExceptionIfAttachmentNotFound = false + }; + + var Attachments = new AttachmentOptions { Attachments = new Attachment[] { attachment } }; + + var result = await SMTP.SendEmail(input, Attachments, _options, default); + Assert.IsFalse(result.EmailSent); + } + + [Test] + public void TrySendingEmailWithNoFileAttachmentFoundException() + { + var input = _input; + input.Subject = "Email test"; + + var attachment = new Attachment + { + FilePath = Path.Combine(_localAttachmentFolder, TEST_FILE_NOT_EXISTING), + SendIfNoAttachmentsFound = false, + ThrowExceptionIfAttachmentNotFound = true + }; + + var Attachments = new AttachmentOptions { Attachments = new Attachment[] { attachment } }; + + var ex = Assert.ThrowsAsync(async () => await SMTP.SendEmail(input, Attachments, _options, default)); + Assert.AreEqual(@$"The given filepath '{attachment.FilePath}' had no matching files", ex.Message); + } +} diff --git a/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Frends.Smtp.SendEmail.csproj b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Frends.Smtp.SendEmail.csproj index 0ea3711..bf90403 100644 --- a/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Frends.Smtp.SendEmail.csproj +++ b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Frends.Smtp.SendEmail.csproj @@ -2,7 +2,7 @@ net6.0 - 1.2.0 + 1.2.1 latest Frends Frends diff --git a/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/SendEmailTask.cs b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/SendEmailTask.cs index e3bb243..4fc5169 100644 --- a/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/SendEmailTask.cs +++ b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/SendEmailTask.cs @@ -85,9 +85,7 @@ public static async Task SendEmail([PropertyTab] Input input, [PropertyT mail.Body = body; } - using var client = new SmtpClient(); - - await ConnectAndAuthenticate(client, SMTPSettings, cancellationToken); + using var client = await InitializeSmtpClient(SMTPSettings, cancellationToken); await client.SendAsync(mail, cancellationToken); await client.DisconnectAsync(true, cancellationToken); @@ -98,8 +96,10 @@ public static async Task SendEmail([PropertyTab] Input input, [PropertyT /// /// Initializes new SmtpClient with given parameters. /// - private static async Task ConnectAndAuthenticate(SmtpClient client, Options settings, CancellationToken cancellationToken) + private static async Task InitializeSmtpClient(Options settings, CancellationToken cancellationToken) { + var client = new SmtpClient(); + var secureSocketOption = settings.SecureSocket switch { SecureSocketOption.None => SecureSocketOptions.None, @@ -108,18 +108,21 @@ private static async Task ConnectAndAuthenticate(SmtpClient client, Option SecureSocketOption.StartTlsWhenAvailable => SecureSocketOptions.StartTlsWhenAvailable, _ => SecureSocketOptions.Auto, }; + await client.ConnectAsync(settings.SMTPServer, settings.Port, secureSocketOption, cancellationToken); SaslMechanism mechanism; if (settings.UseOAuth2) mechanism = new SaslMechanismOAuth2(settings.UserName, settings.Token); + else if (string.IsNullOrEmpty(settings.Password)) + return client; else mechanism = new SaslMechanismLogin(new NetworkCredential(settings.UserName, settings.Password)); await client.AuthenticateAsync(mechanism, cancellationToken); - return client.IsConnected && client.IsAuthenticated; + return client; } ///