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
using System;using System.Collections.Generic;using System.ComponentModel;using System.Net;using System.Net.Mail;using System.Text;using System.Threading.Tasks;using Microsoft.AspNetCore.Mvc;using SendGrid.SmtpApi;using SendGrid;using SendGrid.Helpers.Mail;using Microsoft.Azure.WebJobs;publicstaticasyncTask<IActionResult>TestEmailViaSendGridAPI(ComplexEmailModelcem,stringsendGridApiKey){try{// Credentialsvarclient=new SendGridClient(sendGridApiKey);// Email Basicsvarfrom=new EmailAddress(cem.From);// needs to be whitelisted with service providervarto=new EmailAddress(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(var att in cem.InlineAttachments)
msg.AddAttachment(att);// send email & report resultsvarresponse=await client.SendEmailAsync(msg);if(response.IsSuccessStatusCode)returnnew OkObjectResult(response);elsereturnnew BadRequestObjectResult(response);}catch(Exceptionwtf){returnnew BadRequestObjectResult(wtf.Message);}}
Example Model
publicclassComplexEmailModel{[JsonProperty("from")]publicstringFrom{get;set;}="no-reply@matchhub.us";[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";staticasync System.Threading.Tasks.Task Main(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.StreamReader str=new System.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.Attachment logoImage=new SendGrid.Helpers.Mail.Attachment
{ContentId="image1",Content=b64_1,Type="image/png",Disposition="inline",Filename="image-1.png"};
SendGrid.Helpers.Mail.Attachment statusImage=new SendGrid.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=new ComplexEmailModel
{To="recipient@gmail.com",Subject="Look, Ma, Images!",TemplateBody=mailBodyContent,InlineAttachments=imageAttachments};varemailResp=await SendGridAPIMailService.TestEmailViaSendGridAPI(cem, SendGrid_FreeKey);
Console.WriteLine(emailResp);}}}