Skip to content

Instantly share code, notes, and snippets.

@ecatanzani
Last active July 13, 2018 05:35
Show Gist options
  • Save ecatanzani/60c0114ca3174e5c6dbb13bd380dd9ea to your computer and use it in GitHub Desktop.
Save ecatanzani/60c0114ca3174e5c6dbb13bd380dd9ea to your computer and use it in GitHub Desktop.
Simple notification emailer with Python
# Simple email notification sender
# Developed by Enrico Catanzani
# Release 3.2
#!/usr/bin/python3
import smtplib
import os.path as op
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email import encoders
def deploy_mail(send_from, send_to, subject, message, files,
server, port, username, password,
use_tls=True):
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(MIMEText(message))
for path in files:
part = MIMEBase('application', "octet-stream")
with open(path, 'rb') as file:
part.set_payload(file.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="{}"'.format(op.basename(path)))
msg.attach(part)
smtp = smtplib.SMTP(server, port)
if use_tls:
smtp.starttls()
smtp.login(username, password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.quit()
# Mail Params
"""Compose and send email with provided info and attachments.
Args:
send_from (str): from name
send_to (str): to name
subject (str): message title
message (str): message body
files (list[str]): list of file paths to be attached to email
server (str): mail server host name
port (int): port number
username (str): server auth username
password (str): server auth password
use_tls (bool): use TLS mode
"""
deploy_mail(send_from, send_to, subject, message, files,
server, port, username, password,
use_tls=True)
'''
####### Python 2 release #######
# Mail Settings
SMTP_SERVER = ''
SMTP_PORT = 587
SMTP_USERNAME = ''
SMTP_PASSWORD = ''
SMTP_FROM = ''
SMTP_TO = ''
TEXT_FILENAME = ''
MESSAGE = """ Message Core
"""
# Building the message !
import smtplib, email
from email import encoders
import os
msg = email.MIMEMultipart.MIMEMultipart()
body = email.MIMEText.MIMEText(MESSAGE)
attachment = email.MIMEBase.MIMEBase('text', 'plain')
attachment.set_payload(open(TEXT_FILENAME).read())
attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(TEXT_FILENAME))
encoders.encode_base64(attachment)
msg.attach(body)
msg.attach(attachment)
msg.add_header('From', SMTP_FROM)
msg.add_header('To', SMTP_TO)
# Deploying ...
mailer = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
mailer.starttls()
mailer.login(SMTP_USERNAME, SMTP_PASSWORD)
mailer.sendmail(SMTP_FROM, [SMTP_TO], msg.as_string())
mailer.close()
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment