我一直在尝试创建一个python(v3.4)脚本来发送带附件的电子邮件。我已经使用smtplib库成功发送了一个没有attachmente。但是,要添加附件,我似乎需要创建一个MIMEMultipart对象。在此之前没什么奇怪的。
根据我创建的这个例子
import smtplib
from email.mime.multipart import MIMEMultipart
try:
fromaddr = 'from@email.com'
toaddrs = ['to@email.com']
# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = fromaddr
msg['To'] = toaddrs
msg.preamble = 'Our family reunion'
password = 'ExamplePassword88'
# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.ehlo()
server.login(fromaddr,password)
text = msg.as_string()
server.sendmail(fromaddr, toaddrs, text)
print("Successfully sent email")
除了SMTPException: 打印("错误:无法发送电子邮件") 最后: server.quit()
然而" text = msg.as_string()" 给我发出以下错误
追踪(最近一次通话): 文件" C:/Users/user/upload_file.py" ;,第37行,in text = msg.as_string() 文件" C:\ Python34 \ lib \ email \ message.py",第159行,as_string g.flatten(self,unixfrom = unixfrom) 文件" C:\ Python34 \ lib \ email \ generator.py",第112行,展平 self._write(MSG) 文件" C:\ Python34 \ lib \ email \ generator.py",第192行,_write self._write_headers(MSG) 文件" C:\ Python34 \ lib \ email \ generator.py",第219行,_write_headers self.write(self.policy.fold(h,v)) 文件" C:\ Python34 \ lib \ email_policybase.py",第314行,折叠 return self._fold(name,value,sanitize = True) 文件" C:\ Python34 \ lib \ email_policybase.py",第352行,in _fold parts.append(h.encode(linesep = self.linesep, AttributeError:' list'对象没有属性'编码'
我该怎么办?
答案 0 :(得分:0)
问题是您的变量toaddrs
是一个列表。
您需要将地址列表作为字符串,地址以逗号分隔,例如
msg['To'] = ",".join(toaddrs)
之后一切都应该正常工作。 有关详细信息,请参见此处 How to send email to multiple recipients using python smtplib?