zack_falcon
zack_falcon

Reputation: 4386

Trying to send an email using python, getting an IndexError: tuple out of range

I'm trying to send an email with an attachment from my local machine to a gmail account.

Here's my code:

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

Based on the accepted answer of this question.

And here's the code that calls it:

send_from = "[email protected]"
send_to = "[email protected]"
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)

But this is what I'm getting in return:

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

What did I miss?

Upvotes: 0

Views: 1440

Answers (2)

skar
skar

Reputation: 401

You are checking for instance for list but the parsed value is string. Try changing

send_to = "[email protected]"

to

send_to = ["[email protected]"]

or modify the logic

Upvotes: 2

DmitrySemenov
DmitrySemenov

Reputation: 10335

this is your problem:

subject = "testEmail",

remove comma at the end and things should work

Upvotes: 2

Related Questions