Send attachment with email in asp.net using c#

In this asp.net tutorial you will learn how to send attachment with email in asp.net using c#. As far as attachment with email is concerned, you have to first upload the file to any folder in your web server and then using that path you can send attachment with email.


So it's crystal clear that you have to first upload the file to the web server.
I have already written a detail tutorial about file uploading in asp.net using c#.


If you don't know how to upload file then please refer to that tutorial.

Send attachment with email in asp.net using c#


Once you have successfully uploaded the attachment file to the web server then add the code snippet of line# 79 and 80 in your c# source code, also you have to copy/paste the sendEmail() function in your c# code.

Upload_single_file.aspx.cs

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;//Used for file uploading
using System.Web.UI.WebControls.WebParts;
using System.Net; //Use for sending Emails
using System.Net.Mail;//Use for sending Emails


public partial class Upload_single_file : System.Web.UI.Page
{
//global variable that will contain the path of the uploaded file

string _uploadedFilePath = "";


protected void Page_Load(object sender, EventArgs e)
{
}


//Function to upload the file
protected void btnUpload_Click(object sender, EventArgs e)
{


//Checking whether asp file upload control (txtFile in my case) contains any file or not


//If it contains file
if (txtFile.HasFile)
{
//Getting file name
string fileName = txtFile.FileName.ToString();


//Creating array that will contain the data before and after period (.)
string[] dots = fileName.Split('.');


string fileType = "pdf,doc,xls";
//type = dots[2 - 1] // type=dots[1] which contains your file extension


string type = dots[dots.Length - 1];
//If uploaded file is not in above mentioned formats format then this set of code will be //executed
if (fileType.IndexOf(type) == -1)
{
//In my case, I have put a asp:label in .aspx page to show message.
lblMessage.Visible=true;
lblMessage.Text = "Please only upload files that end in types: \n\n" + (fileType) + "\n\nPlease select a new file and try again.";
txtFile.Focus();
return;
}
else
{


string strUploadPath = "", strFilePath = "";


//Replace your folder Name with this Uploaded Folder Name
strFilePath = @"~\uploaded Folder Name\";


//Current Date Time is appending with the File Name to track when the file
//is uploaded


string path = DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Year.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Millisecond.ToString();
strUploadPath = Server.MapPath(strFilePath) + path + txtFile.FileName.ToString().Replace("'", "");
txtFile.SaveAs(strUploadPath.ToString());
uploadedFilePath=strUploadPath;
sendEmail();


lblMessage.Visible=true;


lblMessage.Text = "Email Sent Successfully";


}
}
public void sendEmail()
{
MailMessage msg = new MailMessage("fromemailaddress@somedomain.com","toemailaddress@somedomain.com");
msg.Subject = "Subject of email will come here";
msg.Body = Bodytext();
msg.IsBodyHtml = true;
msg.Attachments.Add(new Attachment(_uploadedFilePath));
SmtpClient smtpclient = new SmtpClient();
try
{
smtpclient.Send(msg);
}
catch (Exception ex)
{
throw ex;
}
}


}

You have seen that using the Attachments property of Mail class, I have attached the uploaded file by passing the global variable _uploadedFilePath that contains the path of the uploaded file and then finally I have send email using the Send() method of the SmtpMail Class.


If you want to delete the attachment file after email sent successfully then you will have to write the following code snippet after the calling of sendEmail() function.



/* Delete the attachements if any */
if (_uploadedFilePath != null)
File.Delete(Server.MapPath(_uploadedFilePath));

Note: - Please check mail settings in your web.config file. Please don't forget to declare the System.Net and System.Net.Mail namespaces if you want to send email.


So this is the proper way to send attachment with email in asp.net using c#. Later on I will teach you how to send multiple attachments with email in asp.net using c#. I also intend to write a tutorial about file uploading using silverlight that will also show a progress bar when file is being uploaded.

0 comments: