Skip to content

Instantly share code, notes, and snippets.

@justengel
Created December 6, 2019 15:09
Show Gist options
  • Save justengel/1a49ed2b78b41d594229012cc530f2dc to your computer and use it in GitHub Desktop.
Save justengel/1a49ed2b78b41d594229012cc530f2dc to your computer and use it in GitHub Desktop.
Simple send_mail function to using environment variables.
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# Check older version compatibility
if not hasattr(smtplib, "SMTPNotSupportedError"):
smtplib.SMTPNotSupportedError = smtplib.SMTPDataError
os.environ.setdefault('SMTP_SERVER', '')
os.environ.setdefault('SMTP_PORT', '465')
os.environ.setdefault('SMTP_USERNAME', '')
os.environ.setdefault('SMTP_PASSWORD', '')
def send_mail(subject, message, from_email, recipient_list, fail_silently=False, html_message=None, **kwargs):
"""Send an email. This method should be somewhat compatible with django and was made to have the same input
arguments as django.
Args:
subject (str): Subject line of the email.
message (str): Body of the email message.
from_email (str): Email address of the person sending the email
recipient_list (list): Who the email is going to.
fail_silently (bool)[True]: A boolean. When it’s False, send_mail() will raise an smtplib.SMTPException
if an error occurs. See the smtplib docs for a list of possible exceptions, all of which are subclasses
of SMTPException.
html_message (str)[None]: Seconary form of sending email. Try to send this html message or use the regular
message as just plain text.
Kwargs:
auth_server (str)[None]: The optional smtp server name if SMTP_SERVER is not set.
auth_user (str)[None]: The optional username to use to authenticate to the SMTP server.
auth_password (str)[None]: The optional password to use to authenticate to the SMTP server.
Raises:
error (smtplib.SMTPException): If the email cannot be sent and the given display_method is None.
"""
auth_server = kwargs.get('auth_server', os.environ['SMTP_SERVER'])
auth_port = int(kwargs.get('auth_port', os.environ['SMTP_PORT']))
auth_user = kwargs.get('auth_user', os.environ['SMTP_USERNAME'])
auth_password = kwargs.get('auth_password', os.environ['SMTP_PASSWORD'])
if not isinstance(recipient_list, (list, tuple)):
raise ValueError('The recipient list argument must be a list!')
msg = MIMEMultipart('alternative')
msg['subject'] = str(subject)
msg['From'] = from_email
msg['To'] = ",".join(recipient_list)
msg.attach(MIMEText(message, 'plain'))
if html_message:
# According to RFC 2046, the last part of a multipart message, in this case the HTML message,
# is best and preferred.
msg.attach(MIMEText(str(html_message), 'html'))
# Setup the SMTP server and send the message
catch_errors = (OverflowError, ) # Fake Don't catch any error
if fail_silently:
# Catch all
catch_errors = (smtplib.SMTPRecipientsRefused, smtplib.SMTPHeloError, smtplib.SMTPSenderRefused,
smtplib.SMTPDataError, smtplib.SMTPNotSupportedError, smtplib.SMTPConnectError, Exception)
try:
with smtplib.SMTP_SSL(auth_server, auth_port) as smtp:
if auth_user:
smtp.login(auth_user, auth_password)
smtp.set_debuglevel(False)
smtp.sendmail(from_email, recipient_list, msg.as_string())
except catch_errors:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment