User Tools

Site Tools


python:sendemailsgmail

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

python:sendemailsgmail [2013/03/16 17:40] (current)
Line 1: Line 1:
 +==== HOWTO SEND EMAILS USING PYTHON AND A GMAIL ACCOUNT ====
 +05.11.2008
  
 +
 +**Before we begin...**
 +
 +... you'll need a gmail account, of course. Even this script applies to gmail, it can be easily modified and used for any email service.
 +
 +
 +**The Script**
 +
 +First, import the needed library **smtplib**
 +
 +<code python>
 +#​!/​usr/​bin/​env python
 +# EXAMPLE: HOWTO SEND AN EMAIL USING A GMAIL ACCOUNT
 +#
 +#
 +
 +import smtplib
 +</​code>​
 +
 +
 +Prepare the sender/​addressee name and email address:
 +
 +<code python>
 +from_addr = "​sender@gmail.com"​
 +sender = "​Sender Name"
 +
 +to_addr = "​johndoe@yahoo.com"​
 +to = "John Doe"
 +</​code>​
 +
 +
 +Fill up the subject. Then create the message from the headers and the body of the message:
 +
 +<code python>
 +subject = "Test smtplib"​
 +
 +# pay attention here: To: and Subject must be right after \n (no space between)
 +headers = "From: %s \r\nTo: %s\r\nSubject:​ %s \r\n\r\n"​ % (sender, to, subject)
 +msg = headers + "This is the body of the message!"​
 +</​code>​
 +
 +
 +**Sending the mail**
 +
 +<code python>
 +mailserver = smtplib.SMTP("​smtp.gmail.com",​ 587) 
 +mailserver.set_debuglevel(1) # to get interesting messages
 +mailserver.ehlo()
 +mailserver.starttls()
 +mailserver.ehlo()
 +mailserver.login(from_addr,​ '​password'​) ​
 +
 +mailserver.sendmail(from_addr,​ to_addr, msg)
 +mailserver.quit()
 +</​code>​
 +
 +Download {{:​python:​gmail.py.zip|here}} the python source file
python/sendemailsgmail.txt ยท Last modified: 2013/03/16 17:40 (external edit)