#!/usr/bin/python
import smtplib
import time
import datetime
from datetime import date
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email import encoders
fromaddr = "NOREPLY@test.com"
toaddr = ['me@test.com', 'thatguy@test.com']
# Date
today = datetime.datetime.today ()
tday = today.strftime ("%m-%d-%Y")
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = ", ".join(toaddr)
msg['Subject'] = "My Subject Goes Here"
body = """\
<html>
<head></head>
<body>
<p>DO NOT REPLY TO THIS EMAIL!!<br>
<br>
Script run for data as of """ + tday + """.<br>
<br>
See attachment for items to discuss<br>
<br>
The files have also been uploaded to <a href="http://testing.com/getit">SharePoint</a><br>
<br>
If you have any issues, email admin@test.com<br>
<br>
</p>
</body>
</html>
"""
msg.attach(MIMEText(body, 'html'))
filename = "discuss.csv"
attachment = open("discuss.csv", "rb")
part = MIMEBase('application', 'octet-stream')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)
msg.attach(part)
server = smtplib.SMTP('localhost')
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()
from datetime import datetime
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
today = datetime.today ()
tday = today.strftime ("%m-%d-%Y")
# email subject, from , to will be defined here
msg = MIMEMultipart()
html = """\
<html>
<head></head>
<body>
<p>Hi!<br>
How are you?<br>
""" +str(today)+ """ and """ +str(tday)+ """
</p>
</body>
</html>
"""
msg.attach(MIMEText(html, 'html'))
对于第一个问题:有很多方法可以创建使用变量的字符串。
一些方法是:
对于第二个问题,您必须告诉我们您正在使用哪个库/模块,然后您可以转到该模块的文档页面,查看是否有添加附件的内容。
感谢大家贴出贴士。
对于后人来说,这就是工作脚本。
剩下的唯一一项是我需要能够发送相同的电子邮件给多个人。
我试图将所有电子邮件地址都添加到变量中,变量之间用逗号隔开,但他们没有收到。当我看到收到的电子邮件时,它们似乎在“收件人”行中。它可能只发送到列出的第一个电子邮件地址吗?
要调用html正文中的变量,只需将它们转换为字符串将它们连接到正文中
有关附件,请查看http://naelshiab.com/tutorial-send-email-python/
编辑: 上面提供的链接似乎不可用,因此通过电子邮件(特别是从gmail)发送附件的代码片段如下
注意:Google有时会阻止其他应用程序(不太安全的应用程序)的登录,因此需要在Google帐户设置中允许此访问 https://myaccount.google.com/u/1/lesssecureapps?pli=1&pageId=none
相关问题 更多 >
编程相关推荐