Wednesday, October 28, 2009

Sending mails from C# with embedded images.

//Sample Code from MCTS 70-536 Kit

// Create the HTML message body
// Reference embedded images using the content ID

string htmlBody =
"[html][body][h1]Picture[/h1]img src=\"cid:Pic1\"][/body][/html]";

AlternateView avHtml = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
// Create a LinkedResource object for each embedded image
LinkedResource pic1 = new LinkedResource("pic.jpg", MediaTypeNames.Image.Jpeg);
pic1.ContentId = "Pic1";
avHtml.LinkedResources.Add(pic1);
// Create an alternate view for unsupported client
sstring textBody ="You must use an e-mail client that supports HTML messages";
AlternateView avText = AlternateView.CreateAlternateViewFromString(textBody, null, MediaTypeNames.Text.Plain);
// Add the alternate views instead of using MailMessage.Body
MailMessage m = new MailMessage();
m.AlternateViews.Add(avHtml);
m.AlternateViews.Add(avText);
// Address and send the message
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);

No comments:

Post a Comment