Can anyone tell my why I'm getting the error [AttributeError: 'list' object has no attribute 'encode']

拜拜、爱过 提交于 2020-08-22 09:57:10

问题


I keep trying to run this code in order to send an excel sheet as an attachment on an email. I can send normal emails using smtplib but can't get the MIMEMultipart to work. I keep getting the [AttributeError: 'list' object has no attribute 'encode'] error

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()

回答1:


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

This looks a little odd to me. Shouldn't they be strings, not lists?

fromaddr = 'Email'
sendto = 'Email'



回答2:


Still I was getting an error, so I did below changes and it worked for me.

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)


来源:https://stackoverflow.com/questions/38151440/can-anyone-tell-my-why-im-getting-the-error-attributeerror-list-object-has

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!