Skip to content

Instantly share code, notes, and snippets.

@jasonrahm
Created November 17, 2021 22:25
Show Gist options
  • Save jasonrahm/1541fe411a58ded3982de392232e727e to your computer and use it in GitHub Desktop.
Save jasonrahm/1541fe411a58ded3982de392232e727e to your computer and use it in GitHub Desktop.
import os
import smtplib
import ssl
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_mail(receiver_email, subject, body, filename=None):
sender_email = os.environ.get("GMAIL_SENDER_EMAIL")
password = os.environ.get("GMAIL_SENDER_PASSWORD")
message = MIMEMultipart()
message["FROM"] = sender_email
message["TO"] = receiver_email
message["SUBJECT"] = subject
message.attach(MIMEText(body, "html"))
if filename is not None:
with open(filename, "rb") as attachment:
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header(
"Content-Disposition",
f"attachment; filename= {filename}",
)
message.attach(part)
text = message.as_string()
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment