From a84c3ae52e69504fa3661681ec1879ed928977d0 Mon Sep 17 00:00:00 2001 From: Peter Date: Thu, 25 Jan 2018 22:49:03 +0100 Subject: [PATCH] Support for embedded images. --- Mailzor/Email.cs | 26 ++++++++++++++++++++++++++ Test/Program.cs | 5 +++++ Test/Views/Emails/hello.cshtml | 2 +- 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/Mailzor/Email.cs b/Mailzor/Email.cs index 92074ce..e80a450 100644 --- a/Mailzor/Email.cs +++ b/Mailzor/Email.cs @@ -2,8 +2,10 @@ using System; using System.Collections.Generic; using System.Dynamic; +using System.IO; using System.Linq; using System.Net.Mail; +using System.Net.Mime; using System.Text; using System.Threading.Tasks; @@ -23,6 +25,8 @@ public class Email:IDisposable public dynamic ViewBag { get; set; } public List Attachments { get; } = new List(); + public List LinkedResources { get; } = new List(); + private string FromMailAddress { get; set; } private string FromDisplayName { get; set; } @@ -99,6 +103,24 @@ public void SetFrom(string mailAddress, string displayName = null) FromDisplayName = displayName; } + public LinkedResource AddImageResource(Stream stream, string contentId, string contentType) + { + return AddImageResource(stream, contentId, new ContentType(contentType)); + } + + public LinkedResource AddImageResource(Stream stream, string contentId, ContentType contentType) + { + var imageResource = new LinkedResource(stream, MediaTypeNames.Image.Jpeg) + { + ContentId = contentId, + ContentType = contentType + }; + + LinkedResources.Add(imageResource); + + return imageResource; + } + public void Dispose() { _smtpClient.Dispose(); @@ -126,6 +148,10 @@ private MailMessage ConfigureEmail(MailAddress[] toMails, string subject, MailAd email.Attachments.Add(attachment); } + var view = AlternateView.CreateAlternateViewFromString(emailHtmlBody, null, MediaTypeNames.Text.Html); + LinkedResources?.ForEach(res => view.LinkedResources.Add(res)); + email.AlternateViews.Add(view); + foreach (var toMail in toMails ?? Enumerable.Empty()) { email.To.Add(toMail); diff --git a/Test/Program.cs b/Test/Program.cs index 1077e5b..5274e82 100644 --- a/Test/Program.cs +++ b/Test/Program.cs @@ -72,6 +72,11 @@ private static void NormalSenario() // set Attachments email.Attachments.Add(new Attachment("Attachments/attach1.pdf")); email.Attachments.Add(new Attachment("Attachments/attach2.docx")); + + // set image resource + var fileStream = new FileStream("Views/Emails/microsoft.png", FileMode.Open); + email.AddImageResource(fileStream, "microsoft.png", "image/png"); + // set your desired display name (Optional) email.SetFrom("test@outlook.com","King Of Mail Zone"); // send it diff --git a/Test/Views/Emails/hello.cshtml b/Test/Views/Emails/hello.cshtml index b7b86c9..e3752ed 100644 --- a/Test/Views/Emails/hello.cshtml +++ b/Test/Views/Emails/hello.cshtml @@ -6,7 +6,7 @@
- +