简体   繁体   English

使用python限制电子邮件的速率

[英]limiting the rate of emails using python

I have a python script which reads email addresses from a database for a particular date, example today, and sends out an email message to them one by one. 我有一个python脚本,该脚本从特定日期(例如今天)的数据库中读取电子邮件地址,并向其发送一封电子邮件。 It reads data from MySQL using the MySQLdb module and stores all results in a dictionary and sends out emails using : 它使用MySQLdb模块从MySQL读取数据,并将所有结果存储在字典中,并使用以下命令发送电子邮件:

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. 但是,我的托管服务仅允许我每小时发送500封电子邮件。 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. 如何限制我的脚本,以确保在一个小时内只发送500封电子邮件,然后检查数据库是否保留了今天的电子邮件,然后在下一个小时发送。

The script is activated using a cron job. 该脚本是使用cron作业激活的。

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. (例如,通过删除电子邮件地址,设置标志或其他方式?)。如果是这样,您可以在SQL查询中添加LIMIT 500 ,然后每小时运行一次Python脚本。

我将使用cron使脚本每小时运行一次,并使用fetchmany而不是fetchall ,将您从数据库中获取的记录数限制为大约490条(为了安全起见)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM