【问题标题】:Sending mail using python on specific days在特定日期使用 python 发送邮件
【发布时间】:2016-12-16 23:56:02
【问题描述】:

要求:我需要存储某些人的生日信息,并在每个生日时向所有人发送邮件。

我做了以下事情:

编写了 python 脚本将 html 文件发送给所有人。内容如下:

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

me = "hunter@gmail.com"
you = "prudhvi@gmail.com"

msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

html = """\ 
<html>
<body>

<b>HAPPY BIRTHDAY SHERLYN<br></b>

</body>
</html>
"""

part = MIMEText(html, 'html')

msg.attach(part)

mail = smtplib.SMTP('smtp.gmail.com', 587)

mail.ehlo()

mail.starttls()

mail.login('username', 'password')
mail.sendmail(me, you, msg.as_string())
mail.quit()

还编写了以下脚本来打印特定日期的生日男孩的名字:

import email
import datetime
now = datetime.datetime.now()
a = now.strftime("%d-%B")

birthdays = {
             '09-December': ['BOB'],
             '10-December': ['JOHN'],
             '16-December': ['SHERLYN'],

            } 

today_birthdays = birthdays.get(a)

if today_birthdays:
    for person in today_birthdays:
        print "Happy Birthday %s!" % person
else:
    print "No Birthday today"       

第二个脚本中的第一条语句:import email 是包含电子邮件代码的 python 文件的名称。因此,每当我运行上述脚本时,每天都会发送电子邮件[不考虑生日],因为我在其中导入了电子邮件 python 文件。

1.) 我希望它只在生日而不是其他日子发送电子邮件。

2.) 在我的 html 代码中,我希望根据生日更改名称。 Ex : 在Sherlyn 的生日,它应该发送Happy Birthday Sherlyn

3.) 在我的第一个代码中,我尝试从 Gmail 帐户发送电子邮件。 所以,我用了:

mail = smtplib.SMTP('smtp.gmail.com', 587)                       

但是,如果我必须通过公司邮件发送呢?

【问题讨论】:

    标签: python email


    【解决方案1】:

    您还需要为每个人发送到不同的电子邮件地址。假设没有重复的名称,您可以使用单独的 name: address 字典来做到这一点。

    1.) 在您的email.py 中,您应该将所有代码移到一个函数中,这样只有在您调用该函数时才会发送电子邮件。目前,所有代码都在该模块的全局范围内,因此它在您 import 它时执行,而不是在您要发送电子邮件时执行。您也可以考虑让函数将姓名和电子邮件地址作为参数:

    def send_email(name, address):
        # Skipped the rest of the contents, as they're the same... 
        # just the sending line:
        mail.sendmail(me, address, msg.as_string())
    

    然后从您的第二个脚本中,您将调用 email.send_email(person, address)

    2.) 您要查找的内容称为字符串格式化和.format 方法。对于这个,你可以这样做:

    html = """\ 
    <html>
    <body>
    
    <b>HAPPY BIRTHDAY {name}<br></b>
    
    </body>
    </html>
    """
    

    然后填写:

    html.format(name="Sherlyn")
    html.format(name="Bob")
    

    3.) 取决于您公司电子邮件的设置方式,您可能需要向您的服务台或帮助台询问 smtp 详细信息。

    【讨论】:

    • 我已经按照您的要求完成了。我通过这种方式收到电子邮件:生日快乐 {name}
    • 你在调用 format() 方法吗? part = MIMEText(html.format(name=name), 'html') 或类似的东西?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    相关资源
    最近更新 更多