1

I'm struggling to figure out what went wrong with the below code. I'm trying to send html mail.

NOW = datetime.datetime.now()

 def sendEmail(msg):
    global NOW
    global SENDER
    global EMAILTARGET
    today = "%s/%s/%s" % (NOW.month,NOW.day,NOW.year)
    # Create message container - the correct MIME type is multipart/alternative.
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "SAR Data Report - %s" % today
    msg['From'] = SENDER
    msg['To'] = EMAILTARGET
    chunk = MIMEText(msg, 'html')
    msg.attach(chunk)
    s = smtplib.SMTP('localhost')
    s.sendmail(SENDER, EMAILTARGET, msg.as_string())
    s.quit()

the above code gives me the following error:

Traceback (most recent call last):
 File "./html_mail.py", line 295, in <module>
 sendEmail(html)
 File "./html_mail.py", line 245, in sendEmail
 chunk = MIMEText(msg, 'html')
 File "/usr/lib/python2.7/email/mime/text.py", line 30, in __init__
  self.set_payload(_text, _charset)
 File "/usr/lib/python2.7/email/message.py", line 226, in set_payload
  self.set_charset(charset)
 File "/usr/lib/python2.7/email/message.py", line 268, in set_charset
  cte(self)
 File "/usr/lib/python2.7/email/encoders.py", line 73, in encode_7or8bit
  orig.encode('ascii')
  AttributeError: MIMEMultipart instance has no attribute 'encode'

2 Answers 2

4

The error in your code is that you've used msg as an in-parameter to your function and it collides with your MIME message container (both named msg).

What you need to do is to change the name of the in-parameter to something else, like html:

def sendEmail(html):
...
chunk = MIMEText(html, 'html')
...
Sign up to request clarification or add additional context in comments.

1 Comment

If you want to avoid all the hassles with SMTP I would recommend an email delivery service like AlphaMail or SendGrid.
0

You're passing msg, which is a MIMEMultipart object, to the MIMEText initializer, which expects a string. You should be passing a string containing the HTML you want to attach, not the message you're trying to attach it to.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.