Requirement:我需要存储关于某些人生日的信息,并在每个生日向所有人发送邮件。
我做了以下工作:
编写了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" 第二个脚本中的第一个语句:导入电子邮件是包含电子邮件代码的python文件的名称。因此,每当我运行上述脚本时,每天都会发送电子邮件,而不考虑生日,因为我在其中导入了电子邮件python文件。
1.)我希望它只在生日时发送电子邮件,而不是在其他日子发送。
2.)在我的html代码中,我希望根据生日的不同来更改名称。例句:在谢林的生日那天,它应该送上生日快乐
3.)在我的第一个代码中,我试图从Gmail帐户发送电子邮件。所以,我用:
mail = smtplib.SMTP('smtp.gmail.com', 587) 但是,如果我必须从公司邮寄呢?
发布于 2016-12-16 15:56:02
您还需要为每个人发送到不同的电子邮件地址。如果没有重复的名称,您可以使用单独的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详细信息。
https://stackoverflow.com/questions/41187896
复制相似问题