Sending An Email With Attachment Of Database Table Using C# Windows forms Application.
In this article I will show you how to send email with attachment (We can Send our full database table) in one click using Gmail SMTP Mail server.
I explained about how to send email with attachment (like Excel file)using Gmail SMTP Mail Server in c# windows forms application.
Step 1: Create a new project in Microsoft Visual Studio 2015 (File -> New -> Project -> Visual C# -> Windows Forms Application)Type Some Name: to Your Form then Click Ok Button.
Step 2: Now Go to Add Reference(Solution Explorer ->Reference -> Add Reference),
Select ClosedXml.dll , DocumentFormat.OpenXml.dll , MySql.Data.dll.
If You Don’t Have This In Your Reference Page DOWNLOAD this here in this link.
And We need OpenXMLSDv2.msi For sending mail Download this at here.
Step 3: Import the below namespaces – (just type them after ‘using System.Text’).
- using ClosedXML.Excel;
- using System.Net.Mail;
- using System.IO;
- using MySql.Data.MySqlClient;
After Complete this Now Our Coding is:
- using ClosedXML.Excel;
- using MySql.Data.MySqlClient;
- using System;
- using System.Data;
- using System.IO;
- using System.Net.Mail;
- using System.Windows.Forms;
- namespace SendingMail
- {
- public partial class Form1: Form
- {
- public Form1()
- {
- InitializeComponent();
- }
-
- String MyConString = "SERVER=******;" + "DATABASE=*****;" + "UID=root;" + "PASSWORD=pws;" + "Convert Zero Datetime = True";
-
- private void btnSend_Click(object sender, EventArgs e)
- {
- DataTable dt = GetData();
- dt.TableName = "data";
- using(XLWorkbook wb = new XLWorkbook())
- {
- wb.Worksheets.Add(dt);
- using(MemoryStream memoryStream = new MemoryStream())
- {
- wb.SaveAs(memoryStream);
- byte[] bytes = memoryStream.ToArray();
- memoryStream.Close();
- using(MailMessage Msg = new MailMessage())
- {
- Msg.From = new MailAddress("YOUR MAIL ID .com");
- Msg.To.Add(txtTo.Text);
- Msg.Subject = "DATA Exported Excel";
- Msg.Body = "DATA Exported Excel Attachment";
- Msg.Attachments.Add(new Attachment(new MemoryStream(bytes), "DATA.xlsx"));
- Msg.IsBodyHtml = true;
- SmtpClient smtp = new SmtpClient();
- smtp.Host = "smtp.gmail.com";
- smtp.EnableSsl = true;
- System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
- credentials.UserName = "YOUR MAIL ID . com";
- credentials.Password = "YOUR MAIL ID PASSWORD";
- smtp.UseDefaultCredentials = true;
- smtp.Credentials = credentials;
- smtp.Port = 587;
- smtp.Send(Msg);
- MessageBox.Show("MAIL SENT SUCCESSFULLY TO " + txtTo.Text);
- txtTo.Text = "";
- }
- }
- }
- }
- private DataTable GetData()
- {
- using(MySqlConnection conn = new MySqlConnection(MyConString))
- {
- using(MySqlCommand cmd = new MySqlCommand("SELECT * from TABLE NAME;", conn))
- using(MySqlDataAdapter sda = new MySqlDataAdapter())
- {
- cmd.Connection = conn;
- sda.SelectCommand = cmd;
- using(DataTable dt = new DataTable())
- {
- sda.Fill(dt);
- return dt;
- }
- }
- }
- }
- }
- }