我是否知道如何根据包含电子邮件地址的gridview列发送电子邮件? 我目前正在使用asp.net和c#。我目前也在使用smtp gmail收发电子邮件。
目前,我有一个gridview1,其中包含已退回支票的客户(email,name,accountNo),但是我希望在点击按钮后向所有这些客户发送标准电子邮件。我可以知道我该怎么办呢?他们的电子邮件存储在数据库中,并将显示在gridview上。
private void SendEMail(MailMessage mail)
{
SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 587;
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("@gmail.com", "password");
try
{
client.Send(mail);
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception caught.", ex);
}
答案 0 :(得分:0)
尝试将电子邮件地址保存在数组中。
然后做一个foreach并发送数组中的电子邮件!
示例:
CLASS:
public SmtpClient client = new SmtpClient();
public MailMessage msg = new MailMessage();
public System.Net.NetworkCredential smtpCreds = new System.Net.NetworkCredential("mail", "password");
public void Send(string sendTo, string sendFrom, string subject, string body)
{
try
{
//setup SMTP Host Here
client.Host = "smtp.gmail.com";
client.Port = 587;
client.UseDefaultCredentials = false;
client.Credentials = smtpCreds;
client.EnableSsl = true;
//convert string to MailAdress
MailAddress to = new MailAddress(sendTo);
MailAddress from = new MailAddress(sendFrom);
//set up message settings
msg.Subject = subject;
msg.Body = body;
msg.From = from;
msg.To.Add(to);
// Send E-mail
client.Send(msg);
}
catch (Exception error)
{
}
}
发送电子邮件:(button_click)
//read the emails from the database and save them in an array.
//count how many are the emails, ex: int countEmails = SqlClass.Function("select emails from table").Rows.Count;
string[] emails = new string[countEmails];
foreach (string item in emails)
{
//send e-mail
callClass.Send(item, emailFrom, subject, body); //you can adapt the class
}
答案 1 :(得分:0)
最简单的方法是遍历已绑定到网格视图的数据集。但是既然你已经询问过gridview,那么你可以通过网格视图行进行循环
按钮_点击此处
string email = "";
foreach (GridViewRow item in GridView1.Rows)
{
//considering 1st column contains email address
//if not, replace it with correct index
email = item.Cells[0].Text;
//code to send email
}
更新2
更新我的代码以使用您的sendEmail功能
public void button_click(object sender, EventArgs e)
{
string email = "";
foreach (GridViewRow item in GridView1.Rows)
{
//if not, replace it with correct index
email = item.Cells[4].Text;
//code to send email
//reciever email add
MailAddress to = new MailAddress(email);
//sender email address
MailAddress from = new MailAddress("your@email");
MailMessage msg = new MailMessage();
//use reason shown in grid
msg.Subject = item.Cells[3].Text;
//you can similar extract FName, LName, Account number from grid
// and use it in your message body
//Keep your message body like
str email_msg = "Dear {0} {1}, Your cheque for account number {2} bounced because of the reason {3}";
msg = String.Format(email_msg , item.Cells[0].Text,item.Cells[1].Text,item.Cells[2].Text,item.Cells[3].Text);
msg.Body = email_msg ;
msg.From = from;
msg.To.Add(to);
SendEMail(msg);
}
}