Send Email with Inline Images & Attachments


When sending an email from an ASP.NET 2.0 page you will, typically:

1. Create a MailMessage object
2. Assign its properties
3. Create an instance of the SmtpClient class
4. Specify details about the SMTP server to use (if they’re not already specified within Web.config)
5. Send the MailMessage via the SmtpClient object’s Send method

ASP.NET makes it easy to utilise e-mail in an application with the System.Web.Mail namespace. Let’s take a closer look at putting this namespace to work in your applications.

System.Web.Mail namespace
The Microsoft documentation provides a good overview of the System.Web.Mail namespace. It’s composed of classes that allow you to create and send messages using the Collaboration Data Objects for Windows 2000 (CDOSYS) message component. The actual message may be delivered via the SMTP (Simple Mail Transfer Protocol) mail service built into Microsoft Windows 2000 and beyond or through an arbitrary SMTP server. The classes in this namespace aren’t restricted to an ASP.NET application.

The namespace includes three classes:

  • MailAttachment: Provides properties and methods for constructing an e-mail attachment.
  • MailMessage: Provides properties and methods for constructing an e-mail message.
  • SmtpMail: Provides properties and methods for sending messages using the CDOSYS message component.

MailAttachment class

The basic approach is the creation of a MailMessage object followed by sending it on its way via a SmtpMail object. The MailMessage class contains numerous methods and properties for working with an e-mail message. Properties such as From, Subject, and Body provide everything you need to create an e-mail message, but a SmtpMail object is still necessary for sending it on its way.

SmtpMail class

The SmtpMail class includes the SmtpServer property that gets or sets the name of the SMTP relay mail server to use to send messages, and the Send method actually sends the message. The Send method is overloaded. It allows a message to send using two approaches:

1. A MailMessage object is passed to the SmtpServer object. Four string objects may be passed to the SmtpServer object with the first being the From field followed by the Recipient, Subject, and the message’s Body.

2. You’ll use the MailAttachment and SmtpMail classes together to create the necessary messages in your application, but make sure the Web server is properly configured to send a message via SMTP. Since IIS (Internet Information Services) is the most popular platform for ASP.NET applications, go ahead and use both the IIS and SMTP services to send messages from your application.

Using SMTP with IIS

You can set up both IIS and SMTP services via the Windows control panel. The SMTP service’s role is to accept and deliver the messages using the server’s configuration. It may deliver the messages directly, or utilise a smart host to deliver the message instead. When a smart host is enlisted, all messages are forwarded to it for delivery.

A little more information is appropriate for debugging. The SMTP service uses a directory structure to contain messages prior to delivery with the default directory being C:\Inetpub\mailroot. It contains numerous subdirectories including Queue, Drop, and Badmail. If you’re unable to configure your instance of the SMTP Service for delivery, you can find the message in an EML file in the Queue subdirectory. The Badmail directory contains messages that that couldn’t be delivered. Now, let’s take a look at sending mail messages from your code.

Sending e-mail messages

To compose an e-mail message in your code, you need to start by creating an instance of the MailMessage class, as shown in the following C# snippet:

MailMessage msg = new MailMessage();

Be sure to include the System.Web.Mail namespace in your code:

using System.Web.Mail;

Once the object is instantiated, the various properties of the MailMessage class are used per your application. The following lines set the recipient, sender, and subject of the message:

msg.To = “test@test.com”;
msg.From = “me@test.com”;
msg.Subject = “Test Message”;

The next step is setting our mail server via the SmtpServer object’s SmtpServer property:

SmtpMail.SmtpServer = “smtp server name or address”;

The final step is sending the message by passing our MailMessage object to the SmtpMail object’s Send method:

SmtpMail.Send(msg);

Here I am Providing you the Complete Example of how to send Email with Inline Image / Multiple Attachments …etc…

—————————————-
Button Event Code
—————————————-

