Creating Mail Messages in C#

There are several steps we have to go through in order to create and send email from within our C# code. First, we create MailMessage object using System.Net.Mail namespace. Second we need to specify recipients of this email. We can do it via constructor or add them to MailMessage object. Third, we need to set our email view. For instance we can specify that our email body is HTML which can be done with the help of AlternateView object. Fourth, we can add attachment to our email with the help of Attachment objects. Fifth, we create SmtpClient object and set SMTP server and if SMTP server requires authentication, we add these required credentials via SmtpClient object as well. Finally, we pass out MailMessage object to SmtpClient.Send method or SmtpClient.SendAsync if we want to send our email asynchronously.

string htmlBody = "<html><body><h1>Pic</h1><br><img src=\"cid:Pic1\"></body></html>";
AlternateView avHtml = AlternateView.CreateAlternateViewFromString
    (htmlBody, null, MediaTypeNames.Text.Html);
LinkedResource pic1 = new LinkedResource("pic.jpg", MediaTypeNames.Image.Jpeg);
pic1.ContentId = "Pic1";
avHtml.LinkedResources.Add(pic1);
string textBody = "You must use an e-mail";
AlternateView avText = AlternateView.CreateAlternateViewFromString
    (textBody, null, MediaTypeNames.Text.Plain);
MailMessage m = new MailMessage();
m.AlternateViews.Add(avHtml);
m.AlternateViews.Add(avText);
m.From = new MailAddress("lance@contoso.com", "Lance Tucker");
m.To.Add(new MailAddress("james@contoso.com", "James van Eaton"));
m.Subject = "A picture using alternate views";
SmtpClient client = new SmtpClient("smtp.contoso.com");
client.Send(m);

We can reference images attached as linked resources from your HTML message body, use "cid:contentID" in the <img> tag.