Python 3.3中的电子邮件附件问题

时间:2013-06-24 13:54:06

标签: python email attachment

我正在尝试通过Python 3.3中的电子邮件附件发送PDF。我搜索了如何操作并在本网站的另一个问题中找到了此代码:

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

我用我的输入调用该函数并得到一个错误:

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'

有谁知道解决方案?提前谢谢。

1 个答案:

答案 0 :(得分:0)

不能肯定地说,但问题可能在于你提到并且没有报告的那些输入 例如,此代码没有问题:

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'