Sending email to multiple Recipients with swiftmailer - php

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.

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

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
}
}

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

Related

my $to variable contains email addresses but i want it one by one in mail function that it gets first email and send it ,then move on second address

$to="example#.com,example#.com"; // i want this email addresses one by one in $tto in mail function
$contacts = array("$to");
foreach($contacts as $contact)
{
$tto = $contact;
$subject="hey";
$body="Test";
$header="example#.com";
if(mail($tto,$subject,$body,$header))
{
echo "SEND";
}}
?>
my $to variable contains email addresses but i want it one by one in
mail function that it gets first email and send it ,then move on
second address, i have tried this code but this is not working
to change/split a string into an array we can use explode function:
in case they are always in comma-separated form:
$to = "example#domain.com,example2#domain.com";
$contacts = explode(",", $to);
array_walk($contacts, 'trim');
// The rest of your code ... (starting from 'foreach')

How to send an email in multiple chunks?

I'm using the php mail function to send email and it's working fine.
The email body is dynamically generated and the problem is that the email recipient can only receive emails that are 160 characters or less. If the body of the email is longer than 160 characters, then I want to split the body into separate blocks, each less than 160 characters.
I'm using CRON Jobs and curl to automatically send the email.
How can I send each separate email to the same recipient when more than one body is generated? Below $bodyAll represents that there is only one email to be sent because the dynamically generated content fits within 160 characters. If the body content is more than 160, then $bodyAll would not be sent and $bodyFirstPart would be sent to the recipient, then $bodySecondPart, etc., until all the separate body texts are sent.
$body = $bodyAll;
$body = $bodyFirstPart;
$body = $bodySecondPart;
$body = $bodyThirdPart;
$mail->addAddress("recepient1#example.com");
$mail->Subject = "Subject Text";
$mail->Body = "<i>Mail body</i>";
if(!$mail->send())
you can use strlen to check the length inside a while loop trimming it down with substr, and send each chunk every loop iteration:
<?php
$bodyAll = "
some really long text that exceeds the 160 character maximum for emails,
I mean it really just tends to drag on forever and ever and ever and ever and
ever and ever and ever and ever and ever and ever and ever......
";
$mail->addAddress("recepient1#example.com");
$mail->Subject = "Subject Text";
while( !empty($bodyAll) ){
// check if body too long
if (strlen($bodyAll) > 160){
// get the first chunk of 160 chars
$body = substr($bodyAll,0,160);
// trim off those from the rest
$bodyAll = substr($bodyAll,160);
} else {
// loop terminating condition
$body = $bodyAll;
$bodyAll = "";
}
// send each chunk
$mail->Body = "$body";
if(!$mail->send())
// catch send error
}

how to justify this contact form results?

i have made my contact form and it's working good except that when someone send me a message it comes without any format like the image below:
this is my .php code that i use:
$formdata = array (
'name' => $name,
'city' => $city,
'message' => $message
);
if ( !( $formerrors ) ) :
$to = "me#sipledomain.com";// input my name address to get mail to
$subject = "From $name";
$message = json_encode($formdata);
if ( mail( $to, $subject, $message ) ):
$msg = "Thanks for filling out the form, i will contact you soon";
else:
$msg = "Problem sending the message";
endif; // mail form data
endif; // check for form errors
endif; //form submitted
thanks in advance
json_encode() encodes your array into a single line of text designed to be decoded later, not for reading by humans.
Instead I would build your email message yourself by writing your own HTML or by giving it line breaks. You could do it programmatically by parsing/iterating through your array.
Eg:
$message = 'Name: '.$formdata['name'].'<br />'.$formdata['city'].'<br />'.'...';
If you really want to encode into JSON, you will need to do parse the JSON after you encode and do the same thing.
You might want to look into a flag when you call json_encode() called JSON_PRETTY_PRINT which will keep whitespace. More info: http://www.php.net/manual/en/json.constants.php
In use: $message = json_encode($formdata, JSON_PRETTY_PRINT);
For playing with JSON I like to use tools like http://jsonmate.com/ that formats JSON into a neat tree.
If you want, send the email as formatted HTML by wrapping everything in standard HTML tags. Otherwise, PHP sends messages as unformatted, so use \n to break lines etc.

load html mail file inside php

