You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Not optimized, or clean, but gets the point across. Getting inline images to show in the email was obnoxious. Key solution points are provided.
Backing Method
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Net;usingSystem.Net.Mail;usingSystem.Text;usingSystem.Threading.Tasks;usingMicrosoft.AspNetCore.Mvc;usingSendGrid.SmtpApi;usingSendGrid;usingSendGrid.Helpers.Mail;usingMicrosoft.Azure.WebJobs;publicstaticasyncTask<IActionResult>TestEmailViaSendGridAPI(ComplexEmailModelcem,stringsendGridApiKey){try{// Credentialsvarclient=newSendGridClient(sendGridApiKey);// Email Basicsvarfrom=newEmailAddress(cem.From);// needs to be whitelisted with service providervarto=newEmailAddress(cem.To);varsubject=cem.Subject;// Default content - Should only be visible to luddites and in case of an issue rendering the HTML varplainTextContent=cem.Content;// This content should have cid placeholders for each image to be added to the emailvarhtmlContent=cem.TemplateBody;// build base SendGridMessage varmsg=MailHelper.CreateSingleEmail(from,to,subject,plainTextContent,htmlContent);// replace cid:'s with imagesforeach(varattincem.InlineAttachments)msg.AddAttachment(att);// send email & report resultsvarresponse=awaitclient.SendEmailAsync(msg);if(response.IsSuccessStatusCode)returnnewOkObjectResult(response);elsereturnnewBadRequestObjectResult(response);}catch(Exceptionwtf){returnnewBadRequestObjectResult(wtf.Message);}}
Example Model
publicclassComplexEmailModel{[JsonProperty("from")]publicstringFrom{get;set;}="[email protected]";[JsonProperty("to")]publicstringTo{get;set;}[JsonProperty("subject")]publicstringSubject{get;set;}="Notice";[JsonProperty("content")]publicstringContent{get;set;}=$"A status update is available for review on MatchHub.";[JsonProperty("templateBody")]publicstringTemplateBody{get;set;}[JsonProperty("inlineImages")]publicList<SendGrid.Helpers.Mail.Attachment>InlineAttachments{get;set;}}
Async Main()
namespaceLocalEmailTest{classProgram{privateconststringSendGrid_FreeKey="INSERT-YOUR-API-KEY-HERE";staticasyncSystem.Threading.Tasks.TaskMain(string[]args){// retrieve the email template.// In this example, there should be two image tags with the following params:// <img src="cid:image1" ...// <img src="cid:image2" ...stringtemplateName="Template1.html";stringtemplateFullPath=System.IO.Path.Combine(Environment.CurrentDirectory,templateName);System.IO.StreamReaderstr=newSystem.IO.StreamReader(templateFullPath);stringmailBodyContent=str.ReadToEnd();str.Close();// Convert image one to a b64 encoded string.stringimageFileName1="image-1.png";stringinlineImagePath1=System.IO.Path.Combine(Environment.CurrentDirectory,imageFileName1);varb64_1=Convert.ToBase64String(System.IO.File.ReadAllBytes(inlineImagePath1));// Convert image two to a b64 encoded string.stringimageFileName2="image-2.gif";stringinlineImagePath2=System.IO.Path.Combine(Environment.CurrentDirectory,imageFileName2);varb64_2=Convert.ToBase64String(System.IO.File.ReadAllBytes(inlineImagePath2));//// uncomment to verify paths//Console.WriteLine(path);//Console.WriteLine(inlineImagePath1);//Console.WriteLine(inlineImagePath2); // instantiate Attachment object for each unique image.SendGrid.Helpers.Mail.AttachmentlogoImage=newSendGrid.Helpers.Mail.Attachment{ContentId="image1",Content=b64_1,Type="image/png",Disposition="inline",Filename="image-1.png"};SendGrid.Helpers.Mail.AttachmentstatusImage=newSendGrid.Helpers.Mail.Attachment{ContentId="image2",Content=b64_2,Type="image/gif",Disposition="inline",Filename="image-2.gif"};// collect AttachmentsvarimageAttachments=newList<SendGrid.Helpers.Mail.Attachment>{logoImage,statusImage};// pack info for transmissionvarcem=newComplexEmailModel{To="[email protected]",Subject="Look, Ma, Images!",TemplateBody=mailBodyContent,InlineAttachments=imageAttachments};varemailResp=awaitSendGridAPIMailService.TestEmailViaSendGridAPI(cem,SendGrid_FreeKey);Console.WriteLine(emailResp);}}}