【发布时间】:2019-12-03 23:36:11
【问题描述】:
我尝试通过这部分代码使用python 3.6从gmail发送消息:
import smtplib as smtp
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import os
SUBJECT = *subject message*
SOURCE = *directory*
TEXT = *some text in message*
msg = MIMEMultipart()
msg['From'] = *send from email*
msg['To'] = *send to email*
msg['Subject'] = SOURCE
#################### part with attachment
msg.attach(MIMEText(TEXT, 'plain'))
filename = os.path.basename(SOURCE)
attachment = open(SOURCE, '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)
#################### end of attachment part
#################### server part
server = smtp.SMTP(smtp.gmail.com', 587)
server.starttls()
server.login(*send from email*, *send from email password*)
server.sendmail(*send from email*, *send to email*, msg.as_string())
server.close()
但是得到一个属性错误:
AttributeError: 'list' 对象没有属性 'encode'
如果我删除代码的附件部分并在服务器部分之前添加msg = MIMEText(TEXT),我会在我的电子邮件中收到一封信,但它不包含主题。所以我收到一封只有一些文字的信。
我做错了什么?有什么想法吗?
编辑:错误出现在msg.as_string() 行
【问题讨论】:
标签: python python-3.x email smtp