protected void Button1_Click(object sender, EventArgs e)
{
string from = “”, to = “”, cc = “”, subject = “”, body = “”, attachedfiles = “”;

from = “sandeep@gmail.com”;
to = “yogesh@gmail.com;sandeep@
gmail.com”; // multiple entry are separated bt ‘;’
cc = “jagat@
gmail.com”;
subject = “Testing Email Module”;

//Read Mail Template
StreamReader sr;
StringBuilder sb = new StringBuilder();
string BodyOfMail = “”;
sr = File.OpenText(Server.MapPath(“~/MailTemplate.txt”));
sb.Append(sr.ReadToEnd());
body = sb.ToString();

//attachments
attachedfiles = “E:\\Images\\1.jpg;E:\\Images\\2.jpg;”;
emailClass.SendEmail(from, to, cc, subject, body, attachedfiles);
}

—————————————-
MailTemplate.txt
—————————————-

<html >
<head>

<title>Untitled Document</title>

</head>
<body>
<form id=”form1″ name=”form1″ method=”post” action=””>
<table width=”100%” border=”0″ cellspacing=”10″ cellpadding=”10″>
<tr>
<td bgcolor=”#FFFFFF”>
<br />
<table width=”550″ border=”0″ cellpadding=”2″ cellspacing=”0″ bordercolor=”#FFFFFF”
id=”Comment Table2″>
<tr>
<td >
Hello Friend Name,<br />
<br />
Your friend has been send you this offer.
<br />
</td>
</tr>

<tr>
<td align=”right”>

