Computers And Industry

Sending Email With Embedded Image C#


The following example shows how to construct an email message with an embedded image. This is different from simply attaching a file. This sample requires .net 4.6.2 but can be used in asp.net. This sample uses a console application to demonstrate functionality.

To use the sample, create an image with the name emailsampleimage.jpg and place it in your My Documents folder.

Using the Class


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Samples
{
  class EmailSendingMain
  {
    static void Main(string[] args)
    {
      Console.Title = "Email Sample";

      Console.WriteLine("***BEGIN SAMPLE OUTPUT***\n\n");

      EmailSendingSample em = new EmailSendingSample();
      em.RECIPIENT = "you@email.com";
      em.SENDER = "someone@email.com";
      em.SMTP_SERVER = "your.smtp.server";
      em.SMTP_UID = "userid";
      em.SMTP_PWD = "password";



      // do the send
      int rc = em.SendMail().Result;


      Console.WriteLine("\n\n***END SAMPLE OUTPUT***");
      Console.ReadKey();
    }
  }
}

// END PROGRAM




The Email Sending Class


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using System.Net.Mail;
using System.Net;
using System.Net.Mime;
using System.Diagnostics;

// add reference to presentation core.
using System.Windows.Media.Imaging; 

namespace Samples
{
  class EmailSendingSample
  {


    public string SENDER { get; set; }
    public string RECIPIENT { get; set; }
    public string JPEG_IMAGE_FILENAME { get; set; }
    public string MESSAGE_HTML { get; set; }
    public string MESSAGE_TEXT { get; set; }
    public string SUBJECT { get; set; }


    public int SMTP_PORT { get; set; }
    public string SMTP_SERVER { get; set; }
    public string SMTP_UID { get; set; }
    public string SMTP_PWD { get; set; }
    public int TIMEOUT_IN_SECONDS { get; set; }

    // constructor
    public EmailSendingSample()
    {
      SENDER = "";
      RECIPIENT = "";
      SMTP_SERVER = "";
      SMTP_UID = "";
      SMTP_PWD = "";
      SMTP_PORT = 25;
      TIMEOUT_IN_SECONDS = 60;
      SUBJECT = "Email Embedded Image Sending Sample";

      MESSAGE_HTML = "" +
               "" +
               "This is a test message with embedded image." + 
               "

" + "" + "

" + "Pretty Cool" + ""; JPEG_IMAGE_FILENAME = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\emailsampleimage.jpg"; } // sends a simple message with an attachment. public async Task SendMail() { int rc = -1; // create the image uri. Uri imgUri = new Uri(JPEG_IMAGE_FILENAME); // load the bitmap image. THis is WPF so you can // use this sample in an app. ie make sure to // add a reference to presentationcore BitmapImage bImage = new BitmapImage(imgUri); // create a new bitmap frame from the bitmap image. // windows.base must be referenced. We use this // to add to the jpeg encoder BitmapFrame bFrame = BitmapFrame.Create(bImage); // create an encoder because we will use this // to get the image in the form of a stream JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder(); // add the image as a frame to the encoder jpgEncoder.Frames.Add(bFrame); // create a memory stream variable MemoryStream jpgMemoryStream = new MemoryStream(); // now write the jpeg in the Encoder to // the memory stream jpgEncoder.Save(jpgMemoryStream); // set the stream pointer back to the beginning jpgMemoryStream.Seek(0, SeekOrigin.Begin); // now make a linked resource LinkedResource rsc = new LinkedResource(jpgMemoryStream); // set the content id. NOTE. normally this is a guid but // for sample purposes, we are just going to use the key // jpeg_image_attachment. Reference the HTML in the // constructor. // NOTE. When specifying the image tag in the // email message, make sure you set the source to // src="cid:jpeg_image_attachment" rsc.ContentId = "jpeg_image_attachment"; // create a new contenttype object. this is in // System.Net.Mime ContentType conType = new ContentType("image/jpeg"); // set the content type property of the // linked resource object. rsc.ContentType = conType; // AT THIS POINT, WE ARE DONE WITH THE IMAGING, // WE HAVE A LINKED RESOURCE THAT WE WILL ADD // TO THE ALTERNATE VIEW OF THE MESSAGE LATER. // build the html message. MailMessage mMsg = new MailMessage(); // set message html property mMsg.IsBodyHtml = true; // create the sender mailaddress object MailAddress sdr = new MailAddress(SENDER); mMsg.From = sdr; // set the message recipient MailAddress rcp = new MailAddress(RECIPIENT); mMsg.To.Add(rcp); // set the subject mMsg.Subject = SUBJECT; // create an alternate view. AlternateView av = AlternateView.CreateAlternateViewFromString(MESSAGE_HTML, null, System.Net.Mime.MediaTypeNames.Text.Html); // add the linked resource to the alternate view. av.LinkedResources.Add(rsc); // add the alternate view to the message mMsg.AlternateViews.Add(av); // AT THIS POINT, WE HAVE BUILT THE EMAIL // MESSAGE, NOW WE SEND THE MESSAGE. // now define the smtp client SmtpClient cli = new SmtpClient(); cli.Port = SMTP_PORT; cli.EnableSsl = true; cli.Host = SMTP_SERVER; cli.Credentials = new NetworkCredential(SMTP_UID, SMTP_PWD); cli.DeliveryMethod = SmtpDeliveryMethod.Network; cli.Timeout = TIMEOUT_IN_SECONDS * 1000; // now send the message try { // send the message. Note we are // sending the mMsg object await cli.SendMailAsync(mMsg); // return code of zero. No error. Console.WriteLine("Message Sent Successfully"); rc = 0; } catch (Exception e) { rc = e.HResult; Console.WriteLine(e.Source + ": " + e.Message); } // dispose the smtp client cli.Dispose(); // dispose the message mMsg.Dispose(); // dispose the linked resource rsc.Dispose(); // dispose the alternate view av.Dispose(); // dispose the memory stream jpgMemoryStream.Dispose(); return rc; } } }
Open Source

Paul F. Sirpenski
Personal Open Source Directory Of Paul F. Sirpenski

ASP.NET Core
Open Source directory Of the Microsoft Asp.Net Core project.

Developed By Paul F. Sirpenski. Copyright 2022.