Sending mass email using PHP - php

I am currently writing a music blog. The administrator posts a new article every 2-3 days. Once the administrator posts an article, a mass email will be sent to around 5000 subscribers immediately.
What is the best way to implement the mass mail feature?
Does the following function work?
function massmail()
{
$content = '...';
foreach ($recipients as $r) {
$_content = $content . '<img src="http://xxx/trackOpenRate.php?id='.$r.'">';
mail($r, 'subject', $_content);
}
}
Another question: If all 5000 subscribers are using Yahoo Mail, will Yahoo treat it as a DDOS attack and block the IP address of my SMTP server?

First off, using the mail() function that comes with PHP is not an optimal solution. It is easily marked as spammed, and you need to set up header to ensure that you are sending HTML emails correctly. As for whether the code snippet will work, it would, but I doubt you will get HTML code inside it correctly without specifying extra headers
I'll suggest you take a look at SwiftMailer, which has HTML support, support for different mime types and SMTP authentication (which is less likely to mark your mail as spam).

I would insert all the emails into a database (sort of like a queue), then process them one at a time as you have done in your code (if you want to use swiftmailer or phpmailer etc, you can do that too.)
After each mail is sent, update the database to record the date/time it was sent.
By putting them in the database first you have
a record of who you sent it to
if your script times out or fails and you have to run it again, then you won't end up sending the same email out to people twice
you can run the send process from a cron job and do a batch at a time, so that your mail server is not overwhelmed, and keep track of what has been sent
Keep in mind, how to automate bounced emails or invalid emails so they can automatically removed from your list.
If you are sending that many emails you are bound to get a few bounces.

This is advice, not an answer: You are much, much better off using dedicated mailing list software. mailman is an oft-used example, but something as simple as mlmmj may suffice. Sending mass mails is actually a more difficult task than it actually appears to be. Not only do you have to send the mails, you also have to keep track of "dead" addresses to avoid your mail, or worse, your mailserver, being marked as spam.
You have to handle people unsubscribing for much the same reason.
You can implement these things yourself, but particularly bounce handling is difficult and unrewarding work. Using a mailing list manager will make things a lot easier.
As for how to make your mail palatable for yahoo, that is another matter entirely. For all its faults, they seem to put great stock in SPF and DomainKey. You probably will have to implement them, which will require co-operation from your mail server administrator.

You may consider using CRON for that kind of operation. Sending mass mail at once is certainly not good, it may be detected as spam, ddos, crash your server etc.
So CRON could be a great solution, send 100 mails at once, then wait a few minutes, next 100, etc.

Do not send email to 5,000 people using standard PHP tools. You'll get banned by most ISPs in seconds and never even know it. You should either use some mailing lists software or an Email Service Provider do to this.

Why don't you rather use phplist? It's also built on top of PHP Mailer and a lot of industry leaders are using it. I've used it myself a couple of times to send out bulk mails to my clients. The nice thing about phplist is that you can throttle your messages on a domain level plus a time limit level.
What we've also done with a couple of internal capture systems we've got was to push our user base to the mailling list and then have a cron entry triggering a given mail each day. The possibilities are endless, that's the awesome thing about open source!

Also the Pear packages:
http://pear.php.net/package/Mail_Mime
http://pear.php.net/package/Mail
http://pear.php.net/package/Mail_Queue
sob.
PS: DO NOT use mail() to send those 5000 emails. In addition to what everyone else said, it is extremely inefficient since mail() creates a separate socket per email set, even to the same MTA.

Also have a look at the PHPmailer class. PHPMailer

You can use swiftmailer for it. By using batch process.
<?php
$message = Swift_Message::newInstance()
->setSubject('Let\'s get together today.')
->setFrom(array('myfrom#domain.com' => 'From Me'))
->setBody('Here is the message itself')
->addPart('<b>Test message being sent!!</b>', 'text/html');
$data = mysql_query('SELECT first, last, email FROM users WHERE is_active=1') or die(mysql_error());
while($row = mysql_fetch_assoc($data))
{
$message->addTo($row['email'], $row['first'] . ' ' . $row['last']);
}
$message->batchSend();
?>

I already did it using Lotus Notus and PHP.
This solution works if you have access to the mail server or you can request something to the mail server Administrator:
1) Create a group in the mail server: Sales Department
2) Assign to the group the accounts you need to be in the group
3) Assign an internet address to the group: salesdept#DOMAIN.com
4) Create your PHP script using the mail function:
$to = "salesdept#DOMAIN.com";
mail($to, $subject, $message, $headers);
It worked for me and all the accounts included in the group receive the mail.
The best of the lucks.

There is more into it aside from using a software. If you could create a bulk emailer program that sends intermittently. Say if you will send 5,000 recipients, create a loop that would send 38 lists per sending then pause for 10 seconds. I have an actual experience sending 500 manually per days for the past weeks and so far i have good results.
Another consideration are the content of your email. Nowadays it is a standard that you need to put your physical office address and the "unsubscribe" opt-out. These are factors that majority of recipient emails servers are checking. If you don't have these they will classify you as spammer.
Mailchimp is my best recommendation to use if you want a paid service provider in sending to your email subscriber NOT sending unsolicited or cold email marketing.
Hope it helps.

Related

Difference between PHP mail function and using email delivery service like Sendgrid, Mandrill

I am building a program and need to send multiple emails based on certain events. I have coded using the PHP mail function but was advised against its use.
Can somebody explain the difference between the workings of the PHP mail function vs using commercial services like Sendgrid, Mandrill etc? Why would one use these services when I can very well use the free PHP mail function to send mails?
Bulk mailing and campaign management is a complex organizational and technological challenge but will not be helped by most opensource php lib for emails (which simply add html formatting and support for attachments).
They won't handle IPR, SPF, spam trap avoidance, bounce handling, throttling, subscription management and more. Which good bulk emaillers provide.
If you know what you are doing, have full admin rights on your system and NS records and time to write the code, then, yes, you could build the same service - but its not just comparing ants to elephants - its comparing a spanner to an orange.
You cannot send bulk emails in one go using this function.
For example, if you want to send emails to 100k users, you will have to iterate over the emails ids. Yes, you can use the cc though but what if you have a template where in every email the user name will be added like:
Dear User abc
You will have to send one by one. You can't achieve this burst email shoot feature in mail function unless you use multiple processes.
MailQueue is good but I have used it, it does the same things, saves the emails into the database and dequeues the emails and send them one by one.
Again we have swift mailer too.
Again, this is on your requirement. If you don't need to send hundreds of notifications that are time sensitive, you don't need these tools then.
comparing mail() to commercial services is like comparing ant to elephant. mail() is good for some fast notifications from the server if you dont need lots of customisation, but if you want to do something like email campaigns you would have to do a lot of additional server setup and build tons of custom functionallity arround your mail() function. Commercial services are good for campaigns but not notifications (waste of money imho). Try using some opensource php lib for emails, that will have a lot of that custom functionality sorted for you.
First of all, by profession I am a part of a global ESP "Pepipost" which helps brands in delivering the business critical triggered and transactional emails to their customers at the most .
But, the intend of myself here answering this question is not to promote an ESP over PHP mail function. I will share you some facts which we observed during our research at Pepipost Labs.
PHP mail function is just a basic method/the core function to generate the email. But, it cannot deliver your emails at a scale, neither it can help in better deliverability, both of these are key to any businesses.
With the evolution of more sophisticated technologies and algorithms, ISPs (Gmail, yahoo, Outlook and others) and Spam Filters are getting more and more smarter. Before reaching the mailbox, each email passes through all these filters where the content, reputation and other parameters are scanned. Hence, its very important to have good reputed IPs and envelope domains.
Once the email reaches the recipient server either it will get deliver, throttle or bounce. In case of Bounce, Spam Complaint, Unsubscribe, the recipient server will communicate your server, and in that case you need to handle all these properly else the reputation of your domain and IP will goes down.
In case of throttling, another set of complex deliver logics required.
In short, if you are planning to send few hundred emails, then PHP mail function might be ok to use, but to scale further it's important to use a good ESP (Email Service Provider).
Mail() function works very simply on *nix systems, it just executes local command sendmail to send message. It does have disadvantages like:
do not work in many cheap hosting environments
You do not have any information if message is accepted by sending MTA, it could be rejected or quarantined or stay forever in local queue
in some environments it could generate garbled headers because of wrong EOL characters (\r\r\n instead of \r\n)
I think You should use open source library like PHPMailer or Swift Mailer, because it has many more functionality besides simply sending mail.
Some advantages of these libraries:
You could easily send HTML mail with attachments and images
You could send messages through external SMTP services
they have DKIM and S/MIME signing support
PS. I do not use commercial services like Sendgrid, Mandrill, thus can't compare.

will adding bcc to php mail save resources?

I am writing an admin notification sytem for my custom CMS. So I am planning of adding a bcc to all the users of sites. So here are my questions?
Is bcc better than the foreach($user){mail()} function? in terms of server resource usage?
How many bcc's will the server support?
Thank you.
A direct mail to a user is usually the 'nicer' option, as it allows you to personalize it. The advantage for you is that you may get the chance to get some feedback by adding a unique id for each mail to each url that links back to your site. Using bcc is just one mail (from the view of your php server), but you shouldn't really worry about server resources here.
Limits for bcc seem to depend on your provider. I have seen limits ranging from 5 too 500.
Sending too many mails at once may also not work due php processing time limits. For many users you will have to split the sending in both cases.
PHP is just the transporter of your request to the SMTP Server, so there is no limitations in PHP What so ever.
You can check your SMTP Servers limitations to see how many you can actually attach the the email.
using bin carbon copies will not really save you that much resources as the SMTP Server Still has to send an email to all attached recipients, this being said the only thing BCC Does for you is hide the email addresses in each email dispatched.
BCC is, lets say, hidden recipients. So if you'll add recipients to BCC users will receive your message, but their emails will not be displayed in "to" or "copy" list.
Max count of BCC recipients depends on mail server.
Well, this only works if you send the exactly same message with no personal/individual information in it, like all would receive this same message:
hello world
and not
Dear Mr. XY
or
Dear Ms. AB

Safe way to send mail via PHP to many users

Let me explain what I mean in my title. Let's say, that for example I'm creating a small e-commerce system for one web shop/catalog. There's a possibility for customers to choose, do they wish to receive newsletters or not. If they do, then logically thinking the newsletters should be send immediately as the newsletter is formed and ready.
Of course it can be done simple by fetching all specified user e-mails from database and using for cycle to send mail via mail function in loop, but problem is that I was told, that this is bad practice. The simple and not cheap way would be purchasing internet service for sending newsletters, but what for the php programmer is needed, then?
So I ask you humble comrades, what from your point of view might be a solution?
NB! You probably won't believe me, but it is not for spamming.
UPD: I might have explained myself wrong, but I would like to hear a solution not only about the correct way to send mail, but also about the correct delivery. Since not every mail send is always delivered.
Of course there are some reasons, which are unpredictable. For example someplace along the way something broke and mail was lost (if such thing is possible), but there are also other reasons which are influenced maybe from server or elsewhere. Maybe there is need to talk with hoster about it?
There is no reason why you couldn't write it in PHP, although I would not make it a part of a webrequest / HTTP process. I've successfully implemented for give or take 500,000 subscribers per mailing (depending on local data available, as this was a location-specific project). It was an in-house project, so unfortunately no code/package for you, but some pointers I came across:
Setting up delivery
Started out with phpmailer itself, to take care of formatting, encoding of contents and headers, adding of attachments etc. That portion of it works well, and I wouldn't want to write that from scratch.
The 'sending' of an email itself is just setting some flag in a database whether / how / what should be sent to (a portion of) the subscribers.
After this flag is set, it will automatically be picked up by a cronjob, no more webserver involved.
I started out with a heavily polluted database with millions of email addresses, of which a lot were obvious not valid, so first thing was to validate all email addresses for format, then for host:
filter_var($email, FILTER_VALIDATE_EMAIL); over the subscribers (and storing the result obviously) got rid of the first few hundred thousand invalid emails.
Splitting out the host (and storing the host name) from the emails, and validating that (does it have an MX or at least an A record in DNS, but keep in mind: you can send email to an IP-address foo#[255.255.255.255], so do keep those valid)) got rid of a good portion more. The emailaddresses here are not permanently disabled, but with a status flag that indicates they're disabled because of the domain name / ip.
Scripts were changed to require valid emailaddresses on subscription / before insertion, this nonsense of 'you aint gonna get it#anywhere' subscription-pollution in the database was just ridiculous.
Now I ended up with a list of email addresses that had the potential of being valid. There are in essence 3 ways to detect invalid addresses (keep in mind, the all can be temporary):
They are denied immediately by the server.
The earlier determined server just doesn't listen to traffic.
They are bounced long after you thought you delivered them.
Strange thing, the bounces, which every emailserver seems to have another format forand were a hell to parse at first, ended up actually pretty easy to capture using VERP. Rather then parsing whole emails, a dedicated email address (let's call it mailer#example.com) was configured to rather then deliver to mailbox, to pipe it through a command, and if we sent email to user#server.tld, the Return-Path was set for mailer+user=server.tld#example.com. Easily parsed on receipt, and after how many bounces (mailbox could not exist, mailbox may be full (yes, still!), etc.) you declare an emailaddress unusable is up to you.
Now, the direct denial by the server. Probably we could have gone with properly configuring some MTA and/or writing plugins for those, but as the emails were time-sensitive, and we had to have absolute configurable control per mailing over last usable delivery time (after which the email was not longer of interest to the user), throttling per receiving server, and generally everything, it would take about the same time writing a mailer in PHP which we knew better, that used the SMTP protocol directly to socket 25 on receiving servers. With a minimum amount of effort the possibility of another transport then the default choices in PHPMailer was built-in. The SMTP protocol is actually quite simple, but there are some caveats:
A lot of receiving server apply Grey Listing: most spambots will not really care if a specific mail arrives, they just churn them out. So, if an unknown / not yet trusted sender send mail, it will be temporarily rejected. Catch that (usually code 451), and place the email in the queue for later retry.
A mailserver, especially of the larger ISP's and free services (gmail, hotmail/msn/live, etc.) will not stand for a torrent of mail without fighting back: after the first couple of hundred / thousand, they start rejecting you. More about that later.
Getting speed
Now, we had a delivery system that worked, but it needed to be fast. Sending a 10,000 emails in an hour is all fine if you only have 10,000 addresses to send to, but the minimum we required was about 200,000 per hour. Start of it was a dedicated server (which can actually be pretty low powered, no matter what you do, most of time taken in delivery of email is in the network, not on your server).
Caching of IP's: remember all those IP's we requested from hostnames in email addresses? We stored those obviously, and looking up their IP's again and again causes considerable lag. However, IPs may change: a DNS record there, another MX at another place... the data gets stale fast. Most of the time the server isn't actually sending anything (subscription newslettters come in bursts obviously), a low-priority cronjob is running checking all hostnames with a stale IP (we chose older then 1 day as being stale) for an IP address, including those which previously had none (new domains get registered all the time, so why shouldn't a domain become available the day after someone already enthusiastically subscribed with his/her brand new email address? Or server problems with some domain are solved, etc.). Actually sending the emails now required no more domain lookups.
Reuse of the SMTP connection: setting up a connection to a server takes relatively a large portion of the time to deliver an email when you're talking directly to port 25. You don't have to setup a new connection for every email, you can just send the next over the same connection. A bit of trail-and-error has resulted in setting the default here to about 50 emails per connection (assuming you have that many or more for the domain). However, on failure of an emailaddress closing and reopening the connection for a retry sometimes helped. All in all, this really helped to speed things along.
Some obvious one, so obvious I almost forgot to mention it: it would be a waste to have to create the body of the email on the spot: if it's a general mail, have the body ready (I altered PHPMailer somewhat to be able to use a cached email), possibly days before (if you know you're going to send a mail on Friday, and your server is idling, why not prepare them on Wednesday already? If it's personalized, you could still prepare it beforehand given enough time, if not, at least have the non-personalized portions waiting to go.
Multiple processes. Did I mention much of the time it takes to deliver email is spend on the network? One mailing process is not nearly getting the most from your emailserver, barely noticable load and the mails are trickling out. Play around with a number of processes mailing different portions of the queue to see what's right for your server/connection, but remember 2 very important things:
Different processes make you very vulnerable to race conditions: be freaking absolutely sure you have a fullproof system that will never send the same mail twice (thrice, of even more). Not only does it seriously annoy users, your spamrating goes up a notch.
Keep domains together where possible: randomly picking from the queue you will lose the advantage of keeping an open connection to the server receiving email for the domain.
Avoiding rejects
You're going to send a lot of mail. That's exactly what spammers do. However, you don't want to be seen as a spammer (after all, you aren't, are you)? There are a number of mechanisms in place which will thoroughly increase your trustworthiness to receiving servers:
Have a proper reverse DNS: processes checking the DNS belonging to the IP that is sending the email like it very much if the second level domains match: are you sending mail on behalf of example.com? Make sure your server's reverse DNS is something like somename.example.com.
Publish SPF records for your domain: explicitly indicate the machine used to send your bulk email is allowed & expected to send mail with that From / Return-Path headers.
remember rejects: servers don't like it to tell you again and again that different email addresses don't exist. Either automated mechanisms, and even human admins, blocked our server while we worked through all non-validated email addresses that did (no longer) exist. We didn't employ a double opt-in until later, so the database was polluted with typos, people switching IPs and thereby email address, prank email addresses and so on. Be sure to capture those invalids, and given enough or sever enough failures, unsubscribe them. They're doing you no good, they're hogging resources, and if they really want you mail and the mailbox becomes available later, they'll just have to resubscribe.
DKIM is another mechanism that may increase your trustworthiness, but as we haven't implemented it (yet), I cannot tell you much about that.
MX records: some servers still like it if your sending server is also the receiving server for the domain. As it was at the time, we had only 1 MX, and as the mailing server was still not that very busy, we dubbed it the fallback MX server for the domain. The normal MX server was not the server sending the subscriptions, as it is very irritating to be temporarily blocked by a server you're trying to send an important email to (clients etc.) because you already sent a load of less important mail. It does have the highest preference as receiving MX, but in the event it would fail we had the nice bonus that our subscription sending server would still be fallback for delivery, so in crisis we could still get to it, preventing awkward bounces to customers trying to reach us.
Tell them about you. Seriously. A lot of major players in free email addresses like live.com offer you the opportunity to sign up in some way, or have some point of contact to go to for help & support if your emails get rejected. I you have a legitimate reason to send so many emails, and it is believable you have that many subscribers, chances are they seriously up the number of emails you can send to their server per hour. A meager 1,000 may become somewhere in the ten-thousands or even higher if you are persuasive and honest enough. There may be contracts, requirements you have to fulfill, and promises you must make (and keep) to be allowed this. ISP's are a brand apart, and every other player is different. Don't bother calling them usually, because 99% of the time the only numbers you can find will only have people willing to troubleshoot your internet connection, which understand (or are allowed) little else. An abuse# email address is a good place to start, but see if you can delve up a more to-the-point email address up from somewhere. Be precise, honest and complete: roughly how many subscribers of you have an emailaddress with that ISP, how often are you trying to mail them, what are the errors or denials you receive, how is the subscribe & unscubscribe process like, and what is the service you actually provide to their customers. Also, be nice: how vital sending those mails may be to your business, panicking about it and claiming terrible losses does not concern them. A polite statement of facts and wishes, and asking whether they can help rather then demanding a solution goes a very long way.
Throttling: as much as you tried, some server will accept only a certain amount of mail per hour and/or day from you. Learn those numbers (we're logging successes & failures anyway), set them to a reasonable default for the normal domains, set them to agreed upon limits for bigger players.
Avoiding being tagged as spam
First rule: don't spam!
Second rule: ever! Not a 'once off', not a 'they haven't subscribed but this may be the deal of a lifetime to them', not with the best intentions, people have had to ask for your emails.
Obviously set up a correct double opt-in subscription mechanism.
PHPMailer does set proper headers on its own,
Set up an easy unsubscribe mechanism, by web (include a link to it in every mail), possibly also email and customerservice if you have it. Make sure the customerservice can unsubscribe people directly.
As said earlier: unsubscribe (excessive) fails & bounces.
Avoid spammy 'deal of a lifetime' wordings.
Use url's in your emails sparingly.
Avoid adding links to domains outside your control, unless you are absolutely sure you can trust them not to spam, if even then...
Provide value to the user: being tagged as spam by user-interaction in google/yahoo/live webmail clients seriously hurts future successes (on a site note: if you sign up for it, live/msn/hotmail will forward all mail to you send by your domain which is tagged as spam by users. Learn to love it, and as always: unsubscribe them, they clearly don't want your mall and are hurting your spam rating).
Monitor blacklists for your IP. If you appear on one of those, it's bye bye, so immidiate action in both clearing your name and determining the case is required.
Measuring success rate
With the whole process under your control, you are reasonably sure the email ended up somewhere (although it could be the MX's bitbucket or a spam folder), or you have logged a failure & the reason why. That takes care of the 'actually delivered' numbers.
Some people will try to convince you to add links to online images to your emails (either real or the famous 1x1 transparent gif) to measure how many people actually read your email. As a high percentage blocks those images, these numbers are shaky at best, and our believe is we just shouldn't bother with them, their numbers are utterly unreliable.
Your best bet for measuring actual success rate are a lot easier if you want the users to do something. Add parameters to links in the mail, so you can measure how many users arrive at the site you linked, whether they performed desired actions (watched a video, left a comment, purchased goods).
All in all, with all the logging, the user-interface, configurable settings per domain / email / user etc. It took us about 1,5 man-month to build & iron out the quirks. That may be quite an investment compared to outsourcing the emails, it may be not, it all depends on the volume & business itself.
Now, let the flaming begin that I was a fool to write an MTA in PHP, I for one thoroughly enjoyed it (which is one reason I wrote this huge amount of text), and the extremely versatile logging & settings capabilities, per-host alerts based on failure percentage etc. are making live oh so easy ;)
Using something like Swiftmailer, PHPmailer or Zend_mail are much better alternatives to using the simple mail() function as it can be easily marked as spam. There are simply too many issues with mailing that need to be considered - most of these are solved by using pre-existing libraries.
Just a few problems that need to be addressed when sending mass emails manually:
Using incorrect headers.
Processing bounced messages
Timing out of script due to an influx of emails.
Edit:
Probably not the answer you're looking for. But, I would strongly suggest you invest in something like Campaign Monitor or Mail Chimp. Since this process is not for educational purposes, but commercial, I would strongly suggest the above services.
I got your question, but before replying, let's me go to usual considerations. First, I strongly recommend using a service like Mail Chimp. It's kinda free for small jobs, and has many cool features, like tracking back how many emails were open, how many were clicked, how many failed on deliver... Think about make a favor to yourself and don't reinvent the wheel.
Now, for getting to know purpose, let's go to the reply to your question.
First thing to have in mind is to enforce your list to be a good one. How to do that? Well, for a good list, I mean a valid email addresses list. Simple put a newsletter form on your page, with just one field (maybe a captcha, but I don't think it is necessary).
Save all input to a database table, with a field "isValid" set as false by default, and any kind of unique hash. Then you send a confirmation email, with a link (with the hash generated) for confimation which when clicked will make the "isValid" flag true, and a link for cancelation (ALWAYS send this cancelation link within all your emails).
This is what stores and serious sites do. Anything that force your customers/visitors to receive is a bad moral practice (ie, spam).
Second thing, use a good hosting service. Too cheap services usually are used by spammers, and major email services blacklist everything coming from those addresses.
I know, you should be asking yourself if I get your question wrong. No, I don't, technical stuff comes now.
Why is a bad practice put a mail function inside a for loop? Simple. Because function mail do several operations everytime it is called. PHP, will open a connection to mail server, send data to be parsed, ask for sending, register mail server status, close connection, bubble up status to finish the mail function you called and clean up the memory mess.
This connection overhead is the problem people state as bad practice from programming point of view. Using a SMTP/IMAP solution is better because it optimizes this process.
A little bit down on tech stuff I see your questions about delivery. Well, as I said, you have some ways to ensure you emails list is good enough. But what if another exception occurs, like having a blackout + no-break failures on customer server?
Well, PHP keeps the status of "asking mail server to send, mail server sent". If the mail server sent your message, PHP will return true. Period.
If client was unable to receive, or reject, you should check email headers and email status. These are on email server. Once again, these informations can be accessed with SMTP/POP/IMAP extensions, not with mail function.
If you wanna go further, read IMAP docs, search for email classes (phpclasses.org, pear and pecl are best places to look into).
Extra tip: RFCs can be useful, as you can understand better what email servers really talks to each other.
Extra tip 2: Access you gmail or ymail and check for your sent/received messages for their "full version" and read its headers. You can learn a lot with them.
Via SMTP Authentication: http://www.cyberciti.biz/tips/howto-php-send-email-via-smtp-authentication.html
Just use PHP Mail and study IMF and how to build custom headers you can attach the fourth parameter, exmaple follows
<?php
// multiple recipients
$to = 'aidan#example.com' . ', '; // note the comma
$to .= 'wez#example.com';
// subject
$subject = 'Birthday Reminders for August';
// message
$message = '
<html>
...
</html>
';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To: Mary <mary#example.com>, Kelly <kelly#example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday#example.com>' . "\r\n";
$headers .= 'Cc: birthdayarchive#example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck#example.com' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
?>
Source: http://php.net/manual/en/function.mail.php
create a mail queue subsystem which might include tables such as mail_queue, mail_status, mail_attachments, mail_recipients and mail_templates etc...
You might consider PHPMailer
http://phpmailer.worxware.com/index.php?pg=exampleasendmail
You can add multiple recipients and a special callback function for handling the returning messages for every single mail sent. (for an example visit the link)
I Don't think that catching a "mail delivery failed" error mail is possible via php except that you are using PHPMailer via SMTP and once in a while watch for any returning message form any recipient in from your outgoing email collection.

How should I send emails to a long list? (PHP)

I figure I can either use one mail() command with a large Bcc list or have a loop that sends many individual emails.
I was just going to use Bcc since that is easiest to program and seemed easiest for the server to handle, but then I have to choose some address for the To field. I can just send mail to the websites own address but it would look more sensible to recipients if it was addressed to them. Also, it would be nice to customize each message by saying "Hello [firstname]" at the beginning.
I'm just concerned that sending to too many people will take too long. The maximum number of recipients will be 2000. Users on the website choose a list of people to send to, type a message, and press Send. Would they be waiting forever if it was sending to 2000 people? Would the server choke?
Also what considerations are there regarding mail servers thinking of this as spam?
EDIT: Apparently my client has an SMTP server he says can throttle the outgoing emails. Still not sure though if the PHP would be slow when sending to 1000+ people...
Sending large number of emails at once can really bog down your server, or if its a shared hosting, there is a limit to the number of emails that can be sent over an hour (with bluehost its 700 per hour). So i would recommend you to send emails in chunk.
Create table email_queue with two fields email_to and email_content. Now whenever you wish to send an email, just insert a record into this table with the email address that you wish to send the email to stored in the email_to column and the raw email content in the email_content column.
Next you would create a cron job that runs every hour, that cron job would check the email_queue table to see if it has to send any email, it will pick up 100 records from the email_queue table and send those 100 emails, when the emails have been send those 100 records would be deleted.
This I think would be an ideal way to send out emails in large numbers.
It's a pretty complex subject with respect to making sure the emails don't start looking like spam. You can really do yourself some favours by hooking it up to something like MailChimp.com and letting them deal with the nasty details for you.
I would actually recommend looking at a third party that can be accessed by an API. Mailing out large numbers of e-mails can be detrimental to your server as it can end up black listed. Check out a company like www.postmark.com or something similar that will throttle your message queue, manage white listed servers, etc.

Sending bulk email in PHP

I want to send mail to hundreds of email addresses in PHP using php mail function.
How can I do that?
You can also use SwiftMailer
Please also look at a similar post here
You can try phplist
It will be a better option
I wouldn't try writing your own bulk mailer, unless you have a lot of time. There is allot of issues to cover including throttling emails, sending emails out into small batches so AOL and other service providers don't consider your server as SPAMMING people. Also you want to probably include tracking for opened emails, track bounced emails, clicked links, etc.
I would look at some open source options such as www.phplist.com which is a very good open source program for doing bulk emails.
Or on the commercial side take a look at Interspire Email Markerer, it's a very slick product and well worth the money, plus you can host it on your own servers.
www.interspire.com/emailmarketer/
You must use PHP? If so, I'd use PHPMailer, I have a bit of experience with it and it hasn't failed me for bulk email sending.
Alternatively, if you have access to the server, look at using Postfix or Sendmail, they are better options for that quantity of mail.
If you're sending a lot of mail, you don't want to do it all # once or else you will consume too many resources.
Here is a Tutorial on how to use the Mail_Queue component of the PEAR library: http://pear.php.net/manual/en/package.mail.mail-queue.mail-queue.tutorial.php
It basically will incrementally send segments of your email blast without throttling your server.
Use PHPMailer library, it has a lot of functionality. Store the email addresses as an array and using for loop just keep adding each email address as a string to the mail->AddAddress field. It will take care of sending the bulk mail. I have only used this to send bulk mails to 6/7 addresses at a time. It should also work for hundreds of addresses.
You can use swiftmailer for it. By using batch process.
<?php
$message = Swift_Message::newInstance()
->setSubject('Let\'s get together today.')
->setFrom(array('myfrom#domain.com' => 'From Me'))
->setBody('Here is the message itself')
->addPart('<b>Test message being sent!!</b>', 'text/html')
;
$data = mysql_query('SELECT first, last, email FROM users WHERE is_active=1') or die(mysql_error());
while($row = mysql_fetch_assoc($data))
{
$message->addTo($row['email'], $row['first'] . ' ' . $row['last']);
}
$message->batchSend();
?>

Categories