简体   繁体   中英

C# MVC Send email to multiple recipient

I have trying to send one mail to Test1 and Test2. I tried separating the recipients with ; like To ="Test1@stanleytests.co.za;Test2@stanleytests.co.za" that did not work and also tried concatenating them by doing To="Test1@stanleytests.co.za"+"Test2@stanleytests.co.za" that did not work. now I wrote and Array. the thing with my array is that it sends 2 mails, so i only want to sent one mail to two recipient.

private void SendDailyEmails(DateTime today)
 {
   today = DateTime.Now;
   string recipient = "Test1@stanleytests.co.za,Test2@stanleytests.co.za";
   string[] emailTo = recipient.Split(',');

    for (int i = 0; i < emailTo.GetLength(0); i++)
     {
       var emailObject = new EmailObject
        {
          To = emailTo[i],
          Cc = "me@stanleytests.co.za",
          Subject = "Daily Mail",
          Body = "Good morning, <br/><br/> This email is sent to you: <strong> "please be adviced" </strong> <br/><br/>Regards"
         };
          _emailService.SendEmail(emailObject);
     }  
 } 

Please assist here.thanks

We don't know what library you are using for sending emails thus I can only make suggestions.

The convention for joining several email address is to separate them with ; :

emailObject.To = String.Join(";", recipient.Split(','));

Partially your code, see the example below. Honestly, I don't have access to our SMTP servers here, so, I can't really test it. This should set you on the right path. I am guessing your issue really is that you are missing: new MailAddress(i) .

Hope this helps, there are more reference material on MSDN's site.

private void SendDailyEmails()
    {

        var today = DateTime.Now;
        var recipient = "Test1@stanleytests.co.za,Test2 @stanleytests.co.za";

        var message = new MailMessage()
        {
            From =  new MailAddress("Somebody"),
            CC = { new MailAddress("me@stanleytests.co.za") },
            Subject = "Daily Mail",
            Body = @"Good morning, <br/><br/> This email is sent to you: <strong> ""please be adviced"" </strong> <br/><br/>Regards",
            IsBodyHtml = true
        };

        foreach (var i in recipient.Split(',').ToList())
        {
            message.To.Add(new MailAddress(i));
        }

        // do your "_emailService.SendEmail(message);
    }
string body = "Body of email";
var message = new MailMessage();
message.To.Add(new MailAddress("example@exaple.com"));
message.To.Add(new MailAddress("example2@exaple.com"));
message.From = new MailAddress("example@gmail.com", "Name");  
message.Subject = "This is the subject";
message.Body = body;
message.IsBodyHtml = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM