Sending Email With an Attached File

Introduction

This article explains how to send an email from an application in which an Excel file is to be connected with the application. There are the following three fields defined in the Excel file:

  • User Name 
  • User EmailID 
  • File that is sent as an attachment

We are developing the scenario in which we need to send the file as an attachment but suppose we do not want to upload and after uploading attach the file. In this case we can provide the file path in the Excel file. The file path is specified in the Excel File as shown in the following screenshot:

So, let's develop the application that connects with the Excel application and send the email to the users. Use the following procedure to do that.

Creating ASP.NET Web Application

Step 1: Create an ASP.NET Web Application in Visual Studio.

Step 2: Just right-click on the project to add the new Web Form to the Solution Explorer.

Step 3: Replace the body code with the following code:

  1. <body>  
  2.     <form id="form1" runat="server">  
  3.     <table style="height: 299px; width: 389px">  
  4.         <tr>  
  5.             <td>Select File:</td>  
  6.             <td><asp:FileUpload ID="FileUploadExcel" runat="server" meta:resourcekey="FileUploadExcelResource1" /></td>  
  7.         </tr>  
  8.         <tr>  
  9.             <td colspan="2" class="auto-style1"><asp:Button ID="BtnUpload" runat="server" Text="Upload"   
  10. OnClick="BtnUpload_Click" meta:resourcekey="BtnUploadResource1" /></td>  
  11.         </tr>  
  12.         <tr>  
  13.             <td>Subject:</td>  
  14.             <td><asp:TextBox ID="TxtSubject" runat="server" meta:resourcekey="TxtSubjectResource1"></asp:TextBox></td>  
  15.         </tr>  
  16.         <tr>  
  17.             <td colspan="2">  
  18.                 <asp:GridView ID="DataGridView" runat="server" AutoGenerateColumns="False" Height="78px" Width="349px"   
  19. meta:resourcekey="DataGridViewResource1">  
  20.                     <Columns>  
  21.                         <asp:TemplateField HeaderText="Name" meta:resourcekey="TemplateFieldResource1">  
  22.                             <ItemTemplate>  
  23.                                 <asp:Label ID="LblName" runat="server" Text='<%# Bind("F1") %>' meta:resourcekey="LblNameResource1"></asp:Label>  
  24.                             </ItemTemplate>  
  25.                         </asp:TemplateField>  
  26.                         <asp:TemplateField HeaderText="Email ID" meta:resourcekey="TemplateFieldResource2">  
  27.                             <ItemTemplate>  
  28.                                 <asp:Label ID="LblEmail" runat="server" Text='<%# Bind("F2") %>' meta:resourcekey="LblEmailResource1"></asp:Label>  
  29.                             </ItemTemplate>  
  30.                         </asp:TemplateField>  
  31.                         <asp:TemplateField HeaderText="File" meta:resourcekey="TemplateFieldResource3">  
  32.                             <ItemTemplate>  
  33.                                 <asp:Label ID="LblFile" runat="server" Text='<%# Bind("F3") %>' meta:resourcekey="LblFileResource1"></asp:Label>  
  34.                             </ItemTemplate>  
  35.                         </asp:TemplateField>  
  36.                     </Columns>  
  37.                 </asp:GridView>  
  38.             </td>  
  39.         </tr>  
  40.         <tr>  
  41.             <td>  
  42.                 <asp:Button ID="BtnSendMail" runat="server" Text="SendMail" OnClick="BtnSendMail_Click"   
  43. meta:resourcekey="BtnSendMailResource1" />  
  44.             </td>  
  45.             <td>  
  46.                 <asp:Label ID="LblMessage" runat="server" meta:resourcekey="LblMessageResource1"></asp:Label>  
  47.             </td>  
  48.         </tr>  
  49.     </table>  
  50.     </form>  
  51. </body> 

Connect ASP.NET to Excel

In this section we'll connect the Excel file to the application. Use the following procedure to do that.

Step 1: Create a folder named Data in the project.

Step 2: Add a class named DAL and replace the code with the code below:

  1. using System;  
  2. using System.Data;  
  3. using System.Data.OleDb;  
  4. using System.Web;  
  5. namespace MailWebAppl  
  6. {  
  7.     public class DAL  
  8.     {  
  9.         OleDbDataAdapter DbAdap;  
  10.         DataTable dt;  
  11.         internal object Get_File(string MyFile)  
  12.         {  
  13.             string connString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0} ;  
  14.             Extended Properties=\"Excel 12.0;HDR=NO;IMEX=1\";", HttpContext.Current.Server.MapPath("~/Data/") + MyFile);  
  15.             OleDbConnection DbCon = new OleDbConnection(connString);  
  16.             DbAdap = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", DbCon);  
  17.             dt = new DataTable();  
  18.             DbAdap.Fill(dt);  
  19.             return dt;  
  20.         }  
  21.     }  
  22. } 

