Its very easy to send an email using .NET 2.0 and you can choose to send HTML and/or plain text using the AlternateView collection on the MailMessage class.

However until reading about it in my MCTS exam book i didn't realise that you could embed images (well anything i guess) into the email, i assumed you were limited to having to have them on a public website and then having a link to them... resulting in most email clients (gmail/outlook that i use) not downloading the images by default for security reasons. I'm sure you'll agree this is annoying, especially if you've spent time and money creating a fancy looking e-newsletter!

 


public static void SendEmail(MailAddress To, MailAddress From, string Subject, string ImageFilePath)
{
  //Create HTML body
  string htmlbody = "<html><body><h1>Hello!</h1><br /><img src=\"cid:Pic1\" /></body></html>";
  //Create HTML AlternativeView
  AlternateView avHTML = AlternateView.CreateAlternateViewFromString(htmlbody, null,   MediaTypeNames.Text.Html);
  //Create LinkedResource to hold the image
  LinkedResource pic1 = new LinkedResource(ImageFilePath, MediaTypeNames.Image.Gif);
  pic1.ContentId =
"Pic1";
  avHTML.LinkedResources.Add(pic1);
  //Add alternative view to message instead of using .Body
  MailMessage mail = new MailMessage();
  mail.AlternateViews.Add(avHTML);
  //Add addresses and subject
  mail.To.Add(To);
  mail.From = From;
  mail.Subject = Subject;
  //Send email
  SmtpClient smtp = new SmtpClient("smtpout.secureserver.net");
  smtp.Credentials = EmailCred;
  smtp.Send(mail);
}

Bookmark with :
Digg It! DZone StumbleUpon Technorati Reddit Del.icio.us Newsvine Furl Blinklist
posted @ Tuesday, June 12, 2007 10:36 AM | in C#

Comments

Gravatar
# re: MailMessage - HTML emails with images using LinkedResource
Posted by Christian
on 8/22/2008 10:19 AM
Great!! Thanks mate!
Gravatar
# re: MailMessage - HTML emails with images using LinkedResource
Posted by peter
on 6/3/2009 8:57 PM
That is a pretty lousy code.
The tricky part is completely left out. I'm referring to the ImageFilePath. Attaching an image through linkresource is not at all that easy, cause it force you to have the image located somewhere on the hard drive which is just not possible if using a web hotel. Writing relative, virtual or http:// paths are neither possible.

Post Comment

Title *
Name *
Email
Url
Comment *  


Please add 8 and 1 and type the answer here: