i am sending gmail via python but I do not get any subject. I realize the code I am showing you does not have any subject but i have tried many variations without success. can someone tell me how to implement a subject. The subject will be the same every time.
fromaddr = 'XXXX@gmail.com'
toaddrs = 'jason@XXX.com'
msg = 'Portal Test had an error'
#provide gmail user name and password
username = 'XXXX'
password = 'XXXXX'
开发者_如何学Go # functions to send an email
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.ehlo()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
There are 2 important step in sending out a Internet email - create a RFC-2822 message and then sent it using SMTP. You were looking at the SMTP part but has not created the right message in the first place. It is easier to demonstrate by doing it.
>>> from email.mime.text import MIMEText
>>>
>>> fromaddr = 'XXXX@gmail.com'
>>> toaddrs = 'jason@XXX.com'
>>> subject = 'This is an important message'
>>> content = 'Portal Test had an error'
>>>
>>> # constructing a RFC 2822 message
... msg = MIMEText(content)
>>> msg['From'] = fromaddr
>>> msg['To'] = toaddrs
>>> msg['Subject'] = subject
A RFC 2822 message is really a piece of text that looks like this:
>>> print msg
From nobody Tue Apr 05 11:37:50 2011
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
From: XXXX@gmail.com
To: jason@XXX.com
Subject: This is an important message
Portal Test had an error
With this you should be able to send it using your SMTP code. Notice that some data like from and to address are repeated in both step.
You need to populate the "Subject" header.
See the following page for some examples of how to do this correctly: 18.1.11. email: Examples. The first one does more or less what you want.
Use Python's email module to generate properly formatted RFC-822 compliant email - including Subject etc. Doing it yourself is error-prone.
http://docs.python.org/library/email
精彩评论