2017-08-30 69 views
-1

這是我的代碼發送datagridview作爲電子郵件。此代碼只適用於在datagridview中發送數據。發送datagridview作爲標題郵件

請指導我如何添加表頭。我希望將電子郵件作爲包含表格標題的整個表格發送。

var client = new SmtpClient("smtp.gmail.com", 587); 
client.EnableSsl = true; 
client.Credentials = new NetworkCredential("from_mail", "password"); 

var mail = new MailMessage(); 
mail.From = new MailAddress("from_mail"); 
mail.To.Add("to_mail"); 
mail.IsBodyHtml = true; 
mail.Subject = "test"; 

string mailBody = "<table width='100%' style='border:Solid 1px Black;'>"; 

foreach (DataGridViewRow row in dataGridView2.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); 
MessageBox.Show("mail send"); 
this.Close(); 
+0

[發送DataGridView的電子郵件]的可能的複製(https://stackoverflow.com/questions/16547588 /送的datagridview至電子郵件) –

回答

0

對於轉換您DataGridViewHTML用於在電子郵件中發送,請使用下面的功能:

private StringBuilder DataGridtoHTML(DataGridView dg) 
{ 
    StringBuilder strB = new StringBuilder(); 

    //create html & table 
    strB.AppendLine("<html><body><center><" + 
       "table border='1' cellpadding='0' cellspacing='0'>"); 
    strB.AppendLine("<tr>"); 

    //create 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; 
}