Click here to Skip to main content
Click here to Skip to main content

How to send DataGridView contents by email

, 14 Feb 2008
Rate this:
Please Sign up or sign in to vote.
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 Smile | :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

dianofff
Web Developer
Russian Federation Russian Federation
No Biography provided

Comments and Discussions

 
QuestionHow to attach xml files in datagridview to mail Pinmembersakthey23-Apr-13 18:38 
Questionsome bug? PinmemberTeguh Syahmar17-Jun-08 19:01 
AnswerRe: some bug? Pinmemberycgary7-Oct-08 19:41 
AnswerRe: some bug? PinmemberAlbrecht Jochen14-Sep-09 2:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 15 Feb 2008
Article Copyright 2008 by dianofff
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid