Skip to content

Instantly share code, notes, and snippets.

@niconico25
Last active March 20, 2019 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niconico25/076734cc6e162d1aaeca7c2461852732 to your computer and use it in GitHub Desktop.
Save niconico25/076734cc6e162d1aaeca7c2461852732 to your computer and use it in GitHub Desktop.
"""Send an email from Gmail.
Before execute this code, you have some tasks.
1) for temporary
Turn on the flag "Allow less secure apps"
from the follwoing link.
https://myaccount.google.com/lesssecureapps
or
2) for permanently
Generate an application password.
https://support.google.com/mail/answer/185833
"""
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment