使用C#无法向多个地址/收件人发送电子邮件

21

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

要获取多个电子邮件,我使用以下代码:

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);

请检查此处发布的代码。当我重新格式化它时,发现多了一组 { }。我认为这不是有意的,所以我将其删除了。如果您想要把它们放回去,请点击上面的编辑链接。 - Bill the Lizard
用逗号分隔不同的电子邮件地址并创建MailAddress对象是行不通的!请查看此解决方案:https://dev59.com/g2s05IYBdhLWcg3wB9af - dtakis
6个回答

60
问题在于您向MailMessage构造函数提供了一个由分号分隔的地址列表,而它只接受表示单个地址的字符串:

一个包含电子邮件消息收件人地址的字符串。

或者可能是一个由逗号分隔的列表(见下文)。
来源
要指定多个地址,您需要使用To属性,它是一个MailAddressCollection,虽然这些页面上的示例并不太清楚。
message.To.Add("one@example.com, two@example.com"));

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

MSDN页面

因此,使用以逗号分隔的列表创建MailMessage应该可以正常工作。


1
你有这个功能的完整示例吗? - Julian Moreno

8

这是对我有效的方法。 (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;
}

7

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

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(); 代替。 - Theodosius Von Richthofen
1
谢谢指出。我已经更新了代码,尽管我使用的是.NET 4.0函数IsNullOrWhiteSpace - Matt

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]);

0

您也可以通过MailMessage.To.Add()传递逗号分隔的有效RFC 822电子邮件地址列表

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

那么代码应该是:

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

注意:任何代码都已发布到公共领域。无需归属。

0

这段代码我用于发送多个邮件,包括收件人、密送和抄送

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));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接