limiting the rate of emails using python
I have a python script which reads email addresses from a database for a particular date, exa开发者_StackOverflow中文版mple today, and sends out an email message to them one by one. It reads data from MySQL using the MySQLdb module and stores all results in a dictionary and sends out emails using :
rows = cursor.fetchall () #All email addresses returned that are supposed to go out on todays date.
for row is rows: #send email
However, my hosting service only lets me send out 500 emails per hour. How can I limit my script from making sure only 500 emails are sent in an hour and then to check the database if more emails are left for today or not and then to send them in the next hour.
The script is activated using a cron job.
If you don't mind if the script is running for hours on end, you can just pause for a few seconds between each email.
from time import sleep
if address_count < 500:
sleep_time = 0
else:
sleep_time = 7.5
for address in addresses:
send_message(address)
sleep(sleep_time)
(Note: This was written for maximum clarity, not maximum efficiency)
When you send an email, do you record it in the database in some way so that the same email address wouldn't be returned by another query in the same day? (say, by removing the email address, or setting a flag, or something?) If so, you could just add a LIMIT 500
to your SQL query and run the Python script every hour.
I would have the script run hourly using cron and limit the number of records that you take from the database to about 490 (just to be on the safe side) by using fetchmany
instead of fetchall
.
精彩评论