From da95ecd48a191ed43040247c94501f3be9042873 Mon Sep 17 00:00:00 2001 From: Riku Virtanen Date: Wed, 29 Nov 2023 09:34:04 +0200 Subject: [PATCH] Debugging password --- Frends.SMTP.SendEmail/CHANGELOG.md | 8 + .../SendEmailTests.cs | 41 ++- .../Frends.Smtp.SendEmail/Definitions.cs | 200 ----------- .../Definitions/Attachment.cs | 42 +++ .../Definitions/AttachmentFromString.cs | 22 ++ .../Definitions/AttachmentOptions.cs | 16 + .../Definitions/AttachmentType.cs | 18 + .../Definitions/Input.cs | 74 +++++ .../Definitions/Options.cs | 56 ++++ .../Definitions/Result.cs | 26 ++ .../Frends.Smtp.SendEmail.csproj | 4 +- .../GlobalSuppressions.cs | 4 + .../Frends.Smtp.SendEmail/SendEmailTask.cs | 310 +++++++++--------- Frends.SMTP.SendEmail/README.md | 19 +- README.md | 2 +- 15 files changed, 452 insertions(+), 390 deletions(-) delete mode 100644 Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions.cs create mode 100644 Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/Attachment.cs create mode 100644 Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/AttachmentFromString.cs create mode 100644 Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/AttachmentOptions.cs create mode 100644 Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/AttachmentType.cs create mode 100644 Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/Input.cs create mode 100644 Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/Options.cs create mode 100644 Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/Result.cs create mode 100644 Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/GlobalSuppressions.cs diff --git a/Frends.SMTP.SendEmail/CHANGELOG.md b/Frends.SMTP.SendEmail/CHANGELOG.md index deb4c20..e20ce09 100644 --- a/Frends.SMTP.SendEmail/CHANGELOG.md +++ b/Frends.SMTP.SendEmail/CHANGELOG.md @@ -1,11 +1,19 @@ # Changelog + +## [1.1.0] - 2023-11-29 +### Fixed +- Fixed issue with the attachments can't be given as expression + ## [1.0.3] - 2023-11-03 +### Added - Fix missing XML comments. ## [1.0.2] - 2023-11-03 +### Added - Fix bug #20 - Missing Frends tasks metadata file ## [1.0.1] - 2023-05-15 +### Fixed - Fix bug #14 - NullReferenceException when field with 'Expression' type is empty ## [1.0.0] - 2022-02-09 diff --git a/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail.Tests/SendEmailTests.cs b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail.Tests/SendEmailTests.cs index 757f5c1..205e25d 100644 --- a/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail.Tests/SendEmailTests.cs +++ b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail.Tests/SendEmailTests.cs @@ -1,21 +1,19 @@ using NUnit.Framework; using System; using System.IO; +using Frends.SMTP.SendEmail.Definitions; namespace Frends.SMTP.SendEmail.Tests { - /// - /// NOTE: To run these unit tests, you need an SMTP test server. Fill in the properties below with your values. - /// [TestFixture] public class SendEmailTests { // ****************************************** FILL THESE ****************************************************** - private const string USERNAME = "apikey"; - private const string PASSWORD = ""; - private const string SMTPADDRESS = "smtp.sendgrid.net"; - private const string TOEMAILADDRESS = "jefim.borissov@hiq.fi"; - private const string FROMEMAILADDRESS = "jefim.borissov@hiq.fi"; + private static readonly string USERNAME = "apikey"; // Environment.GetEnvironmentVariable("Frends_SMTP_Username"); + private static readonly string PASSWORD = Environment.GetEnvironmentVariable("SMTP_PASSWORD"); // Environment.GetEnvironmentVariable("Frends_SMTP_Password"); + private static readonly string SMTPADDRESS = "smtp.sendgrid.net"; // Environment.GetEnvironmentVariable("Frends_SMTP_Address"); + private static readonly string TOEMAILADDRESS = "jefim.borissov@hiq.fi"; // Environment.GetEnvironmentVariable("Frends_SMTP_Email"); + private static readonly string FROMEMAILADDRESS = "jefim.borissov@hiq.fi"; // Environment.GetEnvironmentVariable("Frends_SMTP_Email"); private const int PORT = 587; private const bool USESSL = true; private const bool USEWINDOWSAUTHENTICATION = false; @@ -71,12 +69,10 @@ public void EmailTestSetup() MessageEncoding = "utf-8" }; - var passwordFromEnvironment = Environment.GetEnvironmentVariable("SMTP_PASSWORD"); - _options = new Options() { UserName = USERNAME, - Password = string.IsNullOrWhiteSpace(passwordFromEnvironment) ? PASSWORD : passwordFromEnvironment, + Password = PASSWORD, SMTPServer = SMTPADDRESS, Port = PORT, UseSsl = USESSL, @@ -97,7 +93,7 @@ public void SendEmailWithPlainText() var input = _input; input.Subject = "Email test - PlainText"; - var result = SMTP.SendEmail(input, null, _options, new System.Threading.CancellationToken()); + var result = SMTP.SendEmail(input, null, _options, default); Assert.IsTrue(result.EmailSent); } @@ -109,15 +105,16 @@ public void SendEmailWithFileAttachment() var attachment = new Attachment { + AttachmentType = AttachmentType.FileAttachment, FilePath = _filepath, SendIfNoAttachmentsFound = false, ThrowExceptionIfAttachmentNotFound = true }; - var Attachments = new Attachment[] { attachment }; + var Attachments = new AttachmentOptions { Attachments = new Attachment[] { attachment } }; - var result = SMTP.SendEmail(input, Attachments, _options, new System.Threading.CancellationToken()); + var result = SMTP.SendEmail(input, Attachments, _options, default); Assert.IsTrue(result.EmailSent); } @@ -132,9 +129,9 @@ public void SendEmailWithStringAttachment() AttachmentType = AttachmentType.AttachmentFromString, stringAttachment = fileAttachment }; - var Attachments = new Attachment[] { attachment }; + var Attachments = new AttachmentOptions { Attachments = new Attachment[] { attachment } }; - var result = SMTP.SendEmail(input, Attachments, _options, new System.Threading.CancellationToken()); + var result = SMTP.SendEmail(input, Attachments, _options, default); Assert.IsTrue(result.EmailSent); } @@ -152,9 +149,9 @@ public void TrySendingEmailWithNoFileAttachmentFound() }; - var Attachments = new Attachment[] { attachment }; + var Attachments = new AttachmentOptions { Attachments = new Attachment[] { attachment } }; - var result = SMTP.SendEmail(input, Attachments, _options, new System.Threading.CancellationToken()); + var result = SMTP.SendEmail(input, Attachments, _options, default); Assert.IsFalse(result.EmailSent); } @@ -172,9 +169,9 @@ public void TrySendingEmailWithNoCcAndBcc() }; - var Attachments = new Attachment[] { attachment }; + var Attachments = new AttachmentOptions { Attachments = new Attachment[] { attachment } }; - var result = SMTP.SendEmail(input, Attachments, _options, new System.Threading.CancellationToken()); + var result = SMTP.SendEmail(input, Attachments, _options, default); Assert.IsFalse(result.EmailSent); } @@ -192,9 +189,9 @@ public void TrySendingEmailWithNoFileAttachmentFoundException() }; - var Attachments = new Attachment[] { attachment }; + var Attachments = new AttachmentOptions { Attachments = new Attachment[] { attachment } }; - Assert.Throws(() => SMTP.SendEmail(input, Attachments, _options, new System.Threading.CancellationToken())); + Assert.Throws(() => SMTP.SendEmail(input, Attachments, _options, default)); } } diff --git a/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions.cs b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions.cs deleted file mode 100644 index 5ac23e0..0000000 --- a/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions.cs +++ /dev/null @@ -1,200 +0,0 @@ -using System.ComponentModel; -using System.ComponentModel.DataAnnotations; - -namespace Frends.SMTP.SendEmail -{ - public class Input - { - /// - /// Recipient addresses separated by ',' or ';' - /// - /// jane.doe@example.org - [DefaultValue("\"jane.doe@example.org\"")] - public string To { get; set; } - - /// - /// Cc recipient addresses separated by ',' or ';' - /// - /// jane.doe@example.org - [DefaultValue("\"jane.doe@example.org\"")] - public string Cc { get; set; } - - /// - /// Bcc recipient addresses separated by ',' or ';' - /// - /// jane.doe@example.org - [DefaultValue("\"jane.doe@example.org\"")] - public string Bcc { get; set; } - - /// - /// Sender address. - /// - /// john.doe@example.org - [DefaultValue("\"john.doe@example.org\"")] - public string From { get; set; } - - /// - /// Name of the sender. - /// - /// Frends - [DefaultValue("\"\"")] - public string SenderName { get; set; } - - /// - /// Email message's subject. - /// - /// Hello Jane - [DefaultValue("\"Hello Jane\"")] - public string Subject { get; set; } - - /// - /// Body of the message. - /// - /// You've got mail! - [DefaultValue("\"You've got mail!\"")] - public string Message { get; set; } - - /// - /// Set this true if the message is HTML. - /// - /// true - [DefaultValue("false")] - public bool IsMessageHtml { get; set; } - - /// - /// Encoding of message body and subject. Use following table's name column for other options. https://msdn.microsoft.com/en-us/library/system.text.encoding(v=vs.110).aspx#Anchor_5 - /// - /// utf-8 - [DefaultValue("\"utf-8\"")] - public string MessageEncoding { get; set; } - - } - - public class Options - { - /// - /// SMTP server address. - /// - /// smtp.somedomain.com - [DefaultValue("\"smtp.somedomain.com\"")] - public string SMTPServer { get; set; } - - /// - /// SMTP server port. - /// - /// 25 - [DefaultValue("25")] - public int Port { get; set; } - - /// - /// Set this true if SMTP expects to be connected using SSL. - /// - /// true - [DefaultValue("false")] - public bool UseSsl { get; set; } - - /// - /// Set this true if you want to use windows authentication to authenticate to SMTP server. - /// - /// true - [DefaultValue("true")] - public bool UseWindowsAuthentication { get; set; } - - /// - /// Use this username to log in to the SMTP server - /// - /// username - [DefaultValue("\"\"")] - [UIHint(nameof(UseWindowsAuthentication), "", false)] - public string UserName { get; set; } - - /// - /// Use this password to log in to the SMTP server - /// - /// Password123 - [PasswordPropertyText(true)] - [DefaultValue("\"\"")] - [UIHint(nameof(UseWindowsAuthentication), "", false)] - public string Password { get; set; } - } - - public class Output - { - /// - /// Value is true if email was sent. - /// - /// true - public bool EmailSent { get; set; } - /// - /// Contains information about the task's result. - /// - /// No attachments found matching path \"C:\\temp\\*.csv\". No email sent. - public string StatusString { get; set; } - } - - public class Attachment - { - /// - /// Chooses if the attachment file is created from a string or copied from disk. - /// - /// FileAttachment - public AttachmentType AttachmentType { get; set; } - - [UIHint(nameof(AttachmentType), "", AttachmentType.AttachmentFromString)] - public AttachmentFromString stringAttachment { get; set; } - - /// - /// Attachment file's path. Uses Directory.GetFiles(string, string) as a pattern matching technique. See https://msdn.microsoft.com/en-us/library/wz42302f(v=vs.110).aspx. - /// Exception: If the path ends in a directory, all files in that folder are added as attachments. - /// - /// /my/attachment/dir - [DefaultValue("\"\"")] - [UIHint(nameof(AttachmentType), "", AttachmentType.FileAttachment)] - public string FilePath { get; set; } - - /// - /// If set true and no files match the given path, an exception is thrown. - /// - /// true - [UIHint(nameof(AttachmentType), "", AttachmentType.FileAttachment)] - public bool ThrowExceptionIfAttachmentNotFound { get; set; } - - /// - /// If set true and no files match the given path, email will be sent nevertheless. - /// - /// true - [UIHint(nameof(AttachmentType), "", AttachmentType.FileAttachment)] - public bool SendIfNoAttachmentsFound { get; set; } - } - public enum AttachmentType - { - /// - /// Select this if the attachment is a file. - /// - FileAttachment, - - /// - /// Select this if the attachment file should be created from a string. - /// - AttachmentFromString - } - - public class AttachmentFromString - { - /// - /// Content of the attachment file - /// - /// My attachment content - [DefaultValue("\"\"")] - [DisplayFormat(DataFormatString = "Text")] - public string FileContent { get; set; } - - /// - /// Name of the attachment file - /// - /// MyAttachment.txt - [DefaultValue("\"\"")] - [DisplayFormat(DataFormatString = "Text")] - public string FileName { get; set; } - } -} diff --git a/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/Attachment.cs b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/Attachment.cs new file mode 100644 index 0000000..c511a98 --- /dev/null +++ b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/Attachment.cs @@ -0,0 +1,42 @@ +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace Frends.SMTP.SendEmail.Definitions +{ + /// + /// Attachment + /// + public class Attachment + { + /// + /// Chooses if the attachment file is created from a string or copied from disk. + /// + public AttachmentType AttachmentType { get; set; } + + /// + /// Attachment from string. + /// + [UIHint(nameof(AttachmentType), "", AttachmentType.AttachmentFromString)] + public AttachmentFromString stringAttachment { get; set; } + + /// + /// Attachment file's path. Uses Directory.GetFiles(string, string) as a pattern matching technique. See https://msdn.microsoft.com/en-us/library/wz42302f(v=vs.110).aspx. + /// Exception: If the path ends in a directory, all files in that folder are added as attachments. + /// + [DefaultValue("\"\"")] + [UIHint(nameof(AttachmentType), "", AttachmentType.FileAttachment)] + public string FilePath { get; set; } + + /// + /// If set true and no files match the given path, an exception is thrown. + /// + [UIHint(nameof(AttachmentType), "", AttachmentType.FileAttachment)] + public bool ThrowExceptionIfAttachmentNotFound { get; set; } + + /// + /// If set true and no files match the given path, email will be sent nevertheless. + /// + [UIHint(nameof(AttachmentType), "", AttachmentType.FileAttachment)] + public bool SendIfNoAttachmentsFound { get; set; } + } +} diff --git a/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/AttachmentFromString.cs b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/AttachmentFromString.cs new file mode 100644 index 0000000..9ee0bff --- /dev/null +++ b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/AttachmentFromString.cs @@ -0,0 +1,22 @@ +using System.ComponentModel; + +namespace Frends.SMTP.SendEmail.Definitions +{ + /// + /// Parameters for adding attachment from string. + /// + public class AttachmentFromString + { + /// + /// Content of the attachment file + /// + [DefaultValue("\"\"")] + public string FileContent { get; set; } + + /// + /// Name of the attachment file + /// + [DefaultValue("\"\"")] + public string FileName { get; set; } + } +} diff --git a/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/AttachmentOptions.cs b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/AttachmentOptions.cs new file mode 100644 index 0000000..0c38676 --- /dev/null +++ b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/AttachmentOptions.cs @@ -0,0 +1,16 @@ +namespace Frends.SMTP.SendEmail.Definitions +{ + /// + /// Parameters for attachments. + /// + public class AttachmentOptions + { + /// + /// Array of Attachments to be send with the message. + /// + /// [ + /// Attachment { AttachmentType = AttachmentType.FileAttachment, FilePath = C:\pathToTheFile\test.txt, SendIfNoAttachmentsFound = false, ThrowExceptionIfAttachmentNotFound = true }, + /// Attachment { AttachmentType = AttachmentType.AttachmentFromString, AttachmentFromString { FileContent = This is test file, FileName = testfile.txt } } ] + public Attachment[] Attachments { get; set; } + } +} diff --git a/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/AttachmentType.cs b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/AttachmentType.cs new file mode 100644 index 0000000..8b6e0e0 --- /dev/null +++ b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/AttachmentType.cs @@ -0,0 +1,18 @@ +namespace Frends.SMTP.SendEmail.Definitions +{ + /// + /// Enumeration for Attachment type. + /// + public enum AttachmentType + { + /// + /// Select this if the attachment is a file. + /// + FileAttachment, + + /// + /// Select this if the attachment file should be created from a string. + /// + AttachmentFromString + } +} diff --git a/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/Input.cs b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/Input.cs new file mode 100644 index 0000000..72538a5 --- /dev/null +++ b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/Input.cs @@ -0,0 +1,74 @@ +using System.ComponentModel; + +namespace Frends.SMTP.SendEmail.Definitions +{ + /// + /// Input parameters. + /// + public class Input + { + /// + /// Recipient addresses separated by ',' or ';' + /// + /// jane.doe@somedomain.com + [DefaultValue("\"jane.doe@somedomain.com\"")] + public string To { get; set; } + + /// + /// Cc recipient addresses separated by ',' or ';' + /// + /// jane.doe@somedomain.com + [DefaultValue("\"jane.doe@somedomain.com\"")] + public string Cc { get; set; } + + /// + /// Bcc recipient addresses separated by ',' or ';' + /// + /// jane.doe@somedomain.com + [DefaultValue("\"jane.doe@somedomain.com\"")] + public string Bcc { get; set; } + + /// + /// Sender address. + /// + /// jane.doe@somedomain.com + [DefaultValue("\"john.doe@somedomain.com\"")] + public string From { get; set; } + + /// + /// Name of the sender. + /// + /// Jane Doe + [DefaultValue("\"\"")] + public string SenderName { get; set; } + + /// + /// Email message's subject. + /// + /// Hello Jane + [DefaultValue("\"Hello Jane\"")] + public string Subject { get; set; } + + /// + /// Body of the message. + /// + /// You've got mail! + [DefaultValue("\"You've got mail!\"")] + public string Message { get; set; } + + /// + /// Set this true if the message is HTML. + /// + /// true + [DefaultValue("false")] + public bool IsMessageHtml { get; set; } + + /// + /// Encoding of message body and subject. Use following table's name column for other options. https://msdn.microsoft.com/en-us/library/system.text.encoding(v=vs.110).aspx#Anchor_5 + /// + /// utf-8 + [DefaultValue("\"utf-8\"")] + public string MessageEncoding { get; set; } + + } +} diff --git a/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/Options.cs b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/Options.cs new file mode 100644 index 0000000..6e2ec20 --- /dev/null +++ b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/Options.cs @@ -0,0 +1,56 @@ +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace Frends.SMTP.SendEmail.Definitions +{ + /// + /// SMTP Options parameters. + /// + public class Options + { + /// + /// SMTP server address. + /// + /// smtp.somedomain.com + [DefaultValue("\"smtp.somedomain.com\"")] + public string SMTPServer { get; set; } + + /// + /// SMTP server port. + /// + /// 25 + [DefaultValue("25")] + public int Port { get; set; } + + /// + /// Set this true if SMTP expects to be connected using SSL. + /// + /// true + [DefaultValue("false")] + public bool UseSsl { get; set; } + + /// + /// Set this true if you want to use windows authentication to authenticate to SMTP server. + /// + /// false + [DefaultValue("true")] + public bool UseWindowsAuthentication { get; set; } + + /// + /// Use this username to log in to the SMTP server + /// + /// testuser + [DefaultValue("\"\"")] + [UIHint(nameof(UseWindowsAuthentication), "", false)] + public string UserName { get; set; } + + /// + /// Use this password to log in to the SMTP server + /// + /// testpassword + [PasswordPropertyText(true)] + [DefaultValue("\"\"")] + [UIHint(nameof(UseWindowsAuthentication), "", false)] + public string Password { get; set; } + } +} diff --git a/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/Result.cs b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/Result.cs new file mode 100644 index 0000000..7ba5969 --- /dev/null +++ b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Definitions/Result.cs @@ -0,0 +1,26 @@ +namespace Frends.SMTP.SendEmail.Definitions +{ + /// + /// Result class of the Task. + /// + public class Result + { + internal Result(bool emailSent, string status) + { + EmailSent = emailSent; + StatusString = status; + } + + /// + /// Value is true if email was sent. + /// + /// true + public bool EmailSent { get; private set; } + + /// + /// Contains information about the task's result. + /// + /// + public string StatusString { get; private set; } + } +} 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 1ccad62..d51eed1 100644 --- a/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Frends.Smtp.SendEmail.csproj +++ b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/Frends.Smtp.SendEmail.csproj @@ -1,9 +1,9 @@ - + netstandard2.0;net6.0 - 1.0.3 + 1.0.4 Frends Frends Frends diff --git a/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/GlobalSuppressions.cs b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/GlobalSuppressions.cs new file mode 100644 index 0000000..586b721 --- /dev/null +++ b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/GlobalSuppressions.cs @@ -0,0 +1,4 @@ +using System.Diagnostics.CodeAnalysis; + +[assembly: SuppressMessage("Minor Code Smell", "S101:Types should be named in PascalCase", Justification = "Following Frends guidelines", Scope = "type", Target = "~T:Frends.SMTP.SendEmail.SMTP")] +[assembly: SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1633:File should have header", Justification = "Following Frends guidelines")] diff --git a/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/SendEmailTask.cs b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/SendEmailTask.cs index 9b1c5b4..57e5258 100644 --- a/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/SendEmailTask.cs +++ b/Frends.SMTP.SendEmail/Frends.Smtp.SendEmail/SendEmailTask.cs @@ -1,158 +1,154 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.IO; -using System.Net; -using System.Net.Mail; -using System.Text; -using System.Threading; -namespace Frends.SMTP.SendEmail -{ -#pragma warning disable S101 // Types should be named in PascalCase - public static class SMTP -#pragma warning restore S101 // Types should be named in PascalCase - - { - /// - /// Sends email message with optional attachments. - /// [Documentation](https://github.com/FrendsPlatform/Frends.SMTP/tree/main/Frends.SMTP.SendEmail) - /// - /// - /// Object { bool EmailSent, string StatusString } - /// - public static Output SendEmail([PropertyTab] Input message, [PropertyTab] Attachment[] attachments, [PropertyTab] Options SMTPSettings, CancellationToken cancellationToken) - { - var output = new Output(); - - using (var client = InitializeSmtpClient(SMTPSettings)) - { - using (var mail = InitializeMailMessage(message)) - { - if (attachments != null) - foreach (var attachment in attachments) - { - if (attachment.AttachmentType == AttachmentType.FileAttachment) - { - ICollection allAttachmentFilePaths = GetAttachmentFiles(attachment.FilePath); - - if (attachment.ThrowExceptionIfAttachmentNotFound && allAttachmentFilePaths.Count == 0) - throw new FileNotFoundException(string.Format("The given filepath \"{0}\" had no matching files", attachment.FilePath), attachment.FilePath); - - if (allAttachmentFilePaths.Count == 0 && !attachment.SendIfNoAttachmentsFound) - { - output.StatusString = string.Format("No attachments found matching path \"{0}\". No email sent.", attachment.FilePath); - output.EmailSent = false; - return output; - } - - foreach (var fp in allAttachmentFilePaths) - { - mail.Attachments.Add(new System.Net.Mail.Attachment(fp)); - } - } - - if (attachment.AttachmentType == AttachmentType.AttachmentFromString - && !string.IsNullOrEmpty(attachment.stringAttachment.FileContent)) - { - mail.Attachments.Add(System.Net.Mail.Attachment.CreateAttachmentFromString - (attachment.stringAttachment.FileContent, attachment.stringAttachment.FileName)); - } - - } - - cancellationToken.ThrowIfCancellationRequested(); - - client.Send(mail); - - output.EmailSent = true; - output.StatusString = string.Format("Email sent to: {0}", mail.To.ToString()); - - return output; - } - } - } - - /// - /// Initializes new SmtpClient with given parameters. - /// - private static SmtpClient InitializeSmtpClient(Options settings) - { - var smtpClient = new SmtpClient - { - Port = settings.Port, - DeliveryMethod = SmtpDeliveryMethod.Network, - UseDefaultCredentials = settings.UseWindowsAuthentication, - EnableSsl = settings.UseSsl, - Host = settings.SMTPServer - }; - - if (!settings.UseWindowsAuthentication && !string.IsNullOrEmpty(settings.UserName)) - smtpClient.Credentials = new NetworkCredential(settings.UserName, settings.Password); - - return smtpClient; - } - - /// - /// Initializes new MailMessage with given parameters. Uses default value 'true' for IsBodyHtml - /// - private static MailMessage InitializeMailMessage(Input input) - { - //split recipients, either by comma or semicolon - var separators = new[] { ',', ';' }; - - string[] recipients = string.IsNullOrEmpty(input.To) - ? new string[] { } - : input.To.Split(separators, StringSplitOptions.RemoveEmptyEntries); - string[] ccRecipients = string.IsNullOrEmpty(input.Cc) - ? new string[] { } - : input.Cc.Split(separators, StringSplitOptions.RemoveEmptyEntries); - string[] bccRecipients = string.IsNullOrEmpty(input.Bcc) - ? new string[] { } - : input.Bcc.Split(separators, StringSplitOptions.RemoveEmptyEntries); - - //Create mail object - var mail = new MailMessage() - { - From = new MailAddress(input.From, input.SenderName), - Subject = input.Subject, - Body = input.Message, - IsBodyHtml = input.IsMessageHtml - }; - //Add recipients - foreach (var recipientAddress in recipients) - { - mail.To.Add(recipientAddress); - } - //Add CC recipients - foreach (var ccRecipient in ccRecipients) - { - mail.CC.Add(ccRecipient); - } - //Add BCC recipients - foreach (var bccRecipient in bccRecipients) - { - mail.Bcc.Add(bccRecipient); - } - //Set message encoding - Encoding encoding = Encoding.GetEncoding(input.MessageEncoding); - - mail.BodyEncoding = encoding; - mail.SubjectEncoding = encoding; - - return mail; - } - - /// - /// Gets all actual file names of attachments matching given file path - /// - private static ICollection GetAttachmentFiles(string filePath) - { - string folder = Path.GetDirectoryName(filePath); - string fileMask = Path.GetFileName(filePath) != "" ? Path.GetFileName(filePath) : "*"; - - string[] filePaths = Directory.GetFiles(folder, fileMask); - - return filePaths; - } - } +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.IO; +using System.Net; +using System.Net.Mail; +using System.Text; +using System.Threading; +using Frends.SMTP.SendEmail.Definitions; + +namespace Frends.SMTP.SendEmail +{ + /// + /// Main class of the Task. + /// + public static class SMTP + { + /// + /// Sends email message with optional attachments. + /// [Documentation](https://tasks.frends.com/tasks/frends-tasks/Frends.SMTP.SendEmail) + /// + /// Message parameters. + /// Parameters for adding attachments. + /// Connection parameters. + /// Token given by Frends to terminate the Task. + /// Object { bool EmailSent, string StatusString } + public static Result SendEmail([PropertyTab] Input message, [PropertyTab] AttachmentOptions attachments, [PropertyTab] Options SMTPSettings, CancellationToken cancellationToken) + { + using (var client = InitializeSmtpClient(SMTPSettings)) + { + using (var mail = InitializeMailMessage(message, cancellationToken)) + { + if (attachments != null) + foreach (var attachment in attachments.Attachments) + { + cancellationToken.ThrowIfCancellationRequested(); + + if (attachment.AttachmentType == AttachmentType.FileAttachment) + { + ICollection allAttachmentFilePaths = GetAttachmentFiles(attachment.FilePath); + + if (attachment.ThrowExceptionIfAttachmentNotFound && allAttachmentFilePaths.Count == 0) + throw new FileNotFoundException(string.Format("The given filepath \"{0}\" had no matching files", attachment.FilePath), attachment.FilePath); + + if (allAttachmentFilePaths.Count == 0 && !attachment.SendIfNoAttachmentsFound) + return new Result(false, $"No attachments found matching path \"{attachment.FilePath}\". No email sent."); + + foreach (var fp in allAttachmentFilePaths) + { + cancellationToken.ThrowIfCancellationRequested(); + mail.Attachments.Add(new System.Net.Mail.Attachment(fp)); + } + } + + if (attachment.AttachmentType == AttachmentType.AttachmentFromString + && !string.IsNullOrEmpty(attachment.stringAttachment.FileContent)) + mail.Attachments.Add(System.Net.Mail.Attachment.CreateAttachmentFromString + (attachment.stringAttachment.FileContent, attachment.stringAttachment.FileName)); + } + + client.Send(mail); + + return new Result(true, $"Email sent to: {mail.To}"); + } + } + } + + /// + /// Initializes new SmtpClient with given parameters. + /// + private static SmtpClient InitializeSmtpClient(Options settings) + { + var smtpClient = new SmtpClient + { + Port = settings.Port, + DeliveryMethod = SmtpDeliveryMethod.Network, + UseDefaultCredentials = settings.UseWindowsAuthentication, + EnableSsl = settings.UseSsl, + Host = settings.SMTPServer + }; + + if (!settings.UseWindowsAuthentication && !string.IsNullOrEmpty(settings.UserName)) + smtpClient.Credentials = new NetworkCredential(settings.UserName, settings.Password); + + return smtpClient; + } + + /// + /// Initializes new MailMessage with given parameters. Uses default value 'true' for IsBodyHtml + /// + private static MailMessage InitializeMailMessage(Input input, CancellationToken cancellationToken) + { + //split recipients, either by comma or semicolon + var separators = new[] { ',', ';' }; + + string[] recipients = string.IsNullOrEmpty(input.To) + ? new string[] { } + : input.To.Split(separators, StringSplitOptions.RemoveEmptyEntries); + string[] ccRecipients = string.IsNullOrEmpty(input.Cc) + ? new string[] { } + : input.Cc.Split(separators, StringSplitOptions.RemoveEmptyEntries); + string[] bccRecipients = string.IsNullOrEmpty(input.Bcc) + ? new string[] { } + : input.Bcc.Split(separators, StringSplitOptions.RemoveEmptyEntries); + + //Create mail object + var mail = new MailMessage() + { + From = new MailAddress(input.From, input.SenderName), + Subject = input.Subject, + Body = input.Message, + IsBodyHtml = input.IsMessageHtml + }; + //Add recipients + foreach (var recipientAddress in recipients) + { + cancellationToken.ThrowIfCancellationRequested(); + mail.To.Add(recipientAddress); + } + //Add CC recipients + foreach (var ccRecipient in ccRecipients) + { + cancellationToken.ThrowIfCancellationRequested(); + mail.CC.Add(ccRecipient); + } + //Add BCC recipients + foreach (var bccRecipient in bccRecipients) + { + cancellationToken.ThrowIfCancellationRequested(); + mail.Bcc.Add(bccRecipient); + } + //Set message encoding + Encoding encoding = Encoding.GetEncoding(input.MessageEncoding); + + mail.BodyEncoding = encoding; + mail.SubjectEncoding = encoding; + + return mail; + } + + /// + /// Gets all actual file names of attachments matching given file path + /// + private static ICollection GetAttachmentFiles(string filePath) + { + string folder = Path.GetDirectoryName(filePath); + string fileMask = Path.GetFileName(filePath) != "" ? Path.GetFileName(filePath) : "*"; + + string[] filePaths = Directory.GetFiles(folder, fileMask); + + return filePaths; + } + } } \ No newline at end of file diff --git a/Frends.SMTP.SendEmail/README.md b/Frends.SMTP.SendEmail/README.md index 6d8de4e..7566635 100644 --- a/Frends.SMTP.SendEmail/README.md +++ b/Frends.SMTP.SendEmail/README.md @@ -1,11 +1,10 @@ # Frends.SMTP.SendEmail +Frends task for sending emails with SMTP. Task sends emails via SMTP protocol and can handle attachments either from file or as raw string input. -[![Frends.Smtp.SendEmail Main](https://github.com/FrendsPlatform/Frends.Smtp/actions/workflows/SendEmail_main.yml/badge.svg)](https://github.com/FrendsPlatform/Frends.Regex/actions/workflows/IsMatch_build_and_test_on_main.yml) - ![GitHub](https://img.shields.io/github/license/FrendsPlatform/Frends.Smtp?label=License) - ![Coverage](https://app-github-custom-badges.azurewebsites.net/Badge?key=FrendsPlatform/Frends.Smtp/Frends.Smtp.SendEmail|main) - -Frends task for sending emails with SMTP. Task sends emails via SMTP protocol and can handle attachments either from file or as raw string input. +[![Frends.Smtp.SendEmail Main](https://github.com/FrendsPlatform/Frends.SMTP/actions/workflows/SendEmail_main.yml/badge.svg)](https://github.com/FrendsPlatform/Frends.SMTP/actions) + ![GitHub](https://img.shields.io/github/license/FrendsPlatform/Frends.SMTP?label=License) + ![Coverage](https://app-github-custom-badges.azurewebsites.net/Badge?key=FrendsPlatform/Frends.SMTP/Frends.SMTP.SendEmail|main) ## Installing @@ -13,14 +12,18 @@ You can install the Task via frends UI Task View. ## Building -Rebuild the project +### Clone a copy of the repository + +`git clone https://github.com/FrendsPlatform/Frends.SMTP.git` + +### Rebuild the project `dotnet build` -Run tests +### Run tests `dotnet test` -Create a NuGet package +### Create a NuGet package `dotnet pack --configuration Release` diff --git a/README.md b/README.md index 8fe4103..8f0159b 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Frends tasks for SMTP protocol. # Tasks -- [Frends.Smtp.SendEmail](Frends.Smtp.SendEmail/README.md) +- [Frends.SMTP.SendEmail](Frends.SMTP.SendEmail/README.md) # Contributing When contributing to this repository, please first discuss the change you wish to make via issue, email, or any other method with the owners of this repository before making a change.