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

aze*_*eem 21 .net c# email

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

为了获得多个我使用的电子邮件:

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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

并发送我使用的电子邮件:

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);
Run Code Online (Sandbox Code Playgroud)

Chr*_*isF 60

问题是MailMessage当您只使用表示单个地址的字符串时,您将提供由分号分隔的地址列表到构造函数:

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

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

资源

要指定多个地址,您需要使用To属性a MailAddressCollection,尽管这些页面上的示例不能非常清楚地显示:

message.To.Add("one@example.com, two@example.com"));
Run Code Online (Sandbox Code Playgroud)

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

MSDN页面

所以MailMessage逗号分隔的列表创建应该有效.


VRC*_*VRC 8

这对我有用.(收件人是一个字符串数组)

//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;
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*att 6

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)