Skip to content

Instantly share code, notes, and snippets.

@sohang3112
Last active April 24, 2024 13:13
Show Gist options
  • Save sohang3112/e5e58482c15c83727036487707ccf8eb to your computer and use it in GitHub Desktop.
Save sohang3112/e5e58482c15c83727036487707ccf8eb to your computer and use it in GitHub Desktop.
Send emails in Python using smtplib
import os
import traceback
import smptlib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate
# specify credentials in the below environment variables
EMAIL_SERVER = 'email-smtp.us-west-2.amazonaws.com' # change this according to requirement
EMAIL_SERVER_PORT = 465
EMAIL_PASSWD = ''
EMAIL_FROM = DEFAULT_FROM_EMAIL = os.environ['EMAIL_SENDER_ADDRESS']
SENDER_NAME = os.environ['EMAIL_SENDER_NAME']
SMTP_USERNAME = os.environ['SMTP_USERNAME']
SMTP_PASSWORD = os.environ['SMTP_PASSWORD']
email_recipients = [
# TODO: specify email addresses of recipients
]
def send_email(subject: str, email_html: str) -> None:
msg = MIMEMultipart()
msg['From'] = EMAIL_FROM
msg['To'] = ", ".join(email_recipients)
msg['Date'] = formatdate(localtime=True)
#msg['Bcc'] = ", ".join(EMAIL_BCC) # optional: list of BCC email recipients
msg['Subject'] = subject
html_part = MIMEText(email_html, 'html')
msg.attach(html_part)
# NOTE: previously tried using smtplib.SMTP() class instead (inside a with statement), however it hanged then
# Also in an AWS Lambda, in addition to SMTP_SSL(), also remember to disable VPC (Virtual Private Cloud), otherwise it will hang
smtpserver = smtplib.SMTP_SSL(EMAIL_SERVER, EMAIL_SERVER_PORT)
try:
smtpserver.ehlo()
smtpserver.login(SMTP_USERNAME, SMTP_PASSWORD)
smtpserver.sendmail(EMAIL_FROM, email_recipients, msg.as_string())
print("Email sent successfully")
except:
print("Error while sending email")
traceback.print_exc()
finally:
smtpserver.close()
# Calling example
send_email(
subject="Hello World",
email_html="""
<html>
<body>
<p>Hello World!</p
<br/>
<br/>
<p>Regards</p>
</body>
</html>
"""
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment