我刚刚开始学习Python,而我正在尝试编写一个机器人,它通过电子邮件发送HTML消息以及.docx(Microsoft Word)附件。这是我的代码,它工作正常,但我对一些参数感到困惑。
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import os
#Email Variables
myemail = "myemail@hotmail.com"
recipient = "recipientemail@hotmail.com"
#Specifying MIME variables to include in email header
mime_details = MIMEMultipart('mixed')
mime_details['Subject'] = "This is my email subject!"
mime_details['From'] = myemail
mime_details['To'] = recipient
#Creating body of message
html_body = """\
<html>\
<p>\
My email message!
</p>\
</html>\
"""
#Attaching File To Email
os.chdir('C:\\Users\Kyle\Desktop\')
openfile = open('testfile.docx', 'rb')
doc = MIMEApplication(openfile.read(), _subtype='vnd.openxmlformats-officedocument.wordprocessingml.document')
doc.add_header('Content-Disposition', 'attachment', filename='My Content.docx')
mime_details.attach(doc)
openfile.close()
#Recording MIME types of email parts
htmlpart = MIMEText(html_body, _subtype='html')
#Attaching parts to message container
mime_details.attach(htmlpart)
#Sending message via SMTP server
s = smtplib.SMTP(host='smtp.live.com', port=587)
s.ehlo()
s.starttls()
s.login(myemail, 'password')
s.sendmail(myemail, recipient, mime_details.as_string())
s.quit()
我对上面的代码有几个问题,如果你能帮我澄清一下我对上述模块的疑惑,我将不胜感激。
A)add_header模块
mime_details['Subject'] = "This is my email subject!"
mime_details['From'] = myemail
mime_details['To'] = recipient
从上面的代码片段中可以看出,我清楚地定义了MIMEMultipart包络中的每个标头变量。根据Python的文档,这些值将直接添加到标题中。我尝试直接使用add_header()方法作为替代方法,例如:
mime_details.add_header(Subject = "This is my email subject!", To = recipient, From = myemail)
但它给了我错误。知道为什么吗?
B)在我的代码的最后几行,我不得不将.as_string()附加到我发送的有效负载上。我尝试将它取出但它给了我一个 TypeError:期望的字符串或缓冲区。
Python文档给了我这个:
as_string(unixfrom = False,maxheaderlen = 0,policy = None)
Return the entire message flattened as a string.
我认为我必须在每种情况下附加这个? mime_details对象有两个部分 - HTML消息和.docx文件。两者都将转换为字符串?那么图像文件呢?
C)当我打开要附加的文件时,我以'rb'模式读取它。
以下是代码:
openfile = open('testfile.docx', 'rb')
我尝试使用'r',但它引发了错误。我已经阅读了这个和'rb'模式只是打开二进制文件。为什么以二进制模式打开.docx文件是有意义的?我是否对所有non.txt文件使用'rb'模式?
D)最后,我看到有些人对附件使用base64编码。我已经四处搜索,下面是一个特别受欢迎的剧本(来自How to send email attachments with Python):
import smtplib, os
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email import encoders
def send_mail( send_from, send_to, subject, text, files=[], server="localhost", port=587, username='', password='', isTls=True):
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
for f in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(f,"rb").read() )
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(f)))
msg.attach(part)
smtp = smtplib.SMTP(server, port)
if isTls: smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.quit()
为什么内容需要在base64中编码?这适用于所有文件,是一般要添加的东西,还是可以忽略它?我应该在什么情况下调用该方法?
最后,作为Python的菜鸟,我上面的一些代码可能是多余的\结构错误。如果您对如何改进我的简单脚本有任何提示或建议,请告诉我。
谢谢!