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

How to send DataGridView contents by email

By , 14 Feb 2008
 

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 :-)

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
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionHow to attach xml files in datagridview to mailmembersakthey23 Apr '13 - 18:38 
Questionsome bug?memberTeguh Syahmar17 Jun '08 - 19:01 
AnswerRe: some bug?memberycgary7 Oct '08 - 19:41 
AnswerRe: some bug?memberAlbrecht Jochen14 Sep '09 - 2:09 

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 15 Feb 2008
Article Copyright 2008 by dianofff
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid