MailMessage - HTML emails with images using LinkedResource

by Brad 12. June 2007 09:36

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);
}

Tags:

C#

Comments

8/22/2008 9:19:50 AM #

Great!! Thanks mate!

Christian |

6/3/2009 7:57:43 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.

peter |

Powered by BlogEngine.NET 1.5.0.7
Theme by Interakting

Interakting

A full service digital agency offering online strategy, design and usability, systems integration and online marketing services that deliver real business benefits and ensure your online objectives are met.

Calendar

<<  July 2010  >>
MoTuWeThFrSaSu
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

View posts in large calendar