Home
    Shop
    Advertise
    Write For Us
    Affiliate
    Newsletter
    Contact

How to Add an Image to Email in ASP.NET

Email is extremely popular way of communication. To make this task easier, Microsoft .Net Framework contains System.Net.Mail namespace. Here are all classes that you need to work with emails. To learn basics, about how to send simple email and add file attachment, see E-Mail in ASP.NET tutorial. In this tutorial we'll see which options are existing if you want to show an images in email. With images in HTML email you can achieve beautiful design and professional look of your newsletter or any other email.

 

To add an image to email message you can use one of these three methods:

- Add an image to email using absolute URL
- Add an image to email using file attachment
- Add an image to email using LinkedResource class

Every method has its own advantages and disadvantages. Depending of your specific needs you can choose the most appropriate method.

Add an image to email using absolute URL

Using absolute URLs is simplest way to add images to email message. To show an image, you need to create HTML email, because you can't use <img > tag in plain text. Image should be stored on your server and requested when visitor reads an email. Code implementation could look like this:

[ C# ]

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
// We need System.Net.Mail namespace when working
// with emails
using System.Net.Mail;
 
public partial class _Default : System.Web.UI.Page
{
 protected void btnSendEmail_Click(object sender, EventArgs e)
 {
   // Create new mail message
   MailMessage mail = new MailMessage();
   // Set recipient email, you can use Add() method to add
   // more than one recipient
   mail.To.Add("recipient@example.com");
   // Set sender email address
   mail.From = new MailAddress("sender@example.com");
   // Set subject of an email
   mail.Subject = "Email with external image";
   // Set mail body. Body contains absolute path to external image
   mail.Body = @"This is an email with image included <br />
               <img src=""http://www.beansoftware.com/Images/Logo.jpg"" alt=""Logo"" /><br />
               But, many mail clients will block external images by default";
 
   // Plain text emails can't display images, so change body to HTML type
   mail.IsBodyHtml = true;
   // Create instance of Smtp client
   SmtpClient sc = new SmtpClient("mail.server.com");
   // If your ISP required it, set user name and password
   sc.Credentials = new System.Net.NetworkCredential("MyUserName", "Password");
   // Finally, send created email
   sc.Send(mail);
 } }

[ VB.NET ]

' We need System.Net.Mail namespace when working
' with emails
Imports System.Net.Mail
 
Partial Class Default2
 Inherits System.Web.UI.Page
 
 Protected Sub btnSendEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSendEmail.Click
   ' Create new mail message
   Dim MyMail As MailMessage = New MailMessage()
   ' Set recipient email, you can use Add() method to add
   ' more than one recipient
   MyMail.To.Add("recipient@example.com")
   ' Set sender email address
   MyMail.From = New MailAddress("sender@example.com")
   ' Set subject of an email
   MyMail.Subject = "Email with external image"
   ' Set mail body. Body contains absolute path to external image
   MyMail.Body = "This is an email with image included <br />" & _
     "<img src=""http://www.beansoftware.com/Images/Logo.jpg"" alt=""Logo"" /><br />" & _
     "But, many mail clients will block external images by default"
 
   ' Plain text emails can't display images, so change body to HTML type
   MyMail.IsBodyHtml = True
 
   ' Create instance of Smtp client
   Dim MySmtpClient As SmtpClient = New SmtpClient("mail.server.com")
   ' If your ISP required it, set user name and password
   MySmtpClient.Credentials = New System.Net.NetworkCredential("MyUserName", "Password")
   ' Finally, send created email
   MySmtpClient.Send(MyMail)
 End Sub
End Class

Using absolute URLs is very useful if you need to find information about recipient. Instead of showing static image, absolute URL is directed to dynamic ASP.NET page. ASP.NET code gather information about recipient, like IP address, geographic location, operating system etc., and then returns requested image. More about gathering visitor's information through a dynamically created image you can find in Tracking Your Website's Visitors and Statistic in ASP.NET tutorial.

Unfortunately, this method was abused by spammers in the past and today many email clients, including MS Outlook will not show images with absolute URLs because of security issues. Instead, recipient will see a notification and choose to load images or not.

Add an image to email using file attachment

Another option is to send an image as a part of email. On this way, recipient will see an attached image, but you can't identify recipient's computer with ASP.NET code on web server. This is OK if you just want to create better looking email and don't want to spy your newsletter subscribers. It is possible to send an image as file attachment or to use LinkedResource class. First, let's look at the code example of sending HTML email with image as file attachment.

[ C# ]

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
// We need System.Net.Mail namespace when working
// with emails
using System.Net.Mail;
 
public partial class _Default : System.Web.UI.Page
{
 protected void btnSendEmail_Click(object sender, EventArgs e)
 {
   // Create new mail message
   MailMessage mail = new MailMessage();
   // Set recipient email, you can use Add() method to add
   // more than one recipient
   mail.To.Add("recipient@example.com");
   // Set sender email address
   mail.From = new MailAddress("sender@example.com");
   // Set subject of an email
   mail.Subject = "Email with inline image";
   // Create mail body string. Body includes an image tag
   mail.Body = @"This is an email with image included <br />
       <img src=""cid:Logo.gif"" /><br />
       But, depending of settings of mail client
       some recipients will see only plain text";
 
   // Set mail body as HTML
   mail.IsBodyHtml = true;
 
   // Create file attachment
   Attachment ImageAttachment = new Attachment(Server.MapPath("/Images/Logo.jpg"));
   // Set the ContentId of the attachment, used in body HTML
   ImageAttachment.ContentId = "Logo.jpg";
 
   // Add an image as file attachment
   mail.Attachments.Add(ImageAttachment);
       
   // Create instance of Smtp client
   SmtpClient sc = new SmtpClient("mail.server.com");
   // If your ISP required it, set user name and password
   sc.Credentials = new System.Net.NetworkCredential("MyUserName", "Password");
   // Finally, send created email
   sc.Send(mail);
 }
}

[ VB.NET ]

' We need System.Net.Mail namespace when working
' with emails
Imports System.Net.Mail
 
Partial Class Default2
 Inherits System.Web.UI.Page
 
 Protected Sub btnSendEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSendEmail.Click
   ' Create new mail message
   Dim MyMail As MailMessage = New MailMessage()
   ' Set recipient email, you can use Add() method to add
   ' more than one recipient
   MyMail.To.Add("recipient@example.com")
   ' Set sender email address
   MyMail.From = New MailAddress("sender@example.com")
   ' Set subject of an email
   MyMail.Subject = "Email with inline image"
   ' Create mail body string. Body includes an image tag
   MyMail.Body = "This is an email with image included <br />" & _
    "<img src=""cid:InlineImageID"" /><br />" & _
    "But, depending of settings of mail client " & _
    "some recipients will see only plain text"
 
   ' Set mail body as HTML
   MyMail.IsBodyHtml = True
 
   ' Create file attachment
   Dim ImageAttachment As Attachment = New Attachment(Server.MapPath("/Images/Logo.jpg"))
   ' Set the ContentId of the attachment, used in body HTML
   ImageAttachment.ContentId = "Logo.jpg"
 
   ' Add an image as file attachment
   MyMail.Attachments.Add(ImageAttachment)
 
   ' Create instance of Smtp client
   Dim MySmtpClient As SmtpClient = New SmtpClient("mail.server.com")
   ' If your ISP required it, set user name and password
   MySmtpClient.Credentials = New System.Net.NetworkCredential("MyUserName", "Password")
   ' Finally, send created email
   MySmtpClient.Send(MyMail)
 End Sub
End Class

Email recipient will get a message similar like this:

Email with image attachment

As you see, image is placed inside of body HTML where I placed an image tag, but also listed in attachments section and at the bottom of the message. This probably looks unprofessional for newsletter but it is useful in some scenario where you want to enable user to easily save an images to local disc. To show an image only in body HTML and not listed as attachment, you need LinkedResource class, explained in next example.

Add an image to email using LinkedResource class

Last method for adding an image to email is by using of LinkedResource class. On this way, image is sent as part of mail like when using file attachment. Recipient will see an image without problems although your bandwidth costs may increase significantly if images and/or your mail list is large. I must mention AlternateView class used in this method. Some recipients will configure their mail clients to display messages as plain text only. AlternateView class is used to provide correct alternate view of message for different user's settings.

Here is code example for sending email with inline image using LinkedResource and AlternateView classes:

[ C# ]

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
// We need System.Net.Mail namespace when working
// with emails
using System.Net.Mail;
 
public partial class _Default : System.Web.UI.Page
{
 protected void btnSendEmail_Click(object sender, EventArgs e)
 {
   // Create new mail message
   MailMessage mail = new MailMessage();
   // Set recipient email, you can use Add() method to add
   // more than one recipient
   mail.To.Add("recipient@example.com");
   // Set sender email address
   mail.From = new MailAddress("sender@example.com");
   // Set subject of an email
   mail.Subject = "Email with inline image";
   // Create mail body string.
   string EMailBody = @"This is an email with image included <br />
            <img src=""cid:InlineImageID"" /><br />
            But, some mail clients will show plain text message";
 
   // Now we'll create two email views: HTML and plain text
   // First, create HTML view
   AlternateView HTMLEmail = AlternateView.CreateAlternateViewFromString(EMailBody,
           null, "text/html");
   // Create plain text view for those visitors who prefer text only messages
   AlternateView PlainTextEmail = AlternateView.CreateAlternateViewFromString(EMailBody, null, "text/plain");
 
   // We'll need LinkedResource class to place an image to HTML email
   LinkedResource MyImage = new LinkedResource("c:\\Images\\MyImage.gif");
   // Set ContentId property. Value of ContentId property must be the same as
   // the src attribute of image tag in email body. In this case it is
   // <img src="cid:InlineImageID" />
   MyImage.ContentId = "InlineImageID";
 
   // Add this linked resource to HTML view
   HTMLEmail.LinkedResources.Add(MyImage);
 
   // Add plain text and HTML views to an email
   mail.AlternateViews.Add(HTMLEmail);
   mail.AlternateViews.Add(PlainTextEmail);
 
   // Create instance of Smtp client
   SmtpClient sc = new SmtpClient("mail.server.com");
   // If your ISP required it, set user name and password
   sc.Credentials = new System.Net.NetworkCredential("MyUserName", "Password");
   // Finally, send created email
   sc.Send(mail);
 }
}

[ VB.NET ]

' We need System.Net.Mail namespace when working
' with emails
Imports System.Net.Mail
 
Partial Class Default2
 Inherits System.Web.UI.Page
 
 Protected Sub btnSendEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSendEmail.Click
   ' Create new mail message
   Dim MyMail As MailMessage = New MailMessage()
   ' Set recipient email, you can use Add() method to add
   ' more than one recipient
   MyMail.To.Add("recipient@example.com")
   ' Set sender email address
   MyMail.From = New MailAddress("sender@example.com")
   ' Set subject of an email
   MyMail.Subject = "Email with inline image"
   ' Set mail body.
   Dim EMailBody As String = "This is an email with image included <br />" & _
       "<img src=""cid:InlineImageID"" /><br />" & _
       "But, many mail clients will block external images by default"
 
   ' Now we'll create two email views: HTML and plain text
   ' First, create HTML view
   Dim HTMLEmail As AlternateView = AlternateView.CreateAlternateViewFromString( _
     EMailBody, Nothing, "text/html")
   ' Create plain text view for those visitors who prefer text only messages
   Dim PlainTextEmail As AlternateView = AlternateView.CreateAlternateViewFromString( _
     EMailBody, Nothing, "text/plain")
 
   ' We'll need LinkedResource class to place an image to HTML email
   Dim MyImage As LinkedResource = New LinkedResource("c:\Images\MyImage.gif")
   ' Set ContentId property. Value of ContentId property must be the same as
   ' the src attribute of image tag in email body. In this case it is
   ' <img src="cid:InlineImageID" />
   MyImage.ContentId = "InlineImageID"
 
   ' Add this linked resource to HTML view
   HTMLEmail.LinkedResources.Add(MyImage)
 
   ' Add plain text and HTML views to an email
   MyMail.AlternateViews.Add(HTMLEmail)
   MyMail.AlternateViews.Add(PlainTextEmail)
 
   ' Create instance of Smtp client
   Dim MySmtpClient As SmtpClient = New SmtpClient("mail.server.com")
   ' If your ISP required it, set user name and password
   MySmtpClient.Credentials = New System.Net.NetworkCredential("MyUserName", "Password")
   ' Finally, send created email
   MySmtpClient.Send(MyMail)
 End Sub
End Class

Conclusion

As you see, it really simple to insert images to email to create more professional look or better user experience. Be aware that every image will increase your bandwidth costs, so optimize your graphics, especially if you have large mail list. Sending a lot of large emails takes some time. During operation, it is possible to receive some problem, like script time out error. More about long time operations you can see at Long Time Operations in ASP.NET tutorial.

Although you can just restart operation if it is not completed successfully, your recipients certainly don't want to receive same large message several times. It is good practice to add some flag (e.g. in database) to know when mail to some recipient is sent without errors. Then, if error occurs, like Internet connection problem or script time out, you can just continue long operation without restarting and sending of same email to recipient twice.


Tutorial toolbar:  Tell A Friend  |  Add to favorites  |  Feedback  |   


comments powered by Disqus