65.9K
CodeProject is changing. Read more.
Home

How to send DataGridView contents by email

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.33/5 (4 votes)

Feb 15, 2008

CPOL
viewsIcon

76862

downloadIcon

2890

How to send a DataGridView by mail.

Introduction

In my work, it is very often required to generate some reports based on database contents. I use the Windows Forms DataGridView and print its contents, but here is a question - how can I send emails with the DataGridView contents? I can send emails with DataGridView contents in two ways - directly in the message body or as an attachment (in my example, as an HTML file).

Using the code

First of all, let's load data into the DataGridView. In this example, I use an XML file as a data source. I've placed it in the bin/Debug folder. I then create an HTML file from the DataGridView. For this, I have a StringBuilder with the DataGridView contents in it.

After that, I can either put it in the message body or in the attachment.

//binding data from xml file to datagridview
DataSet ds = new DataSet();
ds.ReadXml("dataFile.xml");//xml file placed in bin/Debug folder
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "authors"; 

private StringBuilder htmlMessageBody(DataGridView dg)
{
    StringBuilder strB = new StringBuilder();
    //create html & table
    strB.AppendLine("<html><body><center><" + 
                    "table border='1' cellpadding='0' cellspacing='0'>");
    strB.AppendLine("<tr>");
    //cteate table header
    for (int i = 0; i < dg.Columns.Count; i++)
    {
        strB.AppendLine("<td align='center' valign='middle'>" + 
                        dg.Columns[i].HeaderText + "</td>");
    }
    //create table body
    strB.AppendLine("<tr>");
    for (int i = 0; i < dg.Rows.Count; i++)
    {
        strB.AppendLine("<tr>");
        foreach (DataGridViewCell dgvc in dg.Rows[i].Cells)
        {
            strB.AppendLine("<td align='center' valign='middle'>" + 
                            dgvc.Value.ToString() + "</td>");
        }
        strB.AppendLine("</tr>");

    }
    //table footer & end of html file
    strB.AppendLine("</table></center></body></html>");
    return strB;} 

    // Create a message with datagridview contents
    // in its body and set up the recipients.
    MailMessage myMessage = new MailMessage();
    try
    {
        myMessage.From = "from@yourDomain.com";//place here from address
        myMessage.To = "to@recipientsDomain";//place here to address
        myMessage.Cc = "cc@someDomain.com";//place here copy address
        myMessage.BodyEncoding = Encoding.UTF8;
        myMessage.BodyFormat = MailFormat.Html;
        //call method, creating HTML from datagridview
        myMessage.Body = htmlMessageBody(dataGridView1).ToString();
        //place here your subject
        myMessage.Subject = "message subject";

        //if it is needed set up credentials
        myMessage.Fields.Add("http://schemas.microsoft.com/cdo/" + 
                             "configuration/smtpauthenticate", 
                             "1");//Basic Authentication
        myMessage.Fields.Add("http://schemas.microsoft.com/cdo/" + 
                             "configuration/sendusername", 
                             "userName");//user name
        myMessage.Fields.Add("http://schemas.microsoft.com/cdo/" + 
                             "configuration/sendpassword", 
                             "password");//password
        //place here SMTP server
        SmtpMail.SmtpServer = "your SMTP server";
        SmtpMail.Send(myMessage);
        MessageBox.Show("Message sent!");
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error! "+ex.Message);
    }
       
    //create message with datagridview contents in attachment
    MailMessage myMessage = new MailMessage();
    try
    {
        myMessage.From = "from@yourDomain.com";//place here from address
        myMessage.To = "to@recipientsDomain";//place here to address
        myMessage.Cc = "cc@someDomain.com";//place here copy address
        myMessage.BodyEncoding = Encoding.UTF8;
        myMessage.BodyFormat = MailFormat.Html;
        myMessage.Body = "some body text";//place here some text
        myMessage.Subject = "message subject";//place here your subject
        //creating attachment
        StreamWriter sw = new StreamWriter("file.html", 
                          true, Encoding.UTF8);//creating html file
        //write datagridview contents to HTML file
        sw.Write(htmlMessageBody(dataGridView1).ToString());
        sw.Close();
        //create attachment
        MailAttachment myAttach = new MailAttachment("file.html");
        myMessage.Attachments.Add(myAttach);//add attachment to our message

        //if it is needed set up credentials
        myMessage.Fields.Add("http://schemas.microsoft.com/cdo/" + 
                             "configuration/smtpauthenticate", 
                             "1");//Basic Authentication
        myMessage.Fields.Add("http://schemas.microsoft.com/cdo/" + 
                             "configuration/sendusername", 
                             "userName");//user name
        myMessage.Fields.Add("http://schemas.microsoft.com/cdo/" + 
                             "configuration/sendpassword", 
                             "password");//password
        //place here SMTP server
        SmtpMail.SmtpServer = "your SMTP server";
        SmtpMail.Send(myMessage);
        MessageBox.Show("Message sent!");
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error! " + ex.Message);
    }

Points of Interest

Now, I do not need to export my DataGridView into a Word or Excel file and then send it to my chief - I can directly send the DataGridView to him :-)