Skip to content

Instantly share code, notes, and snippets.

@niconico25 niconico25/gmail.py
Last active Mar 20, 2019

Embed
What would you like to do?
"""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
You can’t perform that action at this time.