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/
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.
Okay, so here's my problem:
I have a list of members on a website, and periodically one of the admins my site (who are not very web or tech savvy) will send a newsletter to the memberlist.
My current memberlist is well over 800 individuals long.
So, I wrote an email script that sends the email to the full memberlist, with the members listed in the Bcc header.
However, I've discovered that my host server has a limit of 300 emails per hour, which I apparently exceed even though the members are listed in the Bcc field. (I wasn't previously aware that the behaviour of Bcc was to send separate emails for each name on the list...)
After some thought, I've come to the conclusion that my only solution is to have my script send only the email to only the first 300 emails, wait an hour, and send a second email to the next three hundred, wait another hour, and so on until I've sent the email to the whole member list.
Looking around on the internet, I've seen some other solutions people have come up with for delaying emails in PHP. Sleep() is obviously not an option, because I can't just leave the script open and running for 3 or four hours. I've seen some people suggest cron jobs, but I'm not sure how feasible it would be to create three new cron jobs every time I send an email, use them once, and then delete them afterward.
The final (and what I think is the smartest) solution I've seen, is to have a table in my database to temporarily store the emails to be delayed and sent later, and then create a cron job that checks this sql table every hour or so, compares the timestamp of the row to the current timestamp, and then sends the email if an hour has passed.
So I'm asking you all which method you would recommend. Is there an easier solution that I've completely looked over (aside from getting a different hosting plan. ha!), or is there a cleaner way to do it than the database / cron job approach?
tl;dr: I have >800 emails to send in an hour on a server that limits me to 300/hr. Using PHP, find a way to get around this problem in a way that the person sending the email needs only to click "send."
You could send this into a gearman queue and then have a gearman worker with the appropriate sleep calls. See http://gearman.org/ and http://php.net/gearman
Sounds like you need to setup a batching function that pulls from a pool of messages to be sent and processes X everytime its run during cron. Then you would have a table that tracks messages that were sent and to who, so you can keep track of who has received emails.
I would recommend that you create a queue, and process X number of items from the queue each time you need to send email. The sender of the messages just places the email in the queue and your processing code picks up the item sending the maximum number of items in that period. Occasionally you will have failures and use of the queue will allow simple recovery. You only remove items from the queue when they are processed.
You can use a simple database table to act as the queue but you may prefer to use a specialist queuing solution.
Another recommendation would be to look into external email services like Strongmail. These will help you send more email per hour.
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.