Note: You must have the Office driver to access the Excel file. Please refer to Excel Connectivity

Step 3: In the WebForm.cs file, we'll upload the Excel file and bind it to the Grid View. Proceed with the following sections:

  • Add the following code above the Page_Load():
    1. string MyFile;  
    2. DAL obj = new DAL(); 
  • Modify the Page_Load() event with the code below:
    1. protected void Page_Load(object sender, EventArgs e)  
    2. {  
    3.     LblMessage.Visible = false;  
    4.     BtnSendMail.Enabled = false;  
    5. }
  • Now we'll create an event for the Upload button to upload the Excel file and then bind it to the Grid View using the following code:
    1. protected void BtnUpload_Click(object sender, EventArgs e)  
    2. {  
    3.     UploadFile();  
    4.     BtnSendMail.Enabled = true;  
    5. }  
    6. void UploadFile()  
    7. {  
    8.     HttpPostedFile PostedFile = Request.Files["FileUploadExcel"];  
    9.     if (PostedFile != null && PostedFile.ContentLength > 0)  
    10.     {  
    11.         MyFile = Path.GetFileName(PostedFile.FileName);  
    12.         PostedFile.SaveAs(Server.MapPath(Path.Combine("~/Data/", MyFile)));  
    13.         Get_Data(MyFile);  
    14.     }  
    15.     else  
    16.     {  
    17.         LblMessage.Text = "Missing File";  
    18.         LblMessage.Visible = true;  
    19.     }  
    20. }  
    21. private void Get_Data(string MyFile)  
    22. {  
    23.     DataGridView.DataSource = obj.Get_File(MyFile);  
    24.     DataGridView.DataBind();  
    25. }

Step 4: Run the application and after uploading the Excel file the web form will look as in the following screenshot:

Emailing

Now in this section we'll use the body of the resource key as an email body and email it. Use the following procedure to do that.

Step 1: At first we'll configure the Web.Config file. Modify the Web.Config file with the following code:

  1. <system.web>  
  2. <appSettings>  
  3.   <add key="FromMail" value="Your-Email-ID"/>  
  4.   <add key="Password" value="Your-Email-Password"/>  
  5.   <add key="Host" value="smtp.gmail.com"/>  
  6. </appSettings> 

Step 2: Create an event for the SendMail Button and code to email using the following:

  1. void Send_Mail()  
  2. {  
  3.     try  
  4.     {  
  5.         string Pass, FromEmailid, HostAdd;  
  6.         foreach (GridViewRow gr in DataGridView.Rows)  
  7.         {  
  8.             HostAdd = ConfigurationManager.AppSettings["Host"].ToString();  
  9.             FromEmailid = ConfigurationManager.AppSettings["FromMail"].ToString();  
  10.             Pass = ConfigurationManager.AppSettings["Password"].ToString();  
  11.             Label LblName = gr.FindControl("LblName"as Label;  
  12.             Label LblMail = gr.FindControl("LblEmail"as Label;  
  13.             Label LblFile = gr.FindControl("LblFile"as Label;  
  14.             string Name = LblName.Text;  
  15.             string Mail = LblMail.Text;  
  16.             string FilePath = LblFile.Text;  
  17.             string subject = TxtSubject.Text;  
  18.             SmtpClient client = new SmtpClient();  
  19.             MailMessage msg = new MailMessage();  
  20.             NetworkCredential credentials = new NetworkCredential(FromEmailid, Pass);  
  21.             client.Host = HostAdd;  
  22.             client.Port = 25;  
  23.             client.UseDefaultCredentials = false;  
  24.             client.Credentials = credentials;  
  25.             client.EnableSsl = true;  
  26.             MailAddress from = new MailAddress(FromEmailid);  
  27.             Attachment attachment = new Attachment(ResolveUrl(FilePath));  
  28.             msg.IsBodyHtml = true;  
  29.             msg.Subject = subject;  
  30.             msg.Attachments.Add(attachment);  
  31.             msg.Body = "Hello";  
  32.             msg.To.Add(Mail);  
  33.             msg.From = from;  
  34.             client.Send(msg);  
  35.             LblMessage.Text = "Email Send Successfully";  
  36.             LblMessage.Visible = true;  
  37.         }  
  38.     }  
  39.     catch (Exception Ex)  
  40.     {  
  41.         LblMessage.Text = Ex.Message;  
  42.         LblMessage.Visible = true;  
  43.     }  
  44. } 

Step 3: Run the application. At first select the Excel file to upload. and then click on the SendMail button.

Summary

This article will help you to connect an Excel file to the ASP.NET application and you can send the file as an attachment. You do not need to attach the file and choose, just provide the file path in the Excel file and the file will be sent as an attachment to that specific user email id. Happy Coding and thanks for reading.


Similar Articles