Created
January 5, 2016 17:34
-
-
Save Stefan-Code/fbc87a51178790358962 to your computer and use it in GitHub Desktop.
Send an email using gmail in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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