Swift mailer default sender - php

I'm trying to set a default sender to all messages in Swift Mailer 4.3.0, but couldn't find a proper solution. I want to avoid using ->setFrom() in every message, since it'll be a future headache. I could use a constant for that, but I was looking for a more elegant solution.
$message = Swift_Message::newInstance()
->setSubject('subject')
->setFrom(array('sender#domain.com' => 'Sender'))
->setTo(array('recipient#domain.com'))
->setBody('Message');
Thanks!

You can't.
As far as I know, you can't omit this parameter.
A From: address is required and is set with the setFrom() method of the message. From: addresses specify who actually wrote the email, and usually who sent it.
This is maybe the best solution:
->setFrom(MyClass::FROM_EMAIL);
Once thing you can try, is to create an instance once in your application, and clone it when you want to send a new mail without re-defining the from part:
// somewhere early in your app
$message = Swift_Message::newInstance()
->setFrom(array('sender#domain.com' => 'Sender'));
And then, somewhere else:
$newMessage = clone $message;
$newMessage
->setSubject('subject')
->setTo(array('recipient#domain.com'))
->setBody('Message')
->send();

If you use a SwiftMailer ≥ 4 and are familiar with Composer, you can use a Defaults Plugin for SwiftMailer to achieve this.
First install the package:
composer require finesse/swiftmailer-defaults-plugin
Second set up a Swift_Mailer instance:
$mailer = new Swift_Mailer(/* your transport here */);
$mailer->registerPlugin(new Finesse\SwiftMailerDefaultsPlugin\SwiftMailerDefaultsPlugin([
'from' => ['sender#domain.com' => 'Sender']
]));
And then send emails without specifying the from address:
$mailer->send((new Swift_Message())
->setSubject('subject')
->setTo(array('recipient#domain.com'))
->setBody('Message'));

Related

Duplicate e-mail subject from ZF2 Sendmail

I'm working on a form on a Zend Framework 2 website, which sends an e-mail using Mail\Transport\Sendmail().
I don't know if it's a server (I'm working in local, Win10 and XAMPP) or framework problem, but the e-mails I receive have duplicate subject.
My code is quite long but very simple at its core, and I use setSubject($subject) to add the subject to the e-mail. If $subject = "TEST", the e-mail I will receive will have the subject "TEST, TEST".
What is wrong and how could I fix this?
if ($form->isValid()) {
$transport = new Mail\Transport\Sendmail();
$mail = new Mail\Message();
$mail->setFrom("my#email.com", "Me");
$mail->addTo($senderEmail, $senderName);
$mail->setSubject($subject);
$mail->setBody($body);
$transport->send($mail);
}
All works fine, but on the received e-mail subject will be duplicated, with a comma in the middle: "$subject, $subject".
I had the same problem, and I changed the transport agent to Zend\Mail\Transport\Smtp instead of using sendmail.
use Zend\Mail\Transport\Smtp as SmtpTransport;
...
$transport = new SmtpTransport();

Swift Mailer can address be banned for mass mailing?

I need to send over 2000 mails and I am using Swift Mailer library for it.
We have own server and it has both SMTP and sendmail transports. I am using SMTP:
$transport = Swift_SmtpTransport::newInstance('localhost', 25);
All mails are send fine to few people, but I'm afraid that we will be banned when we send mass mail.
I don't really know what means "banned" and how it looks like, but I'm afraid about the aftermath.
So, is it true, that such "ban" exists and how to implement mass mailing with Swift Mailer in a right way?
P.S.: My code looks like:
// 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($message_theme)
->setFrom(array($sender => $name))
->setTo($emails)
->setBody($message_text,"text/html")
;
try {
// Send the message
$result = $mailer->send($message);
}
catch(Exception $e) {
echo "Error: ".$e->getMessage();
}
As I'm hoping you will not use this for spam!!!
Here are some things to do:
try to same different Emails (change name of the recipient in body)
send emails once every 3-4 seconds and not 100 emails/second - it should send 2000 emails in about 2-3 hours.
Blacklisting/graylisting does indeed exist and there are some best practices you can implement to try to avoid these issues. For 2,000 emails, as long as your headers are legitimate, there is nothing fishy going on in your body text, and your recipients are on different domains, you should not run into this issue. However, as khomyakoshka mentions, the above code is incorrect and you should use a loop to send each email. This avoids exposing your entire mail list to each user.
Some additional best practices:
1) Swiftmailer offers plugins (http://swiftmailer.org/docs/plugins.html) that will help you send bulk email. Of particular note are the Throttler and AntiFlood plugins.
2) If you intend on modifying the contents of the mail to tailor to the recipient, consider using the Decorator plugin (also mentioned on the plugins page) for this task.
Hope these tips help.

PHPMailer 5.1 sends duplicatie mails when adding more than 1 receiver

I'm using PHPMailer for a while now and never really had any problems, but last week I installed one of my CMS on a website and the client insisted on having 2 e-mails receiving the contents of the contact form of his website.
Ok, no problem I thought, just adding an e-mail address using the $phpmailer->AddAddress() function. However, adding a second receiver is causing PHPMailer to send the mail twice to both receivers. I tried adding a third receiver to see if I got it three times, but this didn't change anything. So adding 2+ receivers is causing PHPMailer to send the message twice to all receivers.
There's nothing strange in my code. It's a basic PHPMailer example:
$mail = new PHPMailer();
$mail->AddReplyTo("name#yourdomain.com","First Last");
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddAddress("info#address.com");
$mail->AddAddress("info#address.nl");
$mail->Subject = "PHPMailer Test Subject via mail(), basic";
$mail->Send();
I've ran out of options. I have absolutely no clue where it's going wrong.
Thanks in advance
--
Just some random thought: I noticed the mailer is defaulted by iso-8859-1 and my site is running utf8. Can there be a "silent" redirect by the server itself?
//EDIT, that ^^ solved my problem
//EDIT2:
Ok, it did not.. today the script worked fine (just 1 mail with 2 receivers) but a moment ago the strange behavior started again. Any tips?
// Solution:
ok, I feel quiet stupid! The answer Zulkhaery Basrul came closest to the actual problem! This is what happened: I was sending an e-mail to multiple addresses in the "to" field. For example:
To: A, B, C
Both A/B are my own adresses. In outlook I had some message rules to put e-mails with certain addressees inside a specific folder. Both A and B had this rule.
When I recieved my e-mail, both mails contained both mailaddresses in the to-field. Causing both of the mails to meet the rule requirements for both rules. Thus keeping the original in one folder and creating a copy in the other (twice).
Thanks for thinking tho :)
You can use $SingleTo property.
From PHPMailer docs:
$SingleTo
Provides the ability to have the TO field process individual emails,
instead of sending to entire 'TO addresses'
$mail = new PHPMailer();
$mail->SingleTo = true; //will send mail to each email address individually
$mail->AddReplyTo("name#yourdomain.com","First Last");
$mail->SetFrom('name#yourdomain.com', 'First Last');
$mail->AddAddress("info#address.com");
$mail->AddAddress("info#address.nl");
$mail->Subject = "PHPMailer Test Subject via mail(), basic";
$mail->Send();
Try to add after
$mail->send();
$mail->ClearAddresses();
Ok, if someone runs into this problem like I did:
My website runs in utf-8, PHPMailer uses iso-8859-1 by default. Somehow the script is run in both charsets causing duplicates. Changing the charset in the class.phpmailer.php file to utf-8 solved the problem!
I think these will do the job :)
$mail->SingleTo = true;
$mail->CharSet = "UTF-8";
I tried everything, UTF8 / BOM check on all files, SingleTo-property, CharSet-property.
It didn't work.
I used the "View Details" function from Gmail and saw that my duplicate mails were sent without a subject.
So, I ended up with a very, very dirty fix.
I put this DIRECTLY below the first line of the send function in the class file:
public function Send() {
if ($this->Subject == "") {
return true;
}
// ... rest of code...
}
I ran into the same problem. The one and only right answer is $mail->ClearAllRecipients()
When I used the accepted answer BCC mails were being sent to all recipients.
SingleTo Is not a good idea. It only works with "sendmail" or "mail" transports, not with SMTP. If you use SingleTo with SMTP, this parameter is just ignored without any error or warning, and you may get duplicates.
According to the authors of the library, SingleTo is planned to be deprecated in the release of PHPMailer 6.0, and removed in 7.0. The authors have explained that it's better to control sending to multiple recipients at a higher level: "PHPMailer isn't a mailing list sender". They tell that the use of the PHP mail() function needs to be discouraged because it's extremely difficult to use safely; SMTP is faster, safer, and gives more control and feedback.
But SMTP is incompatible with SingleTo -- that's why the authors of PHPMailer will remove SingleTo, not SMTP.

