This is a mirror of official site:

Send an email with an embedded image in its body

| Wednesday, May 2, 2012

The article is about how to send an email with an image within its body and not as an attachment (like a company's logo). The only possible solution is to format the body of the message as an "HTML" document. We will have to use the .NET classes LinkedResource and AlternateView as merely setting the src of the HTML <img> tag won't help.


Before going through this article, we need to have a basic understanding of ASP.NET 2.0 (and ofcourse, HTML).

Using the code

First of all, we need to import the namespace System.Net.Mail. Then in the configSections of the web.config file, add the following:

<add key="SMTP" value="SMTP Address"/>  //like
<add key="MailFrom" value="Mail From"/>
<add key="Port" value="Port Number"/> //usually 25
<add key="MailUserName" value="user name of the mail from which the mail will be sent"/>
<add key="MailPwd" value="Password"/>
<add key="To" value="To whom you're sending the mail"/>
<add key="CC" value="If there's any cc to add"/>

Now in the .NET class file, write the following code. (Note that here we are not concerned about validations.)

 Collapse | Copy Code
MailMessage msg = new MailMessage();

string To, Cc;
string strMailContent = "You can include your text here";

To = ConfigurationManager.AppSettings["To"].ToString();
Cc = ConfigurationManager.AppSettings["CC"].ToString();

//checking that if there exist a Cc
if (Cc != "" && Cc != String.Empty && Cc != null)
msg.From = new MailAddress(ConfigurationManager.AppSettings["MailUserName"].ToString());
msg.Subject = sub;

string path = Server.MapPath(@"images/Logo.jpg"); // my logo is placed in images folder

LinkedResource logo = new LinkedResource(path);
logo.ContentId = "companylogo";

//now do the HTML formatting
AlternateView av1 = AlternateView.CreateAlternateViewFromString(
      "<html><body><img src=cid:companylogo/>" + 
      "<br></body></html>" + strMailContent, 
      null, MediaTypeNames.Text.Html);

//now add the AlternateView

Read more: Codeproject
QR: Inline image 1

Posted via email from Jasper-net