I implemented a html email inside a html file. And i have a php file which uses the PHPMailer class to send emails.
What i want to achieve is, i have some text inside the html that should change depends who i send the email.
This is the php file that sends the emails
<?php
// get variables
$contact_name = addslashes($_GET['contact_name']);
$contact_phone = addslashes($_GET['contact_phone']);
$contact_email = addslashes($_GET['contact_email']);
$contact_message = addslashes($_GET['contact_message']);
// send mail
require("class.phpmailer.php");
$mailer = new PHPMailer();
$mailer->IsSMTP();
$mailer->Host = 'ssl://smtp.gmail.com:465';
$mailer->SMTPAuth = TRUE;
$mailer->Username = 'danyel.p#gmail.com';
$mailer->Password = 'mypass';
$mailer->From = 'contact_email';
$mailer->FromName = 'PS Contact';
$mailer->Subject = $contact_name;
$mailer->AddAddress('pdaniel#gmail.com');
$mailer->Body = $contact_message;
if($mailer->Send())
echo 'ok';
?>
And the html file containing a simple html mail implemented with tables and all that standard it need.
I want to ask braver minds than mine which is the best approach to accomplish this. :)
Thank you in advance,
Daniel!
EDIT: right now, in the $mailer->Body i have the $contact_message variable as a text email.. but i want in that body to load an html file containing an html email and i want to somehow change the body of the html email with the text inside this $contact_message variable.
One simple way to go is to have special tokens in your html files that will be replaced by the caller. For example assuming that you have two variables that might dynamically change content, name, surname then put something like this in your html: %%NAME%%, %%SURNAME%% and then in the calling script simply:
$html = str_replace("%%NAME%%", $name, $html);
$html = str_replace("%%SURNAME%%", $surname, $html);
or by nesting the two above:
$html = str_replace("%%NAME%%", $name, str_replace("%%SURNAME%%", $surname, $html));
EDIT
A more elegant solution in case you have many variables: Define an associative array that will hold your needles and replacements for them:
$myReplacements = array ( "%%NAME%%" => $name,
"%%SURNAME%%" => $surname
);
and use a loop to make it happen:
foreach ($myReplacements as $needle => $replacement)
$html = str_replace($needle, $replacement, $html);
Create conditional statements based on the email you want to see to.
Then include that in the tempalted php html email text.
You can also pass the changing values to a function which will implement the above.
If I build a website I usually use a templating engine, something like Smarty... You could write your html mail in a smarty template file. Then you could add the wanted texts based on criteria automatically. Just assign the correct values to the templating engine.
To answer your edit:
function renderHtmlEmail($body) {
ob_start();
include ('my_html_email.php');
return ob_get_clean();
}
In your my_html_email.php file you would have something like so:
<html>
<body>
<p>....<p>
<!-- the body -->
<?php echo $body; ?>
</body>
</html>
And
$mailer->Body = renderHtmlEmail($contact_message);
If you need other variables to pass to the layout/template file, add params to that method, or pass an associative array like so function renderHtmlEmail($viewVars) and inside the function extract($viewVars);
You will then be able to use those vars inside the template, for ex. Dear <?php echo $to; ?>,
You will probably have to change your html file from .html to .php if it isn't already.
That is, if I understood the issue correctly.

Calling require_once() inside foreach loop, code is not available on each iteration

I have an array of emails and want to send an email for each entry in the array but currently it only sends it to the first address. I have looked around and can't see what I am doing wrong.
//This is the array
$emails = array($teamleademail, $coleademail, $sponsoremail, $facilitatoremail, $cisupportemail);
//Now the foreach statment
foreach ($emails as $value) {
//pulls in email sending code
require_once ("Mail.php");
//variables required to send the email
$from = "Scope Sheet Process Database (no reply)<scopesheetprocess#goodrich.com>";
//Make the $to variable that of the email in the array
$to = "$value";
$subject = "Scope Sheet $scopesheetid Closed";
$body = "Scope Sheet $scopesheetid has been closed and can no longer be edited.";
//send email code
require_once ("sendemail.php");
}
I am using pear php to send the email because of IT issues but that shouldn't matter since it should be running the scripts each time and sending separate emails.
The problem is this line:
require_once ("sendemail.php");
...should just be
require ("sendemail.php");
As it is, it will only be included on the first iteration of the loop, hence only the first email is sent.
This on its own may not fix your problem - if it doesn't we'll need to see the code in sendemail.php.

Categories