Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python email sending TypeError: Expected string or buffer

Alright guys, I have looked on the internet for ages and simply could not find an answer to this. I have tried many suggestions but I can't seem to get it to work. I am attempting to send an email using python (smtplib and email modules) and the gmail service. Here are my imported packages:

import time, math, urllib2, urllib, os, shutil, zipfile, smtplib, sys
from email.mime.text import MIMEText

and here is my def statement for sending the email:

def sendmessage():
print('== You are now sending an email to Hoxie. Please write your username below. ==')
mcusername = str(raw_input('>> Username: '))
print('>> Now your message.')
message = str(raw_input('>> Message: '))
print('>> Attempting connection to email host...')
fromaddr = '[email protected]'
toaddrs = '[email protected]'
username = '[email protected]'
password = '1013513403'
server = smtplib.SMTP('smtp.gmail.com:587')
subject = 'Email from',mcusername
content = message
msg = MIMEText(content)
msg['From'] = fromaddr
msg['To'] = toaddrs
msg['Subject'] = subject
try:
    server.ehlo()
    server.starttls()
    server.ehlo()
except:
    print('!! Could not connect to email host! Check internet connection! !!')
    os.system('pause')
    main()
else:
    print('>> Connected to email host! Attempting secure login via SMTP...')
    try:
        server.login(username,password)
    except:
        print('!! Could not secure connection! Stopping! !!')
        os.system('pause')
        main()
    else:
        print('>> Login succeeded! Attempting to send message...')
        try:
            server.sendmail(fromaddr, toaddrs, msg)
        except TypeError as e:
            print e
            print('Error!:', sys.exc_info()[0])
            print('!! Could not send message! Check internet connection! !!')
            os.system('pause')
            main()
        else:
            server.quit()
            print('>> Message successfully sent! I will respond as soon as possible!')
            os.system('pause')
            main()

I have debugged as extensively as I dare and get this:

>> Login succeeded! Attempting to send message...
TypeError: expected string or buffer

Which means it succeeded at logging in but stopped when it tried to send the message. One thing that boggles me is that it doesn't point where. Also my coding might not be that great so no cyber bullying.

Any help would be greatly appreciated! Thanks.

like image 511
CR0SS0V3R Avatar asked Jan 30 '12 06:01

CR0SS0V3R


2 Answers

The line that's crashing is

server.sendmail(fromaddr, toaddrs, msg)

You're giving it two strings and a MIMEText instance; it wants the message in the form of a string. [I think it also wants the addresses in the form of a list, but it special-cases one string.] For example, you can look at the example in the docs:

s = smtplib.SMTP('localhost')
s.sendmail(me, [you], msg.as_string())
s.quit()

You have to convert the MIMEText into a string for sendmail to be happy. After fixing the subject bug that @jdi pointed out (which generates an "AttributeError: 'tuple' object has no attribute 'lstrip'" message) and changing msg to msg.as_string(), your code works for me.

like image 124
DSM Avatar answered Oct 29 '22 03:10

DSM


My guess is the culprit is this line:

subject = 'Email from',mcusername

If you are expecting to create subject as a string, its actually being made into a tuple because you are passing two values. What you probably wanted to do is:

subject = 'Email from %s' % mcusername

Also, for the debugging aspect... The way you are wrapping all of your exceptions and just printing the exception message is throwing away the helpful traceback (if there is one). Have you tried not wrapping everything until you really know the specific exception you are trying to handle? Doing blanket catch-all exception handling like that makes debugging harder when you have syntax bugs.

like image 3
jdi Avatar answered Oct 29 '22 02:10

jdi