如何使用System.Net.Mail将电子邮件发送到多个地址

Den*_*ish 52 .net c# smtp

我有smtp电子邮件功能.它适用于单个地址但在多个地址中有问题.

我使用以下代码行传递多个地址.

MailAddress to = new MailAddress("abc@gmail.com,xyz@gmail.com");
Run Code Online (Sandbox Code Playgroud)

请告诉我这个问题,因为我没有收到任何错误.

Mar*_*rco 84

MailMessage msg = new MailMessage();
msg.Body = ....;
msg.To.Add(...);
msg.To.Add(...);

SmtpClient smtp = new SmtpClient();
smtp.Send(msg);
Run Code Online (Sandbox Code Playgroud)

To是一个MailAddressCollection,所以你可以添加你需要的地址.

如果您需要显示名称,请尝试以下操作:

MailAddress to = new MailAddress(
    String.Format("{0} <{1}>",display_name, address));
Run Code Online (Sandbox Code Playgroud)

  • 您无需单独添加每个收件人.`msg.To.Add("abc @ gmail.com,xyz @ gmail.com");`工作正常. (5认同)
  • 来自地址怎么样? (3认同)

Har*_*ala 23

试试这个..

using System;
using System.Net.Mail;

public class Test
{
    public static void Main()
    {
        SmtpClient client = new SmtpClient("smtphost", 25);
        MailMessage msg = new MailMessage("x@y.com", "a@b.com,c@d.com");
        msg.Subject = "sdfdsf";
        msg.Body = "sdfsdfdsfd";
        client.UseDefaultCredentials = true;
        client.Send(msg);
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 12

我认为您可以使用此代码以使具有显示名称(也不同)的传出地址列表:

//1.The ACCOUNT
MailAddress fromAddress = new MailAddress("myaccount@myaccount.com", "my display name");
String fromPassword = "password";

//2.The Destination email Addresses
MailAddressCollection TO_addressList = new MailAddressCollection();

//3.Prepare the Destination email Addresses list
foreach (var curr_address in mailto.Split(new [] {";"}, StringSplitOptions.RemoveEmptyEntries))
{
    MailAddress mytoAddress = new MailAddress(curr_address, "Custom display name");
    TO_addressList.Add(mytoAddress);
}

//4.The Email Body Message
String body = bodymsg;

//5.Prepare GMAIL SMTP: with SSL on port 587
var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
    Timeout = 30000
};


//6.Complete the message and SEND the email:
using (var message = new MailMessage()
        {
            From = fromAddress,
            Subject = subject,
            Body = body,
        })
{
    message.To.Add(TO_addressList.ToString());
    smtp.Send(message);
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*leu 10

StewieFG的建议是有效的,但是如果你想添加收件人名称,请使用这个,以及Marco在上面发布的内容,但首先是电子邮件地址,并显示名称第二:

msg.To.Add(new MailAddress("your@email1.com","Your name 1"));
msg.To.Add(new MailAddress("your@email2.com","Your name 2"));
Run Code Online (Sandbox Code Playgroud)