This tutorial will demonstrate how to send emails with images in them using ASP.NET 4.0 and C#.

There are a few different ways that you can send images via email. The easiest way to do this is to simply make the body of the email html and add in an tag that links directly to the image on the internet. However, because this has been abused by email spammers an image sent like that will most likely not be viewed depending on the recipients email settings. In this tutorial we will demonstrate how to send an email with an attached image displayed in the messages body.

Adding the Default.aspx Page

To demonstrate this I am going to create a simple web site with a button in it that I will use to send the email. At this point in the tutorial I have created a new ASP.NET Empty Web Site. To begin:

  1. Right click the project in your solution explorer.
  2. Select add new item…
  3. Select a web form.
  4. Name it ‘Default.aspx’.
  5. Click add.
  6. Open Default.aspx up to design mode.
  7. Drag and drop a button onto the web form.

Adding the Image

For this example, I will be adding an image to the project so that we can simplify the code here, however you can use whatever image you want. To do this:

  1. Right click the project in your solution explorer.
  2. Select add existing item…
  3. Select the image you want to add.
  4. Click add.

Sending the Email

Next, we need to add in the code to send the email. It is important to understand that you will need access to your own email account to which you know the SMTP settings in order to send an email. For this code sample I wll be configuring the SMTP settings to send an email using Gmail. However, you can use whatever email you want as long as it is configured properly. To begin:

  1. Open Default.aspx to design mode.
  2. Double click the button we added earlier to generate the click event method for it.
  3. Add the following using statements at the top of the Default.aspx.cs class:

  4. Add the following code to the Button1_Click event method to send the email:

What this is doing is creating a new email message and attaching an image to it. Then, in the body we add an tag that links to the image in the attachment of the email. This way, your image is more likely to show up to the recipient based on their email settings.

Testing

To test this out, modify the Button1_Click event method to work with your corresponding email address and provider. Then, change the recipient email to one of your email accounts. Once this is done, load up the web site and click the button to send the email. Then, verify that the email is sent and the proper image is attached and viewable within your email.
Download Source Files