How to use php mail() function without crashing the server?
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 开发者_JAVA百科server. How can I do this without overwhelming the system?
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.
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).
精彩评论