Saturday, May 4, 2013

Email messages with embedded images

In the past I've had multiple projects where I've needed to create email templates that contained images for email blast and etc..  One of the biggest issues I've come across is that most email clients don't allow you to display images.  The reasoning behind this is because images you include are being downloaded from the web which could propose security risk to either the client and or the one receiving the email.  In this example you'll see the convention to access a linked resource is "cid:name" of the linked resource, which is the value of IMG tag SRC attribute.  There's one thing to consider when doing it this way.  The function will increase the size of the email, because the images will be embedded.  Have fun!!
public void SendImbeddedEmail()
{
var logo = new LinkedResource(@"C:\logo.jpg");
string from = "[EMAIL ADDRESS]";
string to = "[EMAIL ADDRESS]";
var subjust = "[EMAIL SUBJECT LINE]";
logo.ContentId = Guid.NewGuid().ToString();
var body = string.Format(@"< html >< body >< h1 >
Image< /h1 >
< img cid:="" src="" />< /body >< /html >", logo.ContentId);
var view = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
view.LinkedResources.Add(logo);

SmtpClient client = new SmtpClient("[SMTP SERVER]");
using (var message = new MailMessage(from, to)
 {
   Subject = subjust,
   Body = body,
   IsBodyHtml = true
 })
    {
      message.AlternateViews.Add(view);
      client.Send(message);
    }
}

No comments:

Post a Comment