Click here to Skip to main content
15,884,176 members
Articles / Programming Languages / C#
Article

How to send DataGridView contents by email

Rate me:
Please Sign up or sign in to vote.
3.33/5 (4 votes)
14 Feb 2008CPOL 75.9K   2.9K   32   4
How to send a DataGridView by mail.

Image 1

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.

C#
//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 :-)

License

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


Written By
Web Developer
Russian Federation Russian Federation
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHow to attach xml files in datagridview to mail Pin
sakthey23-Apr-13 18:38
sakthey23-Apr-13 18:38 
Questionsome bug? Pin
Teguh Syahmar17-Jun-08 19:01
Teguh Syahmar17-Jun-08 19:01 
AnswerRe: some bug? Pin
ycgary7-Oct-08 19:41
ycgary7-Oct-08 19:41 
This is because the DataGridViewCell is empty ,so you can you want to add a judge,Code is as follows:

...
foreach (DataGridViewCell dgvc in dg.Rows[i].Cells)
{
if (!(dgvc.value==null))
{
strB.AppendLine(" " + dgvc.Value.ToString() + " ");
}
}
....
AnswerRe: some bug? Pin
Albrecht Jochen14-Sep-09 2:09
Albrecht Jochen14-Sep-09 2:09 

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

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