What is the most proper way to sending email of minimal 1000 or more in PHP? Any reliable email queuing technique that is capable to handle that?
You could just insert your emails into a Mail Queue database table, and have a separate process check the queue and batch send a certain number at once.
There's a tested solution for that: PEAR Mail_Queue
Works fine for me.
as mercutio suggested, i would insert a new record into a mail queue table for each email waiting to be sent and then use a separate process (like a CRON) to check the table periodically for any queued items.
if any emails are queued (and the email is not customised for each recipient) i would then group the emails by domain and send blocks together to reduce the total number of emails that have to be sent, i.e. if you have 1000 emails queued and 250 are to gmail accounts i would send the 250 in 25 blocks of 10 (remember to Bcc recipients to avoid them seeing each other).
to actually send the mail i would use PEAR mail over php's mail() function
after sending the email either delete record(s) from the queue or change a status flag to show it was sent and loop - i would also add a counter to keep track of emails that failed to send and remove them after x failed attempts
to overcome timeout issues i would either,(depending on the situation)
- set the set_time_limit() to x seconds and keep track of the script execution time (killing the script after (x-1) seconds)
- call the script from the command line to avoid timeouts
- set a limit to the number of emails the script could send in one execution
Sure, the database table might be an idea. But what about sending 1000 e-mails with a 2mb attachment? you'd have to take that into account as well. I had the problem myself, and I eventually resorted to writing the e-mail to the database, and the files to the filesystem. The e-mail script I used then read the database records, and tried to fetch the attachments to send.
Are you sure you need do this mail queuing yourself?
Just deliver all mail to the local machine's mail transfer agent (sendmail...) and let that take care of the queuing and sending. After all, that's what was designed for.
In other words: don't worry about it!
I created Emailqueue, which is a server that allows you to add emails to a queue so your app get relieved of the stress of the mailing, and also provides useful additional options, like the ability to program emails to be sent in the future, or setting per-email sending priorities. I think this might very well be what you're searching for.
Emailqueue is available here: https://github.com/tin-cat/emailqueue
And there is also a Docker version that allows you to set up a working Emailqueue server in just a few minutes, here: https://github.com/tin-cat/emailqueue-docker
I've generally relied on a hack.
I have a database list of email addresses and then use a meta-redirect to self with an increasing 'offset' parameter that specifies which row in the database I am up to. Server redirects cause problems because browsers assume that the time taken indicates an infinite loop.
Related
I have a big amount of users that agreed to recive daily newsletter. Content of newsletter is being auto-generated, so the only thing to do is to set up a cron job which would send e-mails.
However, if there is e.g. 10.000 users, such cron job would kill my server. What can be done to solve this problem?
Is sleep(1) after sending 100 e-mails enough? (and of course setting execution time limit to 1 day)
Have a look into http://php.net/manual/en/function.mail.php
Note:
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.
So simply use the Mail_Queue package... which takes every mail and then simply works through them.
I have made a system for sending emails for project few months ago so I done the following:
In database, I have 3 tables:
users
user_emails (some users have multiple emails)
email_campaign (this is table in which I store data temporary while sending campaign and on finish I truncate everything in it)
And when I start sending campaign I insert row in email_campaign table for every user that I finished sending email to.
This way if error occur before campaign finishes, I know where to continue and know to whom I sent email and to who need to send email.
Practicaly I was able to send 45.000 emails during 2 hours. Without server overload.
I use sleep() on every 100 emails like you wanted to do.
Also I send campaigns at 2 am in the morning when my server load is the lowest.
You could also configure your email server to send limited ammount of emails per hour.
This would slow sending but it will reduce server load.
I have created a Job Queue module that processes jobs and constructs "social-network" type emails.
2 processes consists of:
Building the custom emails (Views) e.g. User A and User B have commented on your post or User B and User C also likes User C's post. Each recipient gets a different email. I initially created a new Swiftmailer instance and add the message content, subject and recipient. I then added these instances to the database.
A cron job runs to fetch and send these emails at a later time.
While benchmarking, I realised it was sending out 2 emails per second avg. So I tried storing Swift_Message Instances in the database instead. No luck though, still takes as long.
Currently, the code
Creates a new Swift_SmtpTransport.
Creates a new Swift_Mailer instance.
Loops through the Swift_Message messages retrieved from the DB
Sends each email.
But it still averages about 2 emails a second. Is there any way I can improve on the process to speed up delivery? I am using Amazon SES as my SMTP transport and I know it can at least handle 5 emails a second.
So it is probably something I am doing wrong. Any thoughts appreciated.
EDIT
Please keep in mind that the messages differ for each recipient. I could try out the Swift_Decorator plugin but it will mean that I will have to change the way the views are generated. I am just looking out for other alternatives to speed the process up.
I am using Amazon SES as my SMTP transport
In my experience using SES, the minimum API response time I've seen has been in the half second range, while the average hovered around one second. This is not a limitation of the connection, of TCP/IP, of bandwidth available, etc, but of their processing of requests per connection. Others on the official support forums report the same. The SMTP transport isn't any faster.
The only way to send faster is to send in parallel. This is the approach they've been recommending on their official support forums.
The SES API permits multiple simultaneous connections as long as you stay under the "mails per second" quota. If you don't know your current per-second quota, check your send stats. I don't know the SMTP transport handles being over this limitation.
In order to send a higher volume of mail in parallel, we modified our queue processor to be able to run in parallel. To ensure that mails were never sent twice, we added an "PID x grabbed this" column to the table and ran a query similar to UPDATE Queue SET selected_pid = ? WHERE target_ts < NOW() AND selected_pid IS NULL LIMIT X. We'd then look for mails we can send, send them all, and then try again until we ran out of mails that we'd need to send in that period.
We also modified the code that populates the queue to ensure that there would never be more mails in the queue than we could send. We were able to do this because we send mails in batches. When you have a constant trickle of mails, chances are that you won't need to jump through that hoop. Just make sure your sending code knows how to properly respond to the various over-quota errors.
As an alternate to a cron-based queue processor, consider using Gearman to set up a set of asynchronous background workers to send mail.
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.
I have created a newsletter system and my question is: How should i write my code considering that i have to send that mail to hundreds of email addresses?
I've discussed with my host administrator and he told me that i should send my emails one by one but not more than 6 per minute.
Can i use the $Timeout property? If so, how?
Thanks.
If you have to send out the mails one by one (instead of using BCC), I'd use a database-queue to respect the limit of sending out only 6 mails per minute (no matter what solution you'll finally use to actually send the mails).
E.g. you'd have a database-table containing recipient, subject, mailbody, lastsenddate, timessent and status.
Save all mails, you will send out, to the database and then set up a cronjob that will run once a minute and check if there are still mails in the queue waiting to be send (e.g. status = "unsend"). Then you'd pick a maximum of 6 (or whatever your limit is) mails from the queue, send them out, set the status to "send" (and increase "timessent" and set "lastsenddate" to the actual time, if you like) and wait for the next cronjob until all mails are sent.
This way you have several advantages:
you can respect your per-minute-limit
you have all your mails in a database and can relate to them later (e.g. to find out how many mails - and which ones - you sent last Friday or to find out whether a certain address has been processed - and when and how many times - if someone claims he never received a mail / or too many)
by tracking a mail-status you could implement a bounce-handler that'll e.g. set a mail-status to "bounced" if a mail returns, so you could start a resend of your mailing some time later to reach addresses that returned a "mailbox full"-message the first time
by saving your mails to a database, you could even setup a "deferred mail service" by adding a database-field "starttime" and make your send-script respect this date, so you could already queue your Christmas-mails in spring :)
Pear Mail will allow you to send email from PHP to allot of people.
http://pear.php.net/package/Mail/
I have to made a page which will send Email to Newsletter subscribers. There is more then 14000 subscriber. I want to use php mail() function to send Email to them. But I'm afraid that it will not be able to send email to all subscribers for php 30sec max_execution_time limit. Its not possible to test how much Email can be sent by sending Test Email to subscribers. So I want to know how much Email can be sent with mail() function in 30 second max_execution_time limit.
Will be very helpful if you can answer me.
also another question - Is mysql execution time is also count in php?
Apache version 2.2.13 (Unix)
PHP version 5.2.11
The php max_execution_time setting is customizable. 30 seconds is the default but you can set it to 0 seconds for no execution time limit at all. Use set_time_limit().
set_time_limit(0);
If you do this, you should be able to send all your email.
Please be careful about sending more than one email to the same mail server per second. You don't want to get blacklisted.
You should run this from a cronjob or spawn a background task or use something else better suited to batch jobs.
You might get 14000 emails out in 30sec if your mailserver is fast enough, but what happens when you get a few more subscribers and it stops working properly?
Perhaps you can set a flag in the database for each user, then reset the flag as their email is sent by a background task. That will help to avoid duplicates and so on if there is a problem with the mail server.
That depends on so many variables that a single answer is not possible. Factors include:
The speed of the CPU
The bandwidth available from the sending system to the MTA
The MTA's capacity to accept emails
The only way to find out is to try it.
I had this exact problem a while back on one of my projects. The solution is to isolate the email sending from the actual site.
I coded a small class that would be called to send an email. It would be passed a templated email, which it would then store into the database in a mail queue. On the back end, I had a cron job that called a mailer script every X seconds. Script looks at the database queue for emails, grabs X number from the queue to attempt to send (ordered by timestamp in), then would attempt delivery. Assuming no errors were thrown, script would mark the message as sent. Next step would be to purge all emails from the queue that were sent and older than X days (kept for logging).
Hope that is helpful.
Seriously, if you want to send the same mail to ten people from your normal mailapp, do you normally create ten identical mails or do you just send the mail once adding the recipients to the send list?
Edit: If the answer is "I send it once", I think you should look in that direction here as well (it is even described how to send to multiple recipients at http://www.php.net/mail)