Aug 23, 2012

In Asp.net, how do I embed images in an email?


static void EmbedImages()
{
//create the mail message
MailMessage mail = new MailMessage();

//set the addresses
mail.From = new MailAddress("me@mycompany.com");
mail.To.Add("you@yourcompany.com");

//set the content
mail.Subject = "This is an email";

//first we create the Plain Text part
AlternateView plainView = AlternateView.CreateAlternateViewFromString("This is my plain text content, viewable by those clients that don't support html", null, "text/plain");

//then we create the Html part
//to embed images, we need to use the prefix 'cid' in the img src value
//the cid value will map to the Content-Id of a Linked resource.
//thus <img src='cid:companylogo'> will map to a LinkedResource with a ContentId of 'companylogo'
AlternateView htmlView = AlternateView.CreateAlternateViewFromString("Here is an embedded image.<img src=cid:companylogo >", null, "text/html");

//create the LinkedResource (embedded image)
LinkedResource logo = new LinkedResource( "c:\\temp\\logo.gif" );
logo.ContentId = "companylogo";

//add the LinkedResource to the appropriate view
htmlView.LinkedResources.Add(logo);

//add the views
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);


//send the message
SmtpClient smtp = new SmtpClient("127.0.0.1"); //specify the mail server address
smtp.Send(mail);
}

4 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. Yes, you can do it dynamic image upload from machine and embed image into email.

    You need to first store into server then pass file path name into LinkedResource object


    LinkedResource logo = new LinkedResource(dynamicFilePath);




    Dynamic file path pass as a parameter


    static void EmbedImages(string dynamicFilePath)





    I hope you get my point.

    ReplyDelete
  3. This comment has been removed by a blog administrator.

    ReplyDelete
  4. This comment has been removed by a blog administrator.

    ReplyDelete