Skip to content

Instantly share code, notes, and snippets.

@Stefan-Code
Created January 5, 2016 17:34
Show Gist options
  • Save Stefan-Code/fbc87a51178790358962 to your computer and use it in GitHub Desktop.
Save Stefan-Code/fbc87a51178790358962 to your computer and use it in GitHub Desktop.
Send an email using gmail in python
import smtplib
def send_email(user, pwd, recipient, subject, body):
"""
Sends an email using a gmail account.
"""
gmail_user = user
gmail_pwd = pwd
FROM = user
TO = recipient if type(recipient) is list else [recipient]
SUBJECT = subject
TEXT = body
# Prepare actual message
message = """\From: %s\nTo: %s\nSubject: %s\n\n%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
try:
server = smtplib.SMTP("smtp.gmail.com", 587)
server.ehlo()
server.starttls()
server.login(gmail_user, gmail_pwd)
server.sendmail(FROM, TO, message)
server.close()
print('successfully sent the mail')
except Exception as e:
print("failed to send mail")
raise e
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment