我正在使用此帖Sending Email Using Python
中的信息到目前为止,说明书都很完美。我还有两件事我想做:
变量将是今天的日期。就是这样:
today = datetime.datetime.today ()
tday = today.strftime ("%m-%d-%Y")
我知道使用mailx,您可以使用-a选项附加。
答案 0 :(得分:6)
要调用html体内的变量,只需将它们转换为字符串以在体内连接它们
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'))
答案 1 :(得分:0)
关于第一个问题:有很多方法可以创建使用变量的字符串。
有些方法是:
body = "blablabla " + tday + " bloo bloo bloo"
body = "Today's date is {}, in case you wondered".format(tday)
对于您的第二个问题,您必须告诉我们您正在使用哪个库/模块,然后您可以访问该模块的文档页面,看看是否有某些内容用于添加附件。
答案 2 :(得分:0)
感谢所有人发布提示。
对后人来说,这是工作脚本。
唯一剩下的项目是我需要能够向多人发送相同的电子邮件。
我尝试在逗号之间添加所有电子邮件地址,但是他们没有得到它。当我查看收到的电子邮件时,它们似乎位于“收件人”行中。它是否可能只发送到列出的第一个电子邮件地址?
#!/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()