Appear in Online Interview to test your skills and be ready for job!
Twitter Twitter LinkedIn YouTube Google
Be Interview ready ! | Search
Make friends on DotNetFunda.com and expand your network!
Winners

Win Prizes

Announcements
Like us on Facebook
Sponsor
Top Articles Author
Thu, 24-Apr-2014 Authors
All Time Authors
Sourav.Kayal
39750
Sheonarayan
34800
Niladri.Biswas
33350

Latest members | More ...


(Statistics delayed by 5 minutes)
Ads

Sending email with attachment in ASP.NET

SheoNarayan
Posted by under ASP.NET category on for Advance level | Points: 250 | Views : 43042 red flag
If you found plagiarised (copied) or inappropriate content,
please let us know the original source along with your correct email id (to communicate) for further action.
Rating: 4 out of 5
2 vote(s)


In this article, I am going to describe how to send email with attachment in ASP.NET. I am going to use System.IO, System.Net and System.Net.Mail namespaces in this article.

 Download source code for Sending email with attachment in ASP.NET


This article is written as a response to the Forums thread posted at http://www.dotnetfunda.com/forums/thread3210-email-in-aspnet-happy-new-year-to-every-body.aspx where author has asked about how to send email in ASP.NET with attaching a file. To show the solution, I have prepared a sample asp.net form that looks like below.

Create a Send Email with Attachment form

Copy-paste below code in your .aspx page.

<table>

<tr><td colspan="2"><h3>Send Email with Attachment in ASP.NET</h3></td></tr>

<tr><td>To</td><td><asp:TextBox ID="txtTo" runat="server" /></td></tr>

<tr><td>Subject</td><td><asp:TextBox ID="txtSubject" runat="server" Columns="30" /></td></tr>

<tr><td>Body</td><td><asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine" Rows="10" Columns="50" /></td></tr>

<tr style="font-weight:bold;"><td>Attachment</td><td><asp:FileUpload ID="FileUpload1" runat="server" /></td></tr>

<tr><td>&nbsp;</td><td><asp:Button ID="btnSubmit" runat="server" Text="Send Email" OnClick="SendEmailWithAttachment" /></td></tr>

</table>

<asp:Label ID="lblMessage" runat="server" EnableViewState="false" />

This code snippet shall create a Send Email form that looks like above picture. Notice that on click on the button I have attached a server side click event that will fire SendEmailWithAttachment method, so let's write code for that.

protected void SendEmailWithAttachment(object sender, EventArgs e)

{

SendEmail(txtTo.Text.Trim(), "", "", txtSubject.Text.Trim(), txtBody.Text.Trim(), MailPriority.High, false);

}

In the above code, I have fired a SendEmail private method that will actually do the work of sending email. Below is the code for the SendEmail method.

Namespace to use

To work with SendEmail method code, you need to use following namespaces

using System.IO;

using System.Net;

using System.Net.Mail;

SendEmail method code

private void SendEmail(string toAddress, string ccAddress, string bccAddress, string subject, string body, MailPriority priority, bool isHtml)

{

try

{

using (SmtpClient smtpClient = new SmtpClient())

{

using (MailMessage message = new MailMessage())

{

MailAddress fromAddress = new MailAddress("fromEmail@MyDomain.com", "FromEmail, myDomain.Com");

 

// You can specify the host name or ipaddress of your server

smtpClient.Host = "smtp.myDomain.com"; //you can also specify mail server IP address here

 

//Default port will be 25

smtpClient.Port = 25;

 

NetworkCredential info = new NetworkCredential("fromEmail@myDomain.com", "fromEmailPassword");

smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;

smtpClient.UseDefaultCredentials = false;

smtpClient.Credentials = info;

 

//From address will be given as a MailAddress Object

message.From = fromAddress;

message.Priority = priority;

 

// To address collection of MailAddress

message.To.Add(toAddress);

message.Subject = subject;

if (ccAddress.Length > 0)

{

message.CC.Add(ccAddress);

}

if (bccAddress.Length > 0)

{

message.Bcc.Add(bccAddress);

}

 

//Body can be Html or text format

//Specify true if it is html message

message.IsBodyHtml = isHtml;

 

// Message body content

message.Body = body;

 

// Add the attachment, if any

if (FileUpload1.PostedFile.ContentLength > 0)

{

Attachment attachment = new Attachment(Path.GetFullPath(FileUpload1.PostedFile.FileName));

message.Attachments.Add(attachment);

}

 

// Send SMTP mail

smtpClient.Send(message);

 

lblMessage.Text = "Email sent to " + toAddress + " successfully !";

}

}

}

catch (Exception ee)

{

lblMessage.Text = ee.ToString();

}

}

