How to send an email from Gmail by Python.

usage

$ python3 sample.py

sample.py

"""Send an email from Gmail.

Before execute this code,
turn on the flag "Allow less secure apps"
from the follwoing link.
https://myaccount.google.com/lesssecureapps
"""
import smtplib
import email.mime.text

# Enter your Gmail account.
username = 'YOUR_GMAIL_ACCOUNT@gmail.com'
password = 'YOUR_GMAIL_PASSWORD'

# Write your email.
from_ = username
to = 'ADDRESS_WHERE_YOU_WANT_TO_SEND_EMAIL@MAILSERVER.COM'
sub = 'Python smtplib'
body = """\
Hello, Bob.
My name is Alice.
"""


# The following code will send your email via Gmail.
msg = email.mime.text.MIMEText(body)
msg['Subject'] = sub
msg['From'] = from_
msg['To'] = to

host = 'smtp.gmail.com'
port = 465
smtp = smtplib.SMTP_SSL(host, port)
smtp.ehlo()
smtp.login(username, password)
smtp.mail(username)
smtp.rcpt(to)
smtp.data(msg.as_string())
smtp.quit()