Swiftmailer multiple recipients with different content - php

I am developing a newsletter emailer, where I have to send thousands of mails with different body content. How can I do this using swiftmailer?
Now my code is:
$emails = array('mail1#gmail.com'=>'name1',
'mail2#gmail.com'=>'name2',
'mail3#gmail.com'=>'name3',
'mail4#gmail.com'=>'name4',
'mail5#gmail.com'=>'name5');
$message = Swift_Message::newInstance('Testing Email')
->setFrom(array('mail1#gmail.com' => 'name'))
->setTo($emails) //$emails
->setReplyTo(array('reply_to#gmail.com' => 'reply'));
$html = $this->send_model->getEmailContent();
$body = $html;
$message->setBody($body, 'text/html')
;
// Send the message
$result = $mailer->send($message);
I want to send all separate mails for all the emails which are in the above array.. with different body content.
Thanks in advance.

Related

Send different email content with $mail php

I have a small problem here that I'm tried to fix for some couple of hours already. I have a PHP $mail function that send emails to multiple addresses using PHP for loop, like:
foreach($recipients as $name => $email){
$mail->AddAddress($email, $name);
};
Problem is:
I need to get inside the Body message, each email from each user at the time of sending the message, so I can use it as variable inside the body message, I've already tried to use another foreach inside, but no luck.
So the PHP will be something like this:
$mail->Body .='Start of the message';
$mail->Body .='path_url?user_email='.$recipient.'';
$mail->Body .='Endof the message';
Is this possible using $mail?
Thanks!
You should use the same for loop for both email addresses and your content.
With out knowing your code in details, I assume you have array contenting recipients email, name and message or something else.
Some thing like this with out testing it:
foreach ($recipients as $value)
{
$mail->AddAddress($value['email'], $value['name']);
$mail->Body .= 'Start of the message';
$mail->Body .= 'path_url?user_email=' . $value['recipient'];
$mail->Body .= 'Endof the message';
...
the rest of your $mail code if there so
...
};

Sending PHP emails with HTML/CSS

I'm trying to send emails with PHP. I would like to add some style with CSS (no matter if inline, internal or with external file).
I've tried PHPmailer, but it fails to recognize some elements (such as body), media queries (#media) and declarations (max-width, inline-block, etc...). I'm now trying to use SwiftMailer, but online documentation doesn't mention anything about styling.
Just for sake of clarity, here's the snippet I would like to use: JsFiddle
Any ideas to send PHP emails with working HTML/CSS?
You could use a CSS inliner tool like http://templates.mailchimp.com/resources/inline-css/
to convert your 'normal' template (made like a normal HTML page) to an email-friendly template. This is needed because mail clients doesn't recognise separate elements.
I currently use a template based on the ones made available by Zurb, http://zurb.com/ink/
It also depends on the receiver's email client. Not all clients accept all css. Use a litmus test of some sort to check with different e-mail clients which css you can use. Tables often work with email clients, a lot of them don't accept divs I believe.
I use PHPMailer to send emails with PHP, and it never fails to recognize these elements (for me anyway).
To use it, i create a fonction :
function sendMail($name, $from, $message, $to, $subject)
{
$mail = new PHPMailer();
$body = "<html><head></head><body style=\"background-color: #F2F1F0;\"><p>".$message."</p></body></html>";
$mail->SetFrom($from, $name);
$mail->AddReplyTo($from, $name);
// Only if you want to send an attachment, send a variable $object to the function
//$mail->AddAttachment($object);
$mail->Subject = $subject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
$mail->AddAddress($to, $name);
if(!$mail->Send()) {
$result = $mail->ErrorInfo;
}
else
{
$result = "Mail sent successfully";
}
return $result;
}
And an exemple to use it :
// Preparation of the message
$message = '<p class="img"><img src="http://mywebsite.com/img/myImage.png" width="220px"></p>';
$message .= '<p class="txt">Hello Mr Dupond !</p>';
$message .= '<p class="txt">We are glad to have you among us</p>';
$message .= '<p class="txt">Se you soon on our Website !</p>';
$message = utf8_decode($message);
// variables needed
$name = "Mr Oktopuss";
$from = "contact#oktopuss.eu";
$to = "contactAddress#domain.ext";
$subject = "The subject of this mail !";
// Send the mail and receive the result
$result = sendMail($name, $from, $message, $to, $subject);
echo $result;
Maybe that could be help you

Swiftmailer remove attachment after send

