From 1bb5a9848212c48671c90a0875b3545dd0e0fb8c Mon Sep 17 00:00:00 2001 From: Param Singh Date: Mon, 10 Dec 2018 23:12:00 +0530 Subject: [PATCH 1/2] Add module for sending mail --- brainzutils/mail.py | 58 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 brainzutils/mail.py diff --git a/brainzutils/mail.py b/brainzutils/mail.py new file mode 100644 index 0000000..5ee617b --- /dev/null +++ b/brainzutils/mail.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +"""This module provides a way to send emails.""" +from email.mime.application import MIMEApplication +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText +from flask import current_app +import smtplib +import socket + + +def send_mail(subject, text, recipients, attachments=None, + from_name="MetaBrainz Notifications", + from_addr=None): + """This function can be used as a foundation for sending email. + + Args: + subject: Subject of the message. + text: The message itself. + recipients: List of recipients. + attachments: List of (file object, subtype, name) tuples. For example: + (, 'pdf', 'receipt.pdf'). + from_name: Name of the sender. + from_addr: Email address of the sender. + """ + if attachments is None: + attachments = [] + if from_addr is None: + from_addr = 'noreply@' + current_app.config['MAIL_FROM_DOMAIN'] + + if current_app.config['TESTING']: # Not sending any emails during the testing process + return + + if not recipients: + return + + message = MIMEMultipart('mixed') + message['Subject'] = subject + message['From'] = "%s <%s>" % (from_name, from_addr) + message.attach(MIMEText(text, _charset='utf-8')) + + for attachment in attachments: + file_obj, subtype, name = attachment + attachment = MIMEApplication(file_obj.read(), _subtype=subtype) + file_obj.close() # FIXME(roman): This feels kind of hacky. Maybe there's a better way? + attachment.add_header('content-disposition', 'attachment', filename=name) + message.attach(attachment) + + try: + smtp_server = smtplib.SMTP(current_app.config['SMTP_SERVER'], current_app.config['SMTP_PORT']) + except (socket.error, smtplib.SMTPException) as e: + current_app.logger.error('Error while sending email: %s', e, exc_info=True) + raise MailException(e) + smtp_server.sendmail(from_addr, recipients, message.as_string()) + smtp_server.quit() + + +class MailException(Exception): + pass From 47e1f74b304f1fd6453633fc08974bf88440bb7b Mon Sep 17 00:00:00 2001 From: Param Singh Date: Mon, 10 Dec 2018 23:13:08 +0530 Subject: [PATCH 2/2] Bump version number --- brainzutils/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/brainzutils/__init__.py b/brainzutils/__init__.py index 77f1c8e..b280975 100644 --- a/brainzutils/__init__.py +++ b/brainzutils/__init__.py @@ -1 +1 @@ -__version__ = '1.5.0' +__version__ = '1.8.0'