【问题标题】:Unable to send an email to multiple addresses/recipients using C#无法使用 C# 向多个地址/收件人发送电子邮件
【发布时间】:2011-03-13 15:42:46
【问题描述】:

我正在使用下面的代码,它只发送一封电子邮件 - 我必须将电子邮件发送到多个地址。

我使用不止一封电子邮件:

string connectionString = ConfigurationManager.ConnectionStrings["email_data"].ConnectionString;
OleDbConnection con100 = new OleDbConnection(connectionString);
OleDbCommand cmd100 = new OleDbCommand("select top 3 emails  from bulk_tbl", con100);
OleDbDataAdapter da100 = new OleDbDataAdapter(cmd100);
DataSet ds100 = new DataSet();
da100.Fill(ds100);

    for (int i = 0; i < ds100.Tables[0].Rows.Count; i++)
    //try
    {
        string all_emails = ds100.Tables[0].Rows[i][0].ToString();
        {
            string allmail = all_emails + ";";
            Session.Add("ad_emails",allmail);
            Response.Write(Session["ad_emails"]);
            send_mail();
        }
    }

以及发送我使用的电子邮件:

string sendto = Session["ad_emails"].ToString();

MailMessage message = new MailMessage("info@abc.com", sendto, "subject", "body");
SmtpClient emailClient = new SmtpClient("mail.smtp.com");
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential("abc", "abc");
emailClient.UseDefaultCredentials = true;
emailClient.Credentials = SMTPUserInfo;
emailClient.Send(message);

【问题讨论】:

  • 请查看此处发布的代码。当我重新格式化它时,我发现了一组额外的{ }。我不认为这是故意的,所以我删除了它们。如果你想把它们放回去,只需点击上面的编辑链接。
  • 放一个 , 来分隔不同的电子邮件并创建一个 MailAddress 对象是行不通的!检查此解决方案:stackoverflow.com/questions/7498968/…

标签: c# .net email


【解决方案1】:

问题在于,当 MailMessage 构造函数只接受一个表示单个地址的字符串时,您正在提供一个用分号分隔的地址列表:

包含电子邮件收件人地址的字符串。

或者可能是一个用逗号分隔的列表(见下文)。

Source

要指定多个地址,您需要使用To 属性,即MailAddressCollection,尽管这些页面上的示例并没有很清楚地显示它:

message.To.Add("one@example.com, two@example.com"));

要添加到 MailAddressCollection 的电子邮件地址。多个电子邮件地址必须用逗号字符 (",") 分隔。

MSDN page

所以使用 逗号 分隔的列表创建 MailMessage 应该可以工作。

【讨论】:

  • 你有这个功能的完整例子吗?
【解决方案2】:

这对我有用。 (recipients 是一个字符串数组)

//Fuse all Receivers
var allRecipients = String.Join(",", recipients);

//Create new mail
var mail = new MailMessage(sender, allRecipients, subject, body);

//Create new SmtpClient
var smtpClient = new SmtpClient(hostname, port);

//Try Sending The mail
try
{
    smtpClient.Send(mail);
}
catch (Exception ex)
{
    Log.Error(String.Format("MailAppointment: Could Not Send Mail. Error = {0}",ex), this);
    return false;
}

【讨论】:

    【解决方案3】:

    此函数验证以逗号或分号分隔的电子邮件地址列表:

    public static bool IsValidEmailString(string emailAddresses)
    {
        try
        {
            var addresses = emailAddresses.Split(',', ';')
                .Where(a => !string.IsNullOrWhiteSpace(a))
                .ToArray();
    
            var reformattedAddresses = string.Join(",", addresses);
    
            var dummyMessage = new System.Net.Mail.MailMessage();
            dummyMessage.To.Add(reformattedAddresses);
            return true;
        }
        catch
        {
            return false;
        }
    }
    

    【讨论】:

    • 这需要 .Where(a=> !String.IsNullOrEmpty(a)).ToArray();而是
    • 感谢您的收获。我已经更新了代码,虽然我使用了 .NET 4.0 函数 IsNullOrWhiteSpace
    【解决方案4】:

    要发送给多个收件人,我将收件人字符串设置为逗号作为分隔符。

    string recipient = "foo@bar.com,foo2@bar.com,foo3@bar.com";
    

    然后将收件人添加到MailMessage 对象:

    string[] emailTo = recipient.Split(',');
    for (int i = 0; i < emailTo.GetLength(0); i++)
        mailMessageObject.To.Add(emailTo[i]);
    

    【讨论】:

      【解决方案5】:

      我使用此代码为 to、bcc 和 cc 发送多封邮件

      MailMessage email = new MailMessage();
      Attachment a = new Attachment(attach);
      email.From = new MailAddress(from);//De
      string[] Direcciones;
      char[] deliminadores = { ';' };
      
      //Seleccion de direcciones para el parametro to
      Direcciones = to.Split(deliminadores);
      foreach (string d in Direcciones)
      email.To.Add(new MailAddress(d));//Para
      
      //Seleccion de direcciones para el parametro CC
      Direcciones = CC.Split(deliminadores);
      foreach (string d in Direcciones)
      email.CC.Add(new MailAddress(d));
      
      //Seleccion de direcciones para el parametro Bcc
      Direcciones = Bcc.Split(deliminadores);
      foreach (string d in Direcciones)
      enter code here`email.Bcc.Add(new MailAddress(d));
      

      【讨论】:

        【解决方案6】:

        你也可以通过MailMessage.To.Add()a comma separated list of valid RFC 822 e-mail addresses:

        Nathaniel Borenstein <nsb@bellcore.com>, Ned Freed <ned@innosoft.com>
        

        所以代码是:

        message.To.Add("Nathaniel Borenstein <nsb@bellcore.com>, Ned Freed <ned@innosoft.com>");
        

        注意:任何发布到公共领域的代码。无需注明出处。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-05-18
          • 1970-01-01
          • 2014-06-22
          • 2022-01-02
          • 1970-01-01
          • 2017-12-05
          相关资源
          最近更新 更多