任何人都可以告诉我为什么我收到错误[AttributeError:'list'对象没有属性'encode']

时间:2016-07-01 18:00:00

标签: python excel smtp attachment

我一直试图运行此代码,以便将excel表格作为电子邮件的附件发送。我可以使用smtplib发送普通电子邮件,但无法使MIMEMultipart工作。我一直得到[AttributeError:'list'对象没有属性'encode']错误

import smtplib, ssl
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders

fromaddr = ['Email']
sendto = ['Email']

msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = sendto
msg['Subject'] = 'This is cool'

body = "this is the body of the text message"


msg.attach(MIMEText(body, 'plain'))

filename = 'Work.xlsx'
attachment = open('/home/mark/Work.xlsx', '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)

smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login('email', 'password')


text = msg.as_string()
smtpObj.sendmail(fromaddr, sendto , text)
smtpObj.quit()

2 个答案:

答案 0 :(得分:8)

fromaddr = ['Email']
sendto = ['Email']

这对我来说有点奇怪。它们不应该是字符串,而不是列表吗?

fromaddr = 'Email'
sendto = 'Email'

答案 1 :(得分:0)

仍然出现错误,所以我做了以下更改,对我有用。

toaddr = ['mailid_1','mailid_2']
cc = ['mailid_3','mailid_4']
bcc = ['mailid_5','mailid_6']
subject = 'Email from Python Code'
fromaddr = 'sender_mailid'
message = "\n  !! Hello... !!"

msg['From'] = fromaddr
msg['To'] = ', '.join(toaddr)
msg['Cc'] = ', '.join(cc)
msg['Bcc'] = ', '.join(bcc)
msg['Subject'] = subject

s.sendmail(fromaddr, (toaddr+cc+bcc) , message)