<table width=”530″ border=”0″ cellpadding=”0″ cellspacing=”0″>
<tr>
<td >
<img src=”{images/logo1.jpg” />
</td>
<td >
<img src=”{images/logo2.jpg”  />
</td>
</tr>
</table>

</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
</body>
</html>

—————————————-
emailClass Class
—————————————-

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Mail;
using System.Net;

/// <summary>
/// Summary description for emailClass
/// </summary>
public class emailClass
{
public emailClass()
{
//
// TODO: Add constructor logic here
//
}
public static void SendEmail(string from, string to, string cc, string subject, string body, string attachedFiles)
{
try
{
MailMessage mailMsg = new MailMessage();
SmtpClient mailObj = new SmtpClient(“server”, 25);//”192.168.0.17″ – SmtpClient

//to authenticate we set the username and password properites on the SmtpClient
mailObj.Credentials = new NetworkCredential(“sandeep@
gmail.com”, “password”);

mailMsg.From = new MailAddress(from);

string[] temp = to.Split(‘;’);
for (int i = 0; i < temp.Length; i++)
{
if (temp[i].ToString().Length > 1)
mailMsg.To.Add(temp[i].ToString());
}

temp = cc.Split(‘;’);
for (int i = 0; i < temp.Length; i++)
{
if (temp[i].ToString().Length > 1)
mailMsg.CC.Add(temp[i].ToString());
}
temp = attachedFiles.Split(‘;’);
for (int i = 0; i < temp.Length; i++)
{
if (temp[i].ToString().Length > 1)
mailMsg.Attachments.Add(new Attachment(temp[i].ToString()));
}

mailMsg.Subject = subject;
mailMsg.Body = body;
mailMsg.IsBodyHtml = true;
int count = 0;
string oldChar = ExtractImages(body, ref count);
Random RGen = new Random();
while (oldChar != “”)
{
string imgPath = oldChar;
int startIndex = imgPath.ToLower().IndexOf(“images/”);
if (startIndex > 0)
{
imgPath = imgPath.Substring(startIndex);
imgPath = imgPath.Replace(“/”, “\\”);
System.Net.Mail.Attachment A = new Attachment(HttpContext.Current.Request.PhysicalApplicationPath + “\\” + imgPath);
A.ContentId = RGen.Next(100000, 9999999).ToString();
body = body.Replace(oldChar, “cid:” + A.ContentId);
mailMsg.Attachments.Add(A);
oldChar = ExtractImages(body, ref count);
}
else
{
oldChar = ExtractImages(body, ref count);
}
}
mailMsg.Body = body;
mailObj.Send(mailMsg);
}
catch (Exception ex)
{
System.Web.HttpContext.Current.Response.Write(ex.Message);
}
}

private static string ExtractImages(string body, ref int count)
{
int startIndex = body.ToLower().IndexOf(“<img src=\””, count);
int endIndex;
if (startIndex >= 0)
{
endIndex = body.IndexOf(“\””, startIndex + 10);
}
else
{
return “”;
}
startIndex = startIndex + 10;
string imgurl = body.Substring(startIndex, (endIndex – (startIndex)));
count = startIndex;
return imgurl;
}
}

ASP.NET makes it easy to utilise e-mail in an application with the System.Web.Mail namespace. Let’s take a closer look at putting this namespace to work in your applications.

System.Web.Mail namespace
The Microsoft documentation provides a good overview of the System.Web.Mail namespace. It’s composed of classes that allow you to create and send messages using the Collaboration Data Objects for Windows 2000 (CDOSYS) message component. The actual message may be delivered via the SMTP (Simple Mail Transfer Protocol) mail service built into Microsoft Windows 2000 and beyond or through an arbitrary SMTP server. The classes in this namespace aren’t restricted to an ASP.NET application.

The namespace includes three classes:

  • MailAttachment: Provides properties and methods for constructing an e-mail attachment.
  • MailMessage: Provides properties and methods for constructing an e-mail message.
  • SmtpMail: Provides properties and methods for sending messages using the CDOSYS message component.

MailAttachment class
The basic approach is the creation of a MailMessage object followed by sending it on its way via a SmtpMail object. The MailMessage class contains numerous methods and properties for working with an e-mail message. Properties such as From, Subject, and Body provide everything you need to create an e-mail message, but a SmtpMail object is still necessary for sending it on its way.

SmtpMail class
The SmtpMail class includes the SmtpServer property that gets or sets the name of the SMTP relay mail server to use to send messages, and the Send method actually sends the message. The Send method is overloaded. It allows a message to send using two approaches:

A MailMessage object is passed to the SmtpServer object. Four string objects may be passed to the SmtpServer object with the first being the From field followed by the Recipient, Subject, and the message’s Body.

You’ll use the MailAttachment and SmtpMail classes together to create the necessary messages in your application, but make sure the Web server is properly configured to send a message via SMTP. Since IIS (Internet Information Services) is the most popular platform for ASP.NET applications, go ahead and use both the IIS and SMTP services to send messages from your application.

Using SMTP with IIS
You can set up both IIS and SMTP services via the Windows control panel. The SMTP service’s role is to accept and deliver the messages using the server’s configuration. It may deliver the messages directly, or utilise a smart host to deliver the message instead. When a smart host is enlisted, all messages are forwarded to it for delivery.

A little more information is appropriate for debugging. The SMTP service uses a directory structure to contain messages prior to delivery with the default directory being C:\Inetpub\mailroot. It contains numerous subdirectories including Queue, Drop, and Badmail. If you’re unable to configure your instance of the SMTP Service for delivery, you can find the message in an EML file in the Queue subdirectory. The Badmail directory contains messages that that couldn’t be delivered. Now, let’s take a look at sending mail messages from your code.

Sending e-mail messages
To compose an e-mail message in your code, you need to start by creating an instance of the MailMessage class, as shown in the following C# snippet:

MailMessage msg = new MailMessage();

Be sure to include the System.Web.Mail namespace in your code:

using System.Web.Mail;

Once the object is instantiated, the various properties of the MailMessage class are used per your application. The following lines set the recipient, sender, and subject of the message:

msg.To = “test@test.com”;
msg.From = “me@test.com”;
msg.Subject = “Test Message”;

The next step is setting our mail server via the SmtpServer object’s SmtpServer property:

SmtpMail.SmtpServer = “smtp server name or address”;

The final step is sending the message by passing our MailMessage object to the SmtpMail object’s Send method:

SmtpMail.Send(msg);

Advertisements

5 thoughts on “Send Email with Inline Images & Attachments

  1. This is very useful but i have some error in this code
    this shows an exception “A recipient must be specified.”,
    but i always trying to do …………but did’t success……
    u just help me………..

  2. you might not passing recipient details & thts wht these msg comes.. & provide yr code if yr problem is not solved yet..

  3. what if I generate a graph using zedgraph in C# platform and then want to mail the graph in message body using outlook (and not as attachment)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s