0

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.

4

1 回答 1

1

不能肯定地说,但问题可能出在您提到但未报告的那些输入中。
例如,这段代码没有问题:

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

但是,如果您将text参数作为列表发送,那么您将获得您报告的确切回溯:

>>> 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'
于 2013-06-24T19:39:44.750 回答