0
votes

I have been trying step by step to create a python (v3.4) script to send a email with attachments. I already succesfully send one without attachmente using smtplib library. However, to add an attachment it seems that I need to create an MIMEMultipart object. Nothing weird until here.

Based on examples I created this

import smtplib
from email.mime.multipart import MIMEMultipart

try:
fromaddr = '[email protected]'
toaddrs  = ['[email protected]']

# 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")

except SMTPException: print("Error: unable to send email") finally: server.quit()

However the line " text = msg.as_string()" throw me the following error

Traceback (most recent call last): File "C:/Users/user/upload_file.py", line 37, in text = msg.as_string() File "C:\Python34\lib\email\message.py", line 159, in as_string g.flatten(self, unixfrom=unixfrom) File "C:\Python34\lib\email\generator.py", line 112, in flatten self._write(msg) File "C:\Python34\lib\email\generator.py", line 192, in _write self._write_headers(msg) File "C:\Python34\lib\email\generator.py", line 219, in _write_headers self.write(self.policy.fold(h, v)) File "C:\Python34\lib\email_policybase.py", line 314, in fold return self._fold(name, value, sanitize=True) File "C:\Python34\lib\email_policybase.py", line 352, in _fold parts.append(h.encode(linesep=self.linesep, AttributeError: 'list' object has no attribute 'encode'

What can I do?

1

1 Answers

3
votes

The problem is that your variable toaddrs is a list.

You need to have the list of addresses as a string with the addresses separated by commas e.g.

msg['To'] = ",".join(toaddrs)

Everything should work fine after that. See here for more details: How to send email to multiple recipients using python smtplib?