Downloading And Embedding Images In Your Emails Using SMTP Client With C#

Introduction

This blog will elaborate how to download and embed images in your emails, using SMTP Client with C#.

Send Email Code

Sending an email using SMTP client requires the following things:

  1. SMTP client address get from OutboundMailServiceInstance.Server.Address.
  2. Reply to email address OutboundMailReplyToAddress
  3. To address email ids.
  4. CC address email ids.
  5. BCC address email ids.
  6. Subject line of email.
  7. Body text with image links attached, as the example shown below:
    1. <html><body><img src="http://serverurl.com/images/picture.jpg"></body></html>   
  8. URL of server containing the image.
  9. Reply to display name.

To download and embed an image in body, we need to call the GenerateImagesForMail function.

The following code snippet shows how to send the emails using SMTP.

  1. private void SendEmail(string smtpClientAddress, string outboundMailReplyToAddress, string toAddress, string ccAddress, string bccAddress, string subject, string bodyText, string url, string replyToDisplayName) {  
  2.     using(MailMessage message = new MailMessage()) {  
  3.         message.From = new MailAddress(outboundMailReplyToAddress, replyToDisplayName);  
  4.         message.Subject = subject;  
  5.         string body = HttpUtility.HtmlDecode(bodyText);  
  6.         message.Priority = MailPriority.High;  
  7.         if (!string.IsNullOrEmpty(toAddress)) {  
  8.             string[] allTOAddresses = toAddress.Split(';');  
  9.             foreach(string address in allTOAddresses) {  
  10.                 if (!string.IsNullOrWhiteSpace(address)) {  
  11.                     MailAddress mailTOAddress = new MailAddress(address);  
  12.                     message.To.Add(mailTOAddress);  
  13.                 }  
  14.             }  
  15.         }  
  16.         if (!string.IsNullOrEmpty(ccAddress)) {  
  17.             string[] allCCAddresses = ccAddress.Split(';');  
  18.             foreach(string address in allCCAddresses) {  
  19.                 if (!string.IsNullOrWhiteSpace(address)) {  
  20.                     MailAddress mailCCAddress = new MailAddress(address);  
  21.                     message.CC.Add(mailCCAddress);  
  22.                 }  
  23.             }  
  24.         }  
  25.         if (!string.IsNullOrEmpty(bccAddress)) {  
  26.             string[] allBCCAddresses = bccAddress.Split(';');  
  27.             foreach(string address in allBCCAddresses) {  
  28.                 if (!string.IsNullOrWhiteSpace(address)) {  
  29.                     MailAddress mailBCCAddress = new MailAddress(address);  
  30.                     message.Bcc.Add(mailBCCAddress);  
  31.                 }  
  32.             }  
  33.         }  
  34.         GenerateImagesForMail(url, message, ref body);  
  35.         message.IsBodyHtml = true;  
  36.         using(SmtpClient smtp = new SmtpClient(smtpClientAddress)) {  
  37.             try {  
  38.                 smtp.Send(message);  
  39.             } catch (SmtpFailedRecipientsException) {  
  40.                 throw;  
  41.             } catch (SmtpException) {  
  42.                 throw;  
  43.             } catch (Exception ex) {  
  44.                 //Cache error   
  45.             }  
  46.         }  
  47.     }  
  48. }  
Downloading and Embedding Images

To download and embed an image, we require the following things:

 

  1. Find the images in HTML body.
  2. Download the image using DownloadData method.
  3. Attach the downloaded image to the HTML body.
  4. Create an AlternateView object for those supporting the HTML content.
  5. Create a LinkedResource object for the inline image to send.
  6. Add a LinkedResource object to the AlternateView object.
  7. Check the correct Image location otherwise it will throw an error.

The following code snippet shows how to download and embed an image to the HTML body content.

  1. private void GenerateImagesForMail(string url, MailMessage message, ref string body) {  
  2.     try {  
  3.         string imageSrcPattern = "<img.+?src=[\"'](.+?)[\"'].+?>";  
  4.         var imgSrcMatches = System.Text.RegularExpressions.Regex.Matches(body, imageSrcPattern, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Multiline);  
  5.         List < string > imgSrcs = new List < string > ();  
  6.         foreach(Match match in imgSrcMatches) {  
  7.             imgSrcs.Add(match.Groups[1].Value);  
  8.         }  
  9.         var webClient = new WebClient();  
  10.         Dictionary < stringstring > srcValues = new Dictionary < stringstring > ();  
  11.         lock(((ICollection) srcValues).SyncRoot) {  
  12.             foreach(var src in imgSrcs.Distinct()) {  
  13.                 if (!src.Contains("http:")) {  
  14.                     if (!src.Contains("https:")) {  
  15.                         srcValues.Add(src, url + src);  
  16.                     } else {  
  17.                         srcValues.Add(src, src);  
  18.                     }  
  19.                 } else {  
  20.                     srcValues.Add(src, src);  
  21.                 }  
  22.             }  
  23.         }  
  24.         int count = 1;  
  25.         List < LinkedResource > linkedResources = new List < LinkedResource > ();  
  26.         try {  
  27.             foreach(KeyValuePair < stringstring > entry in srcValues) {  
  28.                 byte[] imageBytes = webClient.DownloadData(entry.Value);  
  29.                 MemoryStream img = new MemoryStream(imageBytes);  
  30.                 if (body.Contains(entry.Key)) {  
  31.                     body = body.Replace(entry.Key, "cid:img" + count + "");  
  32.                 }  
  33.                 LinkedResource imgLink = new LinkedResource(img, MediaTypeNames.Image.Jpeg);  
  34.                 imgLink.ContentId = "img" + count + "";  
  35.                 linkedResources.Add(imgLink);  
  36.                 count++;  
  37.             }  
  38.         } catch (Exception ex) {  
  39.             //Catch error   
  40.         }  
  41.         AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);  
  42.         if (linkedResources != null) {  
  43.             foreach(var linkedResource in linkedResources) {  
  44.                 htmlView.LinkedResources.Add(linkedResource);  
  45.             }  
  46.         }  
  47.         message.AlternateViews.Add(htmlView);  
  48.     } catch (Exception ex) {  
  49.         //Catch error   
  50.     }  
  51. }  
Now, we can use the SendEmail () method to send the email. The received email will look like the following:

output

Summary

Thus, you have learned how to download and embed images in your emails using SMTP Client with C#.

 

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now