Introduction
Sending and receiving emails is a daily task for almost every professional, and programmers are not different. Sending emails and attachment is considered a trivial task, and all programming platforms support this feature.
Background
You can send an email with images as external links, but most email clients block external links. There is another way around to send images as part of an email.
Using the code
The following code is self explanatory. Here, we go:
- Create a string that contains the HTML message to send.
- Create an
AlternateView object for supporting the HTML. - Create a
LinkedResource object for the image to send. - Add a
LinkedResource object to the AlternateView object. - Create a
Mailmesasge object and set its To, From, and Subject properties. - Add an
AlternateView object to the MailMessage object. - Create an
SmtpClient object and send the MailMessage object.
using System.Net.Mail;
string htmlBody = "<html><body><h1>Picture</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);
MailMessage m = new MailMessage();
m.AlternateViews.Add(avHtml);
m.From = new MailAddress("rizwan@dotnetplayer.com", "Rizwan Qureshi");
m.To.Add(new MailAddress("shayan@dotnetplayer.com", "Shayan Qureshi"));
m.Subject = "A picture using alternate views";
SmtpClient client = new SmtpClient("smtp.dotnetplayer.com");
client.Send(m);
Points of interest
Since embedded images are part of emails, they can considerably increase the size of emails and can cause an email client to treat them as spam.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.