Last active
August 16, 2020 07:16
-
-
Save abhyudayasrinet/7f8da4f6980197b15d1c16e02af84a6e to your computer and use it in GitHub Desktop.
Send emails using gmail app passwords and python smtp library
This file contains 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 os | |
import smtplib | |
import logging | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
class GmailAPI(): | |
''' | |
Send email using email, app key from environment variables | |
Usage: | |
g = GmailAPI() | |
g.send_email(to, subject, body) | |
''' | |
def __init__(self): | |
self.user = os.getenv('GMAIL_USER') | |
self.key = os.getenv('GMAIL_APP_KEY') | |
def create_message(self, sender, to, subject, body): | |
msg = MIMEMultipart('alternative') | |
msg['Subject'] = subject | |
msg['From'] = sender | |
msg['To'] = to | |
msg.attach(MIMEText(body, 'html')) | |
return msg | |
def send_email(self, to, subject, body): | |
message = self.create_message(self.user, to, subject, body) | |
server = smtplib.SMTP_SSL('smtp.gmail.com', 465) | |
server.ehlo() | |
server.login(self.user, self.key) | |
server.sendmail(self.user, to, message.as_string()) | |
server.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment