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.
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.