Skip to content

Instantly share code, notes, and snippets.

@answerquest
Last active June 30, 2023 03:37
Show Gist options
  • Save answerquest/421d5f3b2a18726133bcb367e4c1c477 to your computer and use it in GitHub Desktop.
Save answerquest/421d5f3b2a18726133bcb367e4c1c477 to your computer and use it in GitHub Desktop.
python SMTP emailing function
# by Nikhil VJ, https://nikhilvj.co.in , https://github.com/answerquest
# generic SMTP emailing function in Python, using SSL
# will take values from these env params:
# EMAIL_SERVER : SMTP server url
# EMAIL_PORT : SMTP port num (must be the SSL port)
# EMAIL_SENDER : Email account whose SMTP login you're using
# EMAIL_PW : SMTP password of the email account (likely same as regular password used to login to that account)
# tested and works well with BigRock.in hosting account's email accounts.
# ..and with Google workspace account IF you enable "allow less secure apps".
import smtplib, os
from email.message import EmailMessage
from email.headerregistry import Address
def makeAddress(emails):
# have to split "name@domain.com" into Address("name","name","domain.com"), and if multiple then have to string them together into tuple
if type(emails) == str:
holder = emails.strip().split('@')
if len(holder) != 2:
print("makeAddress: Invalid email id:",emails)
return os.environ.get('EMAIL_SENDER','')
return Address(holder[0],holder[0],holder[1])
elif type(emails) == list:
collector = []
for oneEmail in emails:
holder = oneEmail.strip().split('@')
if len(holder) != 2:
print("makeAddress: Invalid email id:",oneEmail)
continue
collector.append(Address(holder[0],holder[0],holder[1]))
# after for loop:
if len(collector): return tuple(collector)
# default
return os.environ.get('EMAIL_SENDER','')
def sendEmail(content, subject, recipients, cc=None, html=None):
'''
Emailing function.
'''
# from https://docs.python.org/3/library/email.examples.html
msg = EmailMessage()
msg['Subject'] = subject
msg['From'] = makeAddress(os.environ.get('EMAIL_SENDER',''))
msg['To'] = makeAddress(recipients)
if cc: msg['Cc'] = makeAddress(cc)
msg.set_content(content)
# adding html formatted body: from https://stackoverflow.com/a/58322776/4355695
if html:
msg.add_alternative(f"<!DOCTYPE html><html><body>{html}</body></html>", subtype = 'html')
print('to:',msg['To'])
# login to server and send the actual email
# try:
server = smtplib.SMTP_SSL(os.environ.get('EMAIL_SERVER',''), os.environ.get('EMAIL_PORT','')) # We are specifying TLS here
server.ehlo()
server.login(os.environ.get('EMAIL_SENDER',''),os.environ.get('EMAIL_PW',''))
status = server.send_message(msg)
server.close()
return status
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment