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:
<body>
<form id="form1" runat="server">
<table style="height: 299px; width: 389px">
<tr>
<td>Select File:</td>
<td><asp:FileUpload ID="FileUploadExcel" runat="server" meta:resourcekey="FileUploadExcelResource1" /></td>
</tr>
<tr>
<td colspan="2" class="auto-style1"><asp:Button ID="BtnUpload" runat="server" Text="Upload"
OnClick="BtnUpload_Click" meta:resourcekey="BtnUploadResource1" /></td>
</tr>
<tr>
<td>Subject:</td>
<td><asp:TextBox ID="TxtSubject" runat="server" meta:resourcekey="TxtSubjectResource1"></asp:TextBox></td>
</tr>
<tr>
<td colspan="2">
<asp:GridView ID="DataGridView" runat="server" AutoGenerateColumns="False" Height="78px" Width="349px"
meta:resourcekey="DataGridViewResource1">
<Columns>
<asp:TemplateField HeaderText="Name" meta:resourcekey="TemplateFieldResource1">
<ItemTemplate>
<asp:Label ID="LblName" runat="server" Text='<%# Bind("F1") %>' meta:resourcekey="LblNameResource1"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email ID" meta:resourcekey="TemplateFieldResource2">
<ItemTemplate>
<asp:Label ID="LblEmail" runat="server" Text='<%# Bind("F2") %>' meta:resourcekey="LblEmailResource1"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="File" meta:resourcekey="TemplateFieldResource3">
<ItemTemplate>
<asp:Label ID="LblFile" runat="server" Text='<%# Bind("F3") %>' meta:resourcekey="LblFileResource1"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td>
<asp:Button ID="BtnSendMail" runat="server" Text="SendMail" OnClick="BtnSendMail_Click"
meta:resourcekey="BtnSendMailResource1" />
</td>
<td>
<asp:Label ID="LblMessage" runat="server" meta:resourcekey="LblMessageResource1"></asp:Label>
</td>
</tr>
</table>
</form>
</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:
using System;
using System.Data;
using System.Data.OleDb;
using System.Web;
{
public class DAL
{
OleDbDataAdapter DbAdap;
DataTable dt;
internal object Get_File(string MyFile)
{
string connString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0} ;
Extended Properties=\"Excel 12.0;HDR=NO;IMEX=1\";", HttpContext.Current.Server.MapPath("~/Data/") + MyFile);
OleDbConnection DbCon = new OleDbConnection(connString);
DbAdap = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", DbCon);
dt = new DataTable();
DbAdap.Fill(dt);
return dt;
}
}
}
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():
string MyFile;
DAL obj = new DAL();
- Modify the Page_Load() event with the code below:
protected void Page_Load(object sender, EventArgs e)
{
LblMessage.Visible = false;
BtnSendMail.Enabled = false;
}
- 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:
protected void BtnUpload_Click(object sender, EventArgs e)
{
UploadFile();
BtnSendMail.Enabled = true;
}
void UploadFile()
{
HttpPostedFile PostedFile = Request.Files["FileUploadExcel"];
if (PostedFile != null && PostedFile.ContentLength > 0)
{
MyFile = Path.GetFileName(PostedFile.FileName);
PostedFile.SaveAs(Server.MapPath(Path.Combine("~/Data/", MyFile)));
Get_Data(MyFile);
}
else
{
LblMessage.Text = "Missing File";
LblMessage.Visible = true;
}
}
private void Get_Data(string MyFile)
{
DataGridView.DataSource = obj.Get_File(MyFile);
DataGridView.DataBind();
}
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:
</system.web>
<appSettings>
<add key="FromMail" value="Your-Email-ID"/>
<add key="Password" value="Your-Email-Password"/>
<add key="Host" value="smtp.gmail.com"/>
</appSettings>
Step 2: Create an event for the SendMail Button and code to email using the following:
void Send_Mail()
{
try
{
string Pass, FromEmailid, HostAdd;
foreach (GridViewRow gr in DataGridView.Rows)
{
HostAdd = ConfigurationManager.AppSettings["Host"].ToString();
FromEmailid = ConfigurationManager.AppSettings["FromMail"].ToString();
Pass = ConfigurationManager.AppSettings["Password"].ToString();
Label LblName = gr.FindControl("LblName") as Label;
Label LblMail = gr.FindControl("LblEmail") as Label;
Label LblFile = gr.FindControl("LblFile") as Label;
string Name = LblName.Text;
string Mail = LblMail.Text;
string FilePath = LblFile.Text;
string subject = TxtSubject.Text;
SmtpClient client = new SmtpClient();
MailMessage msg = new MailMessage();
NetworkCredential credentials = new NetworkCredential(FromEmailid, Pass);
client.Host = HostAdd;
client.Port = 25;
client.UseDefaultCredentials = false;
client.Credentials = credentials;
client.EnableSsl = true;
MailAddress from = new MailAddress(FromEmailid);
Attachment attachment = new Attachment(ResolveUrl(FilePath));
msg.IsBodyHtml = true;
msg.Subject = subject;
msg.Attachments.Add(attachment);
msg.Body = "Hello";
msg.To.Add(Mail);
msg.From = from;
client.Send(msg);
LblMessage.Text = "Email Send Successfully";
LblMessage.Visible = true;
}
}
catch (Exception Ex)
{
LblMessage.Text = Ex.Message;
LblMessage.Visible = true;
}
}
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.