PHP Sending mass mails: One for each or one for all?

When sending mass mails with PHP, is it better to send each subscriber an e-mail (running a for loop through all the e-mail addresses) or is it better to just add all in BCC in a comma separated list and thus sending only one e-mail?
Thank you.
There's a good chance the number of addresses in the BCC field is limited on the SMTP server (to avoid spamming). I'd go with the safe route and send an e-mail to each individual subscriber. That will also allow you to customize the e-mail for each subscriber if needed.
Also note that mail() is probably not the best way to send bulk mail (due to the fact that it opens a new connection to the SMTP server each time it's invoked). You may want to look into PEAR::Mail.
Best practice is to send an email per recipient.
If it's a linux mail server, it can handle massive throughputs so volume should not be an issue unless it's a crap server!
If it's a shared webserver your host may not be happy - if this si the case I'd split it into chuncks and spread the send. If it's dedicated then do as you will :)
If the sending process for some reason failed (example cause might me unresolvable domain) for one of the BCC recipients, the whole operation would be canceled (which is in 99% of cases unwanted behavior).
I you send the emails in a PHP loop, even if one of the emails fails to send, other emails will be sent.
As the others says one mail per recipient is the better fit.
If you want a library to do the dirty job for you, give a try to SwiftMailer http://swiftmailer.org
Here is an example directly from the docs:
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'))
->setTo(array('receiver#domain.org', 'other#domain.org' => 'A name'))
->setBody('Here is the message itself')
;
//Send the message
$numSent = $mailer->batchSend($message);
printf("Sent %d messages\n", $numSent);
/* Note that often that only the boolean equivalent of the
return value is of concern (zero indicates FALSE)
if ($mailer->batchSend($message))
{
echo "Sent\n";
}
else
{
echo "Failed\n";
}
*/
It also has a nice Antiflood plugin: http://swiftmailer.org/docs/antiflood-plugin-howto

Send emails to multiple users using PHP/Javascript

I was trying to find an easier way to send e-mails to all my clients using our database (MySQL). I wanted to see if there is a way that it can select all the e-mails of my clients and I can add message, Subject and send it to all of my clients from my website rather than copying each of the mail.
Is there a way to integrate SMTP to do this? either using PHP or javascript.
Thanks.
Yes, there are about 5,247 ways. See these:
PEAR Mail
SwiftMailer
PHPMailer
Zend_Mail
Those are all good (and not the only ones). It is up to you to pick the one that best suits your purpose, there is no "single best" library.
I use SwiftMailer .. it works wonders for me.
* Send emails using SMTP, sendmail, postfix or a custom Transport implementation of your own
* Support servers that require username & password and/or encryption
* Protect from header injection attacks without stripping request data content
* Send MIME compliant HTML/multipart emails
* Use event-driven plugins to customize the library
* Handle large attachments and inline/embedded images with low memory use
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'))
->setTo(array('receiver#domain.org', 'other#domain.org' => 'A name'))
->setBody('Here is the message itself')
;
//Send the message
$numSent = $mailer->batchSend($message);
printf("Sent %d messages\n", $numSent);
/* Note that often that only the boolean equivalent of the
return value is of concern (zero indicates FALSE)
if ($mailer->batchSend($message))
{
echo "Sent\n";
}
else
{
echo "Failed\n";
}
read more here ..
http://swiftmailer.org/docs/batchsend-method

Categories