Send Email With Attached File Using C# And SendGrid

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.

  1. using ExcelAttechment.Models;  
  2. using SendGrid;  
  3. using SendGrid.Helpers.Mail;  
  4. using System;  
  5. using System.Collections.Generic;  
  6. using System.Configuration;  
  7. using System.Data;  
  8. using System.IO;  
  9. using System.Linq;  
  10. using System.Net;  
  11. using System.Net.Mail;  
  12. using System.Reflection;  
  13. using System.Text;  
  14. using System.Threading.Tasks;  
  15. using System.Web;  
  16. using System.Web.UI;  
  17. using System.Web.UI.WebControls;  
  18.   
  19. namespace ExcelAttechment  
  20. {  
  21.     public partial class _Default : Page  
  22.     {  
  23.   
  24.         string savelocation = @"D:\Excel\";  
  25.         protected void Page_Load(object sender, EventArgs e)  
  26.         {  
  27.         }  
  28.   
  29.         protected void Button1_Click(object sender, EventArgs e)  
  30.         {  
  31.             AtulTestEntities1 at = new Models.AtulTestEntities1();  
  32.            // var data = new DALExcel().GetDataForExcel();  
  33.              var data = at.Students.ToList();  
  34.             DataTable dt = ToDataTable(data.ToList());  
  35.             excelimport(dt, savelocation).Wait();  
  36.         }  
  37.         public DataTable ToDataTable<T>(List<T> items)  
  38.         {  
  39.             DataTable dataTable = new DataTable(typeof(T).Name);  
  40.             //Get all the properties  
  41.             PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);  
  42.             foreach (PropertyInfo prop in Props)  
  43.             {  
  44.                 //Setting column names as Property names  
  45.                 dataTable.Columns.Add(prop.Name);  
  46.             }  
  47.             foreach (T item in items)  
  48.             {  
  49.                 var values = new object[Props.Length];  
  50.                 for (int i = 0; i < Props.Length; i++)  
  51.                 {  
  52.                     //inserting property values to datatable rows  
  53.                     values[i] = Props[i].GetValue(item, null);  
  54.                 }  
  55.                 dataTable.Rows.Add(values);  
  56.             }  
  57.             //put a breakpoint here and check datatable  
  58.             return dataTable;  
  59.         }  
  60.         public async Task excelimport(DataTable Tbl, string savelocation)  
  61.         {  
  62.             simpletest st = new simpletest();  
  63.             string name = Tbl.TableName;  
  64.             int rowcount = Tbl.Rows.Count + 1;  
  65.             Microsoft.Office.Interop.Excel.Range excelCellrange;  
  66.             Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();  
  67.             excelApp.Workbooks.Add();  
  68.             // single worksheet  
  69.             Microsoft.Office.Interop.Excel._Worksheet workSheet = excelApp.ActiveSheet;  
  70.             workSheet.Name = Tbl.TableName;  
  71.             //column headings  
  72.             for (int i = 0; i < Tbl.Columns.Count; i++)  
  73.             {  
  74.                 workSheet.Cells[1, (i + 1)] = Tbl.Columns[i].ColumnName.ToUpper();  
  75.             }  
  76.             // rows  
  77.             for (int i = 0; i < Tbl.Rows.Count; i++)  
  78.             {  
  79.                 // to do: format datetime values before printing  
  80.                 for (int j = 0; j < Tbl.Columns.Count; j++)  
  81.                 {  
  82.                     workSheet.Cells[(i + 2), (j + 1)] = Tbl.Rows[i][j];  
  83.                 }  
  84.             }  
  85.             excelCellrange = workSheet.Range[workSheet.Cells[1, 1], workSheet.Cells[rowcount, Tbl.Columns.Count]];  
  86.             excelCellrange.EntireColumn.AutoFit();  
  87.             Microsoft.Office.Interop.Excel.Borders border = excelCellrange.Borders;  
  88.             border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;  
  89.             workSheet.get_Range("A1""G1").Font.Bold = true;  
  90.             border.Weight = 2d;  
  91.             if (savelocation != null && savelocation != "savelocation")  
  92.             {  
  93.                 try  
  94.                 {  
  95.                     workSheet.SaveAs(savelocation + workSheet.Name + ".xls");  
  96.                     excelApp.Quit();  
  97.                     string email = "atulrawat414@gmail.com";  
  98.                     string filepath = savelocation + name + ".xls";  
  99.                     //send mai with attachment.  
  100.                     await st.sendemail(email, filepath);  
  101.                 }  
  102.                 catch (Exception ex)  
  103.                 {  
  104.                     throw ex;  
  105.                 }  
  106.             }  
  107.             else    // no filepath is given  
  108.             {  
  109.                 excelApp.Visible = true;  
  110.             }  
  111.   
  112.         }  
  113.     }  
  114. }   


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.

  1. public class simpletest  
  2.    {  
  3.        public async Task sendemail(string Toemail, string filePath)  
  4.        {  
  5.            try  
  6.            {  
  7.                await Task.Run(() =>  
  8.                {  
  9.                    MailMessage mail = new MailMessage();  
  10.                    SmtpClient SmtpServer = new SmtpClient("smtp.sendgrid.net");  
  11.                    mail.From = new MailAddress("xxxxxxxx@gmail.com");  
  12.                    mail.To.Add(Toemail);  
  13.                    mail.Subject = "Test Mail - 1";  
  14.                    mail.Body = "mail with attachment";  
  15.                    System.Net.Mail.Attachment attachment;  
  16.                    attachment = new System.Net.Mail.Attachment(filePath);  
  17.                    mail.Attachments.Add(attachment);  
  18.                    SmtpServer.Port = 25;  
  19.                    SmtpServer.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["ApiKey"], ConfigurationManager.AppSettings["ApiKeyPass"]);  
  20.                    SmtpServer.EnableSsl = true;  
  21.                    SmtpServer.Send(mail);  
  22.                });  
  23.            }  
  24.            catch (Exception ex)  
  25.            {  
  26.                throw ex;  
  27.            }  
  28.        }  
  29.    }  

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.