尝试使用python发送电子邮件,使IndexError:tuple超出范围

时间:2015-03-27 03:59:22

标签: python python-2.7 email

我尝试将包含本地计算机附件的电子邮件发送到Gmail帐户。

这是我的代码:

import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email import Encoders

def send_mail(send_from, send_to, body, text, files=None,server="127.0.0.1"):
    try:
        assert isinstance(send_to, list)
    except AssertionError as e:
        print e

    msg = MIMEMultipart(
        From=send_from,
        To=COMMASPACE.join(send_to),
        Date=formatdate(localtime=True),
        Subject=body
    )
    msg.attach(MIMEText(text))

    for f in files or []:
        with open(f, "rb") as fil:
            msg.attach(MIMEApplication(fil.read(), Content_Disposition='attachment; filename="%s"' % basename(f)))

    try:
        smtp = smtplib.SMTP(server)
        smtp.sendmail(send_from, send_to, msg.as_string())
        print "Successfully sent mail."
    except SMTPException:
        print "Error: unable to send email"

    smtp.close()

基于this问题的接受答案。

以下是调用它的代码:

send_from = "name.surname@my-company.com"
send_to = "lcuky_recipient@gmail.com"
subject = "testEmail", 
text = "This is a test. Hopefully, there's a file attached to it."
files = ".././dudewhat.csv"
send_mail(send_from, send_to, subject, text, files)

但这是我得到的回报:

File "belo_monthly.py", line 138, in <module>
    send_mail(send_from, send_to, subject, text, files)
  File "belo_monthly.py", line 26, in send_mail
    Subject=body
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/email/mime/multipart.py", line 36, in __init__
    MIMEBase.__init__(self, 'multipart', _subtype, **_params)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/email/mime/base.py", line 25, in __init__
    self.add_header('Content-Type', ctype, **_params)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/email/message.py", line 408, in add_header
    parts.append(_formatparam(k.replace('_', '-'), v))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/email/message.py", line 52, in _formatparam
    value = utils.encode_rfc2231(value[2], value[0], value[1])
IndexError: tuple index out of range

我错过了什么?

2 个答案:

答案 0 :(得分:2)

这是你的问题:

subject =“testEmail”,

最后删除逗号,事情应该有效

答案 1 :(得分:2)

您正在检查列表的实例,但解析的值是字符串。尝试更改

send_to = "lcuky_recipient@gmail.com"

send_to = ["lcuky_recipient@gmail.com"]

或修改逻辑