Reputation: 1
I'm trying to send a PDF through email attachment in Python 3.3. I searched for how to do it and found this code in another question on this site:
import smtplib, os
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email import encoders
def send_mail( send_from, send_to, subject, text, files=[], server="localhost", port=587, username='', password='', isTls=True):
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime = True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
for f in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(f,"rb").read() )
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(f)))
msg.attach(part)
smtp = smtplib.SMTP(server, port)
if isTls: smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.quit()
I call the function with my inputs and get an error that reads:
File "C:\Python33\mailAttach.py", line 46, in send_mail
msg.attach( MIMEText(text) )
File "C:\Python33\lib\email\mime\text.py", line 34, in __init__
_text.encode('us-ascii')
AttributeError: 'list' object has no attribute 'encode'
Does anyone know a solution? Thanks in advance.
Upvotes: 0
Views: 2398
Reputation: 85683
It can not be said for sure but probably the problem is in those inputs you mention and do not report.
For example, this code gives no problem:
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53) on Windows (64 bits).
This is the IEP interpreter.
Type "help" for help, type "?" for a list of *magic* commands.
>>> from email.mime.multipart import MIMEMultipart as MM
>>> from email.mime.text import MIMEText as MT
>>> msg = MM()
>>> msg.attach(MT('hello'))
But if you send the text
parameter as a list, then you get exactly the traceback you report:
>>> msg.attach(MT(['hello']))
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "c:\python33\lib\email\mime\text.py", line 34, in __init__
_text.encode('us-ascii')
AttributeError: 'list' object has no attribute 'encode'
Upvotes: 1