How to send an email from Gmail by Python.

PythonGmail を使ってメールを送る方法

usage

$ python3 sample.py

code

"""Send a 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, Python'


# 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()
Remove all ads