Skip to content

Commit

Permalink
Merge pull request #24 from paramsingh/mail
Browse files Browse the repository at this point in the history
Add module for email sending
  • Loading branch information
paramsingh authored Dec 10, 2018
2 parents fa849aa + 47e1f74 commit f413e09
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
2 changes: 1 addition & 1 deletion brainzutils/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = '1.5.0'
__version__ = '1.8.0'
58 changes: 58 additions & 0 deletions brainzutils/mail.py
Original file line number Diff line number Diff line change
@@ -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:
(<file_obj>, '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

0 comments on commit f413e09

Please sign in to comment.