Created
June 6, 2019 09:44
-
-
Save polozhevets/6f4fa5c6f0f3a903f7d544105783c3bb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! python3.7 | |
from email.message import EmailMessage | |
import smtplib | |
from pathlib import Path | |
def send_simple_message(email, subject, html, from_subject="Company Name", bcc="", attachment=None): | |
from_address = 'no-reply@domain.com' | |
auth_user = '' | |
auth_password = '' | |
smtp_host = 'email-smtp.eu-west-1.amazonaws.com' | |
smtp_port = 587 | |
def attach_file(email, filepath, extention, filename): | |
types = { | |
'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', | |
'pdf': 'application/pdf' | |
} | |
maintype, subtype = types[extention].split('/', 1) | |
with open(filepath, 'rb') as content_file: | |
content = content_file.read() | |
email.add_attachment(content, maintype=maintype, subtype=subtype, filename=filename) | |
return email | |
def create_email_message(from_address, to_address, subject, body, bcc): | |
msg = EmailMessage() | |
msg['From'] = "%s <%s>" % (from_subject, from_address) | |
msg['To'] = to_address | |
msg['Bcc'] = bcc | |
msg.set_content(body, subtype='html') | |
msg.add_header('Subject', subject) | |
return msg | |
msg = create_email_message(from_address, email, subject, html, bcc) | |
if attachment: | |
msg.make_mixed() | |
if not isinstance(attachment, list): | |
attachment = [attachment] | |
for item in attachment: | |
filename = Path(item).name | |
subtype = str(Path(filename).suffix).replace('.', '') | |
msg = attach_file(msg, item, subtype, filename) | |
with smtplib.SMTP(smtp_host, port=smtp_port) as smtp_server: | |
smtp_server.ehlo() | |
smtp_server.starttls() | |
smtp_server.login(auth_user, auth_password) | |
smtp_server.send_message(msg) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment