Safe way to send mail via PHP to many users

Eugene picture Eugene · Sep 29, 2010 · Viewed 9.2k times · Source

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?

Answer

Wrikken picture Wrikken · Oct 5, 2010

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 [email protected]) was configured to rather then deliver to mailbox, to pipe it through a command, and if we sent email to [email protected], the Return-Path was set for [email protected]. 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 ;)