【问题标题】:Allowing users to manage frequency of emails? - Python Bulk Mailer允许用户管理电子邮件的频率? - Python 批量邮件程序
【发布时间】:2021-10-16 06:58:09
【问题描述】:

我的任务是在 python 中创建一个批量邮件程序,它将批量电子邮件内容发送到订阅者列表 - 我将如何输入代码以允许订阅者管理他们收到的电子邮件的频率和内容?

import pandas as pd
import smtplib

# reading excel email list + retrieving the values
e = pd.read_excel(r"C:\Users\****\OneDrive\Desktop\emailList.xlsx")
email = e['Email'].values

# setting up server to send mail
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login("bulkmailer****@gmail.com", "*****")
msg = "Hi there! Check out these exclusive offers tailored just for you!"
subject = "Exclusive Offers Inside"
body = "Subject : {}\n\n{}".format(subject, msg)

# for loop for server to send emails from server to email list
for email in email:
    server.sendmail("bulkmailer****@gmail.com", email, body)
server.quit()

【问题讨论】:

  • 请记住,您可能不想自己执行此操作:请参阅 stackoverflow.com/questions/3905734/…
  • 我不需要创建一个这么大的批量邮件 - 我只需要它能够发送到 2-3 封电子邮件,因为这只是一个单一的任务

标签: python smtp smtplib


【解决方案1】:

您提供的代码具有向您的每个订阅者发送一条消息的效果。要拥有任何“频率”,你需要偶尔运行这个程序——例如,你可以设置一个cron job(或 Windows 等价物),它每 X 次执行一次——比如说,每分钟一次.

这是否意味着您的订阅者每分钟会收到一次垃圾邮件?除非我们添加其他内容:一种记录消息发送时间的方法,或者等效地,记录下一条消息的到期时间。

具体来说,与每个地址一起,您需要存储: 您这次要发送给他们的消息内容;您打算发送消息的时间间隔;以及我们上次向该地址发送消息的时间。

为此,普通应用程序使用数据库。您正在使用 Pandas Dataframes,它可能具有足够的功能,但它们肯定更难用于此目的。既然你在cmets里说了this is a homework question,也因为我没有Pandas的经验,所以我会提供一些类似ORM的伪代码。

from dataclasses import dataclass
import database
import time
import mailer

@dataclass
class DatabaseRow:
    """ Single row in database of email addresses and associated data """
    email: str  # email address to send message to
    subject: str  # message subject
    body: str  # message body
    send_interval: int  # or float -- number of seconds between each message
    next_send_at: Optional[int]  # int or None (or float or None); Unix time at which to send next message; if None, send immediately

for row in database.get_all_rows():
    current_time = time.time()  # this returns Unix time: the number of seconds since 1 Jan 1970
    if row.next_send_at is None or current_time < row.next_send_at: 
        # it is not time to send it to them yet; don't do anything
        continue
    mailer.send(row.address, row.subject, row.body)
    row.next_send_at = current_time + row.send_interval  # the next time we'll send a message is (send_interval) away from now
    row.save()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    • 1970-01-01
    相关资源
    最近更新 更多