C# - Send an HTML email containing an embedded image via SMTP

By , 12/5/2012
(0 ratings)
Following example shows, how to send an HTML-email containing an included image.

It has already be shown, how a text-email can be sent over SMTP (http://dotnet-snippets.de/dns/mail-senden-mit-authentifizierung-unter-net-20-SID36.aspx).

Author: Günther Foidl, translation by Michael List
using System.Net;
using System.Net.Mail;
using System.Text;

namespace HTMLMail_with_Image
{
	class Program
	{
		static void Main(string[] args)
		{
			// Create Email:
			MailMessage mailMessage = new MailMessage(
				new MailAddress("to@tirol.at", "Receiver"),
				new MailAddress("test@tirol.at", "Test"));
			mailMessage.Subject = "Subject";
			mailMessage.ReplyTo = new MailAddress("replyaddress@tirol.at", "No Reply");

			// HTML-part of the email. To include an image, you have
			// to use the prefix 'cid' in the <img>-Tag to map
			// the ContentID for the included ressource:
			AlternateView htmlView =
				AlternateView.CreateAlternateViewFromString(
					"HTML content as String",
					Encoding.UTF8,
					"text/html");

			// Embedded ressource:
			LinkedResource logo = new LinkedResource(
				"Path to the image to be embedded");

			// ContentID -> see comment above for the included image
			logo.ContentId = "MyID";

			// Add embedded ressource to the HTML view:
			htmlView.LinkedResources.Add(logo);

			// Add HTML view to the mail:
			mailMessage.AlternateViews.Add(htmlView);

			// Send mail:
			new SmtpClient().Send(mailMessage);

			SmtpClient smtp = new SmtpClient("myHost");
			smtp.Credentials = new NetworkCredential(
				"UserName",
				"Password");
			smtp.Send(mailMessage);
		}
	}
}
Tagged with Email, HTML email, send email, mail, image.

Comments

 

Log in, to comment!