tags:

views:

59

answers:

2

I want to send out some batch e-mails using php. I have done so in the past with a foreach loop within which I use the php mail() function. However, when there are a lot of e-mails to send out, this often gets backed up and crashes the server. How can I do this without overwhelming the system?

+3  A: 

Don't use the mail() function for mass e-mail sending. (I think it's even stated in the manual.) The function opens a new smtp connection per mail, which is highly ineffective. Better use an SMTP client, which can reuse the same connection for all your emails.

You'll find lots of libraries on google. The first result for me is a whole MTA, which might be interesting, because you can do much more accurate stats with that. If you're not feeling like experimenting, you can always use PEAR classes, Mail is what you need.

Edit: Just checked the manual. There's a note on mass e-mailing:

It is worth noting that the mail() function is not suitable for larger volumes of email in a loop. This function opens and closes an SMTP socket for each email, which is not very efficient.

For the sending of large amounts of email, see the » PEAR::Mail, and » PEAR::Mail_Queue packages.

svens
For me, the standout PHP email library is [Swiftmailer](http://swiftmailer.org/), which I find far more intuitive and powerful than PEAR::Mail.
lonesomeday
A: 

It depends what you are sending. If you are sending out newsletter or something of the like, I would look into a service like Sendgrid or Mailchimp.

If you are sending other kind of email, I would recommend using a Messaging Queue and create 1 job per email you need to send and let the workers connected to your messaing queue do the work.

That way, if you got tons of emails to send, you can just add more workers to empty your mail queue faster. A few Message Queue solution you might want to look into are beanstalkd, RabbitMQ, Resque (It has been ported to PHP).

philhq