Introduction
In this article, we will learn how can we send mail with an attachment. In this article I am going to send excel files through SendGrid and save the excel file in folder let’s see step by step process.
Step 1
First, create a simple ASP.NET project. Here, I am not showing how to create ASP.NET project. I am creating my project with the name ExcelAttechment
Step 2
In this step, we need to install Microsoft.Office.Interop.Excel package through NuGet.
Step 3
In this step, we can add an entity ADO.NET entity Data Model in our project.
I am creating a table with the name Student.
![]()
Afterwards, I will fetch the data from the table with the help of an entity. I am using buttonClick event to get the data.
Let’s see the code on how can we get the data from the database. In the code given below, I am getting the data in list format after which I am converting the list into DataTable format.
- using ExcelAttechment.Models;
- using SendGrid;
- using SendGrid.Helpers.Mail;
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Data;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Mail;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
-
- namespace ExcelAttechment
- {
- public partial class _Default : Page
- {
-
- string savelocation = @"D:\Excel\";
- protected void Page_Load(object sender, EventArgs e)
- {
- }
-
- protected void Button1_Click(object sender, EventArgs e)
- {
- AtulTestEntities1 at = new Models.AtulTestEntities1();
-
- var data = at.Students.ToList();
- DataTable dt = ToDataTable(data.ToList());
- excelimport(dt, savelocation).Wait();
- }
- public DataTable ToDataTable<T>(List<T> items)
- {
- DataTable dataTable = new DataTable(typeof(T).Name);
-
- PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
- foreach (PropertyInfo prop in Props)
- {
-
- dataTable.Columns.Add(prop.Name);
- }
- foreach (T item in items)
- {
- var values = new object[Props.Length];
- for (int i = 0; i < Props.Length; i++)
- {
-
- values[i] = Props[i].GetValue(item, null);
- }
- dataTable.Rows.Add(values);
- }
-
- return dataTable;
- }
- public async Task excelimport(DataTable Tbl, string savelocation)
- {
- simpletest st = new simpletest();
- string name = Tbl.TableName;
- int rowcount = Tbl.Rows.Count + 1;
- Microsoft.Office.Interop.Excel.Range excelCellrange;
- Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
- excelApp.Workbooks.Add();
-
- Microsoft.Office.Interop.Excel._Worksheet workSheet = excelApp.ActiveSheet;
- workSheet.Name = Tbl.TableName;
-
- for (int i = 0; i < Tbl.Columns.Count; i++)
- {
- workSheet.Cells[1, (i + 1)] = Tbl.Columns[i].ColumnName.ToUpper();
- }
-
- for (int i = 0; i < Tbl.Rows.Count; i++)
- {
-
- for (int j = 0; j < Tbl.Columns.Count; j++)
- {
- workSheet.Cells[(i + 2), (j + 1)] = Tbl.Rows[i][j];
- }
- }
- excelCellrange = workSheet.Range[workSheet.Cells[1, 1], workSheet.Cells[rowcount, Tbl.Columns.Count]];
- excelCellrange.EntireColumn.AutoFit();
- Microsoft.Office.Interop.Excel.Borders border = excelCellrange.Borders;
- border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
- workSheet.get_Range("A1", "G1").Font.Bold = true;
- border.Weight = 2d;
- if (savelocation != null && savelocation != "savelocation")
- {
- try
- {
- workSheet.SaveAs(savelocation + workSheet.Name + ".xls");
- excelApp.Quit();
- string email = "[email protected]";
- string filepath = savelocation + name + ".xls";
-
- await st.sendemail(email, filepath);
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- else
- {
- excelApp.Visible = true;
- }
-
- }
- }
- }
![]()
In the code given above, I got the data in DataTable format and afterwards create Excel file, fill the data in an Excel file and save in the folder, where you want. Saving the Excel file process is done. Now, we will send an Excel file through SendGid. SendGrid provides free trial Service to create SendGridAccount. Hit the link given below.
https://sendgrid.com/ after which you can get the option of try of free. Click on and go forward, where there are two ways, where first is WebAPI and second is SMTPRelay.
I am using the second option. I will send the mail with SMTP.
It provides me all the cardinals for helping to send the email. Let’s see how can we use the cardinals.
- public class simpletest
- {
- public async Task sendemail(string Toemail, string filePath)
- {
- try
- {
- await Task.Run(() =>
- {
- MailMessage mail = new MailMessage();
- SmtpClient SmtpServer = new SmtpClient("smtp.sendgrid.net");
- mail.From = new MailAddress("[email protected]");
- mail.To.Add(Toemail);
- mail.Subject = "Test Mail - 1";
- mail.Body = "mail with attachment";
- System.Net.Mail.Attachment attachment;
- attachment = new System.Net.Mail.Attachment(filePath);
- mail.Attachments.Add(attachment);
- SmtpServer.Port = 25;
- SmtpServer.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["ApiKey"], ConfigurationManager.AppSettings["ApiKeyPass"]);
- SmtpServer.EnableSsl = true;
- SmtpServer.Send(mail);
- });
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- }
In the code given above, I will send the email with an attachment file, using SMTP.
Lets see the mail.
![]()
Now, I got the mail with the attached file.
Summary
In this article, we learned how to send an email with an attached file, using SendGrid.