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

3

21

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()
Bedding answered 1/7, 2016 at 18:0 Comment(2)
I am using Python 3.4.3 if that makes a differenceBedding
Including the entire traceback might be illuminating, but I think @Kevin is right.Saguaro
B
23
fromaddr = ['Email']
sendto = ['Email']

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

fromaddr = 'Email'
sendto = 'Email'
Bolme answered 1/7, 2016 at 18:2 Comment(0)
K
20

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)
Kittrell answered 1/2, 2019 at 11:21 Comment(0)
B
2

There seems bug. For to email list. You need to handle it little differently. The To message attribute you need as string, whereas the function for sending needs a list. I see it pass with To attribute being list as well but outlook only first recipient is getting mail. Others though shown in To list but they never get any mails.

to_mail_list = ", ".join(to_mail)
msg['To'] = to_mail_list
smtp_obj.sendmail(from_mail, to_mail, msg.as_string())
Blastosphere answered 30/1, 2023 at 12:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.