@bobnoordam

Sending email with an inline image

While you will usualy link images to a static location, there are situations where it can be very practical to include the actual image in the message and send it inline. This code snippet is a demonstration of the minimal code required to send an email message with an inline image using C#.

using System.Net.Mail;
 
namespace EmbeddedImageMailDemo
{
 
    /// <summary>
    /// Demonstration of the minimal code required to send an email message with an inline image
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
 
            // Initialisation
            string sendermail = "someone@somewhere.com";
            string receivermail = "someoneelse@someoneelse.com";
            string mailserver = "your.smtpserver.local";
 
            // Base email message
            var msg = new MailMessage();
            msg.IsBodyHtml = true;
            msg.From = new MailAddress(sendermail);
            msg.To.Add(receivermail);
            msg.Subject = "Demo email with image";
 
            // Create the embedded resource and the body
            LinkedResource lr = new LinkedResource(@".\myimage.jpg", "image/jpeg");
            lr.ContentId = "myimage";
            string bodytext = "<img src='cid:myimage' />";
            bodytext += "This is my testmail with embedded image below!";
            AlternateView htmlview = AlternateView.CreateAlternateViewFromString(bodytext, new System.Net.Mime.ContentType("text/html"));
            htmlview.LinkedResources.Add(lr);
            msg.AlternateViews.Add(htmlview);
 
            // Send the message
            var smtp = new SmtpClient(mailserver);
            smtp.Send(msg);
 
        }
    }
}