In the above code snippet, I have instantiated the SmtpClient object that provides ability to send email in ASP.NET. After that I have instantiated the MailMessage object that will have necessary properties set to be used to send email (for example, to, from, network body attachment etc.). All the above procedures are same as we do for normal sending email (like setting the network credential for the SmtpClient object, specifying host name etc.)

Important lines of code to notice in the above method is related with the file attachment, notice the if condition block just above smtpClient.Send(message) line. In this if block I have first checked if any file has been selected by accessing the ContentLength property of the FileUpload control; if yes then I have instantiated the Attachment object and passed the path of the file in the constructor and then added to the message.Attachments collection. If you have more than one file to attach in the email, you can add them one by one in the message.Attachments collection.

Once the smtpClient.Send(message) line will execute successfully, an email will be sent and success message will be written on the page. In case any error, it will go to the catch block and write the actual error with complete description in the label.

I hope this article will be useful for Sathya who has asked this question in the Forums thread as well as others who are looking for sending email in ASP.NET with attachment.

Wrote this article on the 1st January 2011 at 7.38 AM. Thank you for reading and wish you a very happy new year!

I have written hundreds of .NET How to's solution (ebook + source code + video) series based on real time project problems, click here to get it.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:




About the Author

SheoNarayan

Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Microsoft_MVP,Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan The Founder http://www.dotnetfunda.com
http://www.snarayan.com

Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan
Login to vote for this post.

Comments or Responses

Posted by: Sjbupi on: 1/15/2011 | Points: 25

I have created this application around 3 years back in 2007. But the problem I faced is that, If I want to send mail to more than one Emanil-Ids, it was not doing that. It was sending mail to the first mail-id written in "To" box. If you can propose such functionality to this application, it would really helpfull.

Posted by: SheoNarayan on: 1/16/2011 | Points: 25

The SendEmail function above has that ability, you just need to pass the CC email id and email will be sen to those email ids as well.

Thanks

Posted by: Artisingh30 on: 1/21/2011 | Points: 25

hello sir
thanks for this reply but my need was formatted email that, contain formatted text and images and by this code i m unable to send formatted mail .i am not talking about attachment. i am talking about formatted Email which have images in background or other logo etc.

Thanks and Regards
Arti Singh

Posted by: Sandeep418995 on: 8/16/2012 | Points: 25

hello sir

thanx for a nice article.
i have a little different requirement in which i have to attach two files from database directly into mail attachment(retrieve from database and attach)
please tell me how can i do it

thanx in advance.

MailMessage mm = new MailMessage();
SmtpClient smtp = new SmtpClient();
mm.From = new MailAddress("sandybmas11@gmail.com");
mm.To.Add(new MailAddress("sandybmas11@gmail.com"));
mm.Subject = "Your Marksheet";
mm.Body = "hi";

// Attachment attachFile = new Attachment(abc.ToString());
// mm.Attachments.Add(attachFile);


mm.IsBodyHtml = true;
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = " ";
NetworkCred.Password = " ";
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);

Posted by: Oceandesigner on: 11/18/2012 | Points: 25

Hello.

This article is very good. I try it without attachment and it looks ok. But when I put a attachment goes to this error:

System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Users\Designer\Desktop\tyres.jpg'. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) at System.Net.Mail.AttachmentBase.SetContentFromFile(String fileName, String mediaType) at System.Net.Mail.AttachmentBase..ctor(String fileName) at System.Net.Mail.Attachment..ctor(String fileName) at SendEmailWithAttachment_Default.SendEmail(String toAddress, String ccAddress, String bccAddress, String subject, String body, MailPriority priority, Boolean isHtml) in c:\inetpub\vhosts\vulcanizadora25deabril.com\httpdocs\email\Default.aspx.cs:line 74

Can anyone help me about this error?
Thank you!

Posted by: Sakthiae on: 6/16/2013 | Points: 25

Hi thanks for your reply

If i use fileupload control means its work fine but i want to attach the file with url
like (
http://localhost:4313/Files/aaradhya-bachchan3.jpg)

if am using this url means am getting error.

pls suggest me .


Login to post response.

Comments / Responses
Select text & click toolbar to format. Formatting appears in viewmode only. HTML Tags are not allowed.
Bold Italic Underline Paragraph Title Code  Link 
 Wait ... Processing ..... please wait.

Comment using Facebook