Our requirement is that we have to send the data of DataGridView in mail in tabular form.
private void button1_Click(object sender, EventArgs e)
{
try
{
//Create instance of MailMessage Class
MailMessage mail = new MailMessage();
//Assign From mail address
mail.From = new MailAddress("frommail@gmail.com");
//Set To mail address
mail.To.Add(new MailAddress("tomaiil@gmail.com"));
//Set Subject of mail
mail.Subject = "Send DataGridView Data in Mail";
//Create Mail Body
mail.Body = "Please check the following data"; mail.Body += GetTableFromDataGrid(); //for sending body as HTML
mail.IsBodyHtml = true;
//Create Instance of SMTP Class
SmtpClient SmtpServer = new SmtpClient();
//Assign Host
SmtpServer.Host = "smtp.gmail.com";
//Assign Post Number
SmtpServer.Port = 587;
//Setting the credential for authentiicate the sender
SmtpServer.Credentials = new System.Net.NetworkCredential("mymail@gmail.com", "password");
//Enable teh Secure Soket Layer to Encrypte the connection
SmtpServer.EnableSsl = true;
//Sending the message
SmtpServer.Send(mail);
MessageBox.Show("Mail Sends Successfully!!");
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}public string GetTableFromDataGrid()
{
StringBuilder strTable = new StringBuilder();
try
{
strTable.Append("<table border='1' cellpadding='0' cellspacing='0'>");
strTable.Append("<tr>");
//Create Header Row for Table
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
strTable.AppendFormat("<th>{0}</th>", col.HeaderText);
}
strTable.Append("</tr>");
//Create Table Rows
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
strTable.Append("<tr>");
foreach (DataGridViewCell cell in dataGridView1.Rows[i].Cells)
{
if (cell.Value != null)
{
strTable.AppendFormat("<td>{0}</td>", cell.Value.ToString());
}
}
strTable.Append("</tr>");
}
strTable.Append("</table>");
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
return strTable.ToString();
}Output Mail
0 comments:
Post a Comment