Click here to Skip to main content
15,895,084 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi all , i made a code that i can send an email to gmail.com with c# and it is working very well.
Now i want to put my datagridview1 in the email body and send it.
Somone can show me how i can do that?
I searched a lot but i only found useless information and asp.net codes.

Here is my atual code of sending an email .
My datagridview name is : datagridview1

C#
private void btnSend_Click_1(object sender, EventArgs e)
{
    // Create a message with datagridview contents in its body and set up the recipients.





    var client = new SmtpClient("smtp.gmail.com", 587);
    client.EnableSsl = true;
    client.Credentials = new NetworkCredential("jpbritopoker@gmail.com", "*****");

    var mail = new MailMessage();
    mail.From = new MailAddress("youraccount@yahoo.com");
    mail.To.Add("jpbritopoker@gmail.com");
    mail.Subject = "This is the subject of the mail";
    mail.Body = "Here i want my datagridview1";
    client.Send(mail);


}
Posted
Comments
joshrduncan2012 14-May-13 11:42am    
What are you wanting to put in the email? An image of your datagridview or the actual spreadsheet itself?
Pedro Brito 14-May-13 11:45am    
I want to put an image of it

You can't send a DataGridView to an email, any more than you could send a Button, and expect it to signal an event on your system when it was pressed. Suppose you could, and the remote system did not have .NET installed? What would happen then?

Instead, set the mail body to HTML (use MailMessage.IsBodyHtml = true), and send it as an HTML Table instead. This should help: From DataGridView to HTML[^]
 
Share this answer
 
I found one easy code :)

XML
var client = new SmtpClient("smtp.gmail.com", 587);
           client.EnableSsl = true;
           client.Credentials = new NetworkCredential("jpbritopoker@gmail.com", "**********");

           var mail = new MailMessage();
           mail.From = new MailAddress("youraccount@yahoo.com");
           mail.To.Add("jpbritopoker@gmail.com");
           mail.IsBodyHtml = true;
           mail.Subject = "This is the subject of the mail";

            string mailBody = "<table>";

     foreach (DataGridViewRow row in dataGridView1.Rows)
     {
           mailBody +="<tr>";
           foreach (DataGridViewCell cell in row.Cells)
           {
              mailBody +="<td>" +cell.Value + "</td>";
           }
           mailBody +="</tr>";
     }
     mailBody +="</table>";

     //your rest of the original code
     mail.Body = mailBody;
           client.Send(mail);
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900