从GridView发送电子邮件

时间:2012-10-24 01:36:29

标签: c# asp.net

我正在尝试发送我的GridView中列出的所有电子邮件但是出于某种原因,电子邮件不会被发送出去。我怀疑我的发送功能(smtpClient.Send(mailMessage);没有工作或者我错过了什么。请帮忙,因为我花了这么多时间搞清楚这一点。谢谢

protected void chkAll_CheckedChanged(object sender, EventArgs e) 
{ 
    foreach(GridViewRow gr in GridView1.Rows) 
    { 
        CheckBox cb = (CheckBox)gr.FindControl("chkItem"); 
        if(((CheckBox)sender).Checked) 
            cb.Checked = true; 
        else 
             cb.Checked = false; 
    } 
} 

protected void Button3_Click(object sender, EventArgs e) 
{ 
    StringBuilder sb = new StringBuilder(); 

    foreach(GridViewRow gr in GridView1.Rows) 
    { 
        CheckBox cb = (CheckBox)gr.FindControl("chkItem"); 
        if(cb.Checked) 
        { 
            sb.Append(GridView1.DataKeys[gr.RowIndex]["Email"].ToString()); 
            sb.Append(","); 
        } 
    } 

    //Create instance of main mail message class. 
    System.Net.Mail.MailMessage mailMessage=new System.Net.Mail.MailMessage(); 

        mailMessage.From = new System.Net.Mail.MailAddress(
                   System.Configuration.ConfigurationManager
                                 .AppSettings["fromEmailAddress"]); 

        mailMessage.Priority = System.Net.Mail.MailPriority.High; 
        //Text/HTML 
        mailMessage.IsBodyHtml = false; 
        mailMessage.Body = "Hello, here is new email"; 
        mailMessage.Subject = "RCA APPROVAL IS REQUIRED"; 

        System.Net.Mail.SmtpClient smtpClient=new System.Net.Mail.SmtpClient();

        try 
        { 
            smtpClient.Send(mailMessage); 

            Response.Write("<B>Email Has been sent successfully.</B>"); 
        } 
        catch (Exception ex) 
        { 
            Response.Write(ex.Message); 
        } 
    }

2 个答案:

答案 0 :(得分:2)

您需要为To

设置MailMessage地址

您可能希望这样做:

protected void Button3_Click(object sender, EventArgs e) 
{
    MailMessage mailMessage=new MailMessage(); 

    foreach(GridViewRow gr in GridView1.Rows) 
    { 
        CheckBox cb = (CheckBox)gr.FindControl("chkItem"); 
        if(cb.Checked) 
        { 
            //sb.Append(GridView1.DataKeys[gr.RowIndex]["Email"].ToString()); 
            //sb.Append(","); 

            //SETUP THE EMAIL ADDRESSES TO WHICH YOU WANT TO SEND EMAIL
            mailMessage.To.Add(new MailAddress(
                     GridView1.DataKeys[gr.RowIndex]["Email"].ToString()));
        } 
    } 

此外,如果您的SMTP服务器需要身份验证,您还需要提供Credentials。或者,您可以将所有设置放在 web.config 中的<system.net><mailSettings>标记中shown here,而不是强烈的 Scott Gu < / p>

答案 1 :(得分:0)

这是因为您没有将电子邮件发送给任何人。

使用gridview上的选定地址设置mailMessage.To属性的值。

此外,请检查您的SMTP服务,可能需要提供凭据并启用SSL。