我想向超过1个人发送电子邮件。为什么这段代码显示此消息:“参数''不能为空字符串参数名称:to”?
connection.Open();
OleDbCommand command1 = new OleDbCommand();
command1.Connection = connection;
string cq = "Select Email From student where S_ID in(select S_ID FROM studentbook where DateDiff('d',[Issue_Date], NOW())=31) ";
command1.CommandText = cq;
OleDbDataAdapter da1 = new OleDbDataAdapter(command1);
DataTable dt1 = new DataTable();
da1.Fill(dt1);
foreach (DataRow row in dt1.Rows)
{
string email = row["Email"].ToString();
MessageBox.Show("Trying to send email ");
using (MailMessage mm = new MailMessage("cuet.library12@gmail.com", email))
{
mm.Subject = "Attention please,renew your book";
mm.Body = string.Format("1 month over,you should renew or return the book");
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
credentials.UserName = "xxxxxxxxxxxxx";
credentials.Password = "xxxxxxxxxx";
smtp.UseDefaultCredentials = true;
smtp.Credentials = credentials;
smtp.Port = 587;
smtp.Send(mm);
MessageBox.Show("Email sent successfully");
}
}
答案 0 :(得分:2)
从数据表中获取电子邮件地址后,请检查电子邮件是否为空。如果它为空则继续下一行。
string email = row["Email"].ToString();
if(String.IsNullOrEmpty(value) || value.Trim().Length == 0)
{
continue;
}
答案 1 :(得分:0)
您必须添加至少一个收件人:
mm.To.Add("email@example.com");
您还可以添加多个收件人。
答案 2 :(得分:0)
试试这个:
mm.To.Add(new MailAddress("addres1@emailserver.com"));
mm.To.Add(new MailAddress("addres2@emailserver.com"));
请勿忘记在以下地址添加地址:
mm.From = new MailAddress("addres3@emailserver.com"));
如果您要在BCC发送电子邮件,可以使用:
mm.Bcc.Add(new MailAddress("addres1@emailserver.com"));
mm.Bcc.Add(new MailAddress("addres2@emailserver.com"));
答案 3 :(得分:0)
我猜你从datatable获得的电子邮件可能为null或为空。因此,在继续发送电子邮件之前,请务必检查空/空字符串。
if(String.IsNullOrEmpty(value))
continue;
此外,如果您要向多个收件人发送相同的电子邮件,则不要在foreach循环中执行所有操作,而是在mm.To.Add("email address to send to");
中添加收件人,然后最后发送电子邮件。
connection.Open();
varcommand1 = new OleDbCommand();
command1.Connection = connection;
varcq = "Select Email From student where S_ID in(select S_ID FROM studentbook where DateDiff('d',[Issue_Date], NOW())=31) ";
command1.CommandText = cq;
varda1 = new OleDbDataAdapter(command1);
vardt1 = new DataTable();
da1.Fill(dt1);
using (var mm = new MailMessage())
{
foreach (DataRow row in dt1.Rows)
{
varemail = row["Email"].ToString();
if(string.IsNullOrWhitespace(email))
continue;
mm.Bcc.Add(email);
}
mm.From.Add("SenderEmailAddress");
mm.Subject = "Attention please,renew your book";
mm.Body = string.Format("1 month over,you should renew or return the book");
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
var credentials = new System.Net.NetworkCredential();
credentials.UserName = "xxxxxxxxxxxxx";
credentials.Password = "xxxxxxxxxx";
smtp.UseDefaultCredentials = true;
smtp.Credentials = credentials;
smtp.Port = 587;
smtp.Send(mm);
}