Sending email to multiple Recipients with swiftmailer

二次信任 提交于 2019-12-14 01:15:45

问题


I am trying to use swiftmailer in my project so that I can send html newsletter to multiple users. I have searched thoroughly but all i got never worked for me. I want to paste more than one recipient in the form input field seperated by comma and send the html email to them. I set the recipients to a variable($recipients_emails) and pass it to setTo() method in the sending code, same with the html_email.

Questions are: Q1 How do i send to more than one recipient from the recipient input field.

I tried this:

if (isset($_POST['recipients_emails'])) {
    $recipients_emails  = array($_POST['recipients_emails'] );
    $recipients_emails= implode(',',$recipients_emails);
}

Q2 How do I make the Html within heredoc tag. when i tried concatenating like this ->setBody('<<<EOT'.$html_email.'EOT;', 'text/html'); , my message would appears with the heredoc tag.

if (isset($_POST['html_email'])) {
    $html_email = $_POST['html_email'];
}

How do I have input from $_POST['html_email']; to be within EOT tag;

this in part of swiftmailer sending script ;

$message = Swift_Message::newInstance()
        ->setSubject($subject)
        ->setFrom($from)
        ->setTo($recipients_emails)
        ->setBody($html_email, 'text/html');

Nota bene : Am still learning these things.


回答1:


According to this document

// Using setTo() to set all recipients in one go
$message->setTo([
  'person1@example.org',
  'person2@otherdomain.org' => 'Person 2 Name',
  'person3@example.org',
  'person4@example.org',
  'person5@example.org' => 'Person 5 Name'
]);

You can input array directly into setTo, setCc or setBcc function, do not need to convert it into string




回答2:


Ok so first of all you need to create a variable that form your heredoc contents. The end tag of heredoc has to have no whitespace before it and then use that variable. (to output variables inside heredoc you need to wrap them with curly braces) see example..

$body = <<<EOT
 Here is the email {$html_email}

EOT;

$message = Swift_Message::newInstance()
        ->setSubject($subject)
        ->setFrom($from)
        ->setTo($recipients_emails)
        ->setBody($body, 'text/html');



回答3:


You should validate the input-data by first exploding them into single E-Mail-Adresses and push the valid Data into an Array. After this you can suppy the generated Array to setTo().

<input type="text" name="recipients" value="email1@host.com;email2@host.com;...">

On Submit

$recipients = array();

$emails = preg_split('/[;,]/', $_POST['recipients']);
foreach($emails as $email){
 //check and trim the Data
 if($valid){
  $recipients[] = trim($email);
  // do something else if valid
 }else{
  // Error-Handling goes here
 }
}


来源:https://stackoverflow.com/questions/44828531/sending-email-to-multiple-recipients-with-swiftmailer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!