I am trying to remove the attachment files after sending an email with Symfony 2.1 and Swiftmailer but if I delete the file before returning a response object (a redirect), the email does not send.
I suppose this is because symfony sends the email in the response, so when the email has send the attachment has been removed already.
For example:
<?php
// DefaultCotroller.php
$message = \Swift_Message::newInstance($subject)
->setFrom('no-reply#dasi.es')
->setTo($emails_to)
->setBody($body, 'text/html')
->attach(\Swift_Attachment::fromPath('backup.rar'));
$this->get('mailer')->send();
unlink('backup.rar'); // This remove the file but doesn't send the email!
return $this->redirect($this->generateUrl('homepage'));
An option is to create a crontab to clean the files, but I prefer not using it.
Thanks!
You can look at the code that processes memory spools here:
https://github.com/symfony/SwiftmailerBundle/blob/master/EventListener/EmailSenderListener.php
This is used to batch the emails to be sent.
You can add this after your send() call and before your unlink() call to mimic the behavior of sending an email
$transport = $this->container->get('mailer')->getTransport();
$spool = $transport->getSpool();
$spool->flushQueue($this->container->get('swiftmailer.transport.real'));
I am not sure, but the message spool might cause this problem. In SF2 memory spool is used by default, which means the messages are being sent on the kernel terminate event.
So you'd have to flush the spool before deleting the file.
If this is the cause of your problem, look here for a well explained solution:
http://sgoettschkes.blogspot.de/2012/09/symfony-21-commands-and-swiftmailer.html
In order to complete the very good answer of james_t, if you use multiple mailers some changes are needed.
Replace
// Default mailer
$mailer = $this->container->get('mailer');
$subject = '...';
$from = '...';
$to = '...';
$body = '...';
$message = \Swift_Message::newInstance()
->setSubject($subject)
->setFrom($from)
->setTo($to)
->setBody($body, 'text/html')
;
// Put e-mail in spool
$result = $mailer->send($message);
// Flush spool queue
$transport = $mailer->getTransport();
$spool = $transport->getSpool();
$realTransport = $this->container->get('swiftmailer.transport.real')
$spool->flushQueue($realTransport);
By
// Custom mailer
$mailerServiceName = 'myCustomMailer';
$customMailer = $this->container->get("swiftmailer.mailer.".$mailerServiceName);
$subject = '...';
$from = '...';
$to = '...';
$body = '...';
$message = \Swift_Message::newInstance()
->setSubject($subject)
->setFrom($from)
->setTo($to)
->setBody($body, 'text/html')
;
// Put e-mail in spool
$result = $customMailer->send($message);
// Flush spool queue
$transport = $customMailer->getTransport();
$spool = $transport->getSpool();
$realTransport = $this->container->get('swiftmailer.mailer.'.$mailerServiceName.'.transport.real');
$spool->flushQueue($realTransport);

how to add an attachment to an email in Symfony?

I want to add an attachment to an email. I am using sfmailer class.
Here I have given my code below:
$mail_body = '<p>custom html mail content</p>';
$message = Swift_Message::newInstance('Message title')
->setFrom(array('sender'))
->setTo(array('receiver'))
->setBody($mail_body, 'text/html', 'utf-8');
try {
$this->getMailer()->send($message);
}
catch(Exception $e) {
}
You have several options to attach a document to an email using swift mailer.
From the symfony doc:
$message = Swift_Message::newInstance()
->setFrom('from#example.com')
->setTo('to#example.com')
->setSubject('Subject')
->setBody('Body')
->attach(Swift_Attachment::fromPath('/path/to/a/file.zip'))
;
$this->getMailer()->send($message);
And many others possibility from the swift mailer doc.
Also you can attach a file by resource.
$message = Swift_Message::newInstance()
->setFrom('from#example.com')
->setTo('to#example.com')
->setSubject('Subject')
->setBody('Body')
->attach(Swift_Attachment::newInstance($content, 'invoice.pdf','application/pdf'));

Swiftmailer 4 does not retrieve bounces as $failedRecipients

I am trying this code (from http://swiftmailer.org/docs/sending.html):
require_once 'lib/swift_required.php';
//Create the Transport
$transport = Swift_SmtpTransport::newInstance('localhost', 25);
//Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
//Create a message
$message = Swift_Message::newInstance('Wonderful Subject')
->setFrom(array('john#doe.com' => 'John Doe'))
->setBody('Here is the message itself')
;
//Send the message
$failedRecipients = array();
$numSent = 0;
$to = array('receiver#domain.org', 'other#baddomain.org' => 'A name');
foreach ($to as $address => $name)
{
$message->setTo(array($address => $name));
$numSent += $this->send($message, $failedRecipients);
}
printf("Sent %d messages\n", $numSent);
The problem is that if I sent an email to a bad domain swiftmailer recognize it as a correct sent email and $failedRecipients is empty. In my mail box I have returned a failure notice.
Why does Swiftmailer not recognize this mail as as a failure, and does not populate $failedRecipients Array?
Swiftmailer only takes care to hand the email over to the mail-server. Everything else is not related to Swiftmailer.
What you get is a bounce message, and you need to process them on your own, because the email itself actually was a syntactically mail address that was not rejected by the first server.
That btw is the case for any other mailing library and even the php mail function. You might be looking for a bounce processing application or code.
Related: Bounce Email handling with PHP?

Categories