Advertisement
OOPMan

email_tasks.py

Jun 19th, 2014
300
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.78 KB | None | 0 0
  1. from email import encoders
  2. import smtplib
  3. from email.mime.multipart import MIMEMultipart
  4. from email.mime.text import MIMEText
  5. from email.mime.image import MIMEImage
  6. from email.mime.base import MIMEBase
  7.  
  8. from django.conf import settings
  9. from html2text import HTML2Text
  10. from celery.utils.log import get_task_logger
  11. from celery.exceptions import SoftTimeLimitExceeded, MaxRetriesExceededError
  12.  
  13. from recomed.celery import app
  14.  
  15.  
  16. __author__ = 'adam.jorgensen.za@gmail.com'
  17. logger = get_task_logger(__name__)
  18.  
  19. html_to_text = HTML2Text()
  20. html_to_text.ignore_images = True
  21.  
  22.  
  23. #TODO: Find a new SMTP server that doesn't limit us to 20 emails per hour
  24. def send_email(to_address, subject, body_html, images=None, attachments=None, APP_ROOT=None):
  25.     """
  26.    Send an email. This is a Celery task and hence can be called asynchronously. SMTP settings are drawn from settings.py
  27.    """
  28.     try:
  29.         logger.info("SENDING EMAIL TO: %s  SUBJECT: %s" % (to_address, subject))
  30.  
  31.         message_root = MIMEMultipart('related')
  32.         message_root.preamble = 'This is a multi-part message in MIME format.'
  33.         message_root['Subject'] = subject
  34.         message_root['From'] = settings.EMAIL_HOST_USER
  35.         message_root['To'] = ', '.join(to_address) if not isinstance(to_address, basestring) else to_address
  36.  
  37.         message_content = MIMEMultipart('alternative')
  38.         message_root.attach(message_content)
  39.  
  40.         if images:
  41.             for filename, image_id in images:
  42.                 with open('%simages/%s' % (APP_ROOT, filename), 'rb') as image_file:
  43.                     image_content = MIMEImage(image_file.read())
  44.                     image_content.add_header('Content-ID', '<%s>' % image_id)
  45.                     message_root.attach(image_content)
  46.  
  47.         if attachments:
  48.             for mime_main_type, mime_sub_type, filename, data in attachments:
  49.                 attachment = MIMEBase(mime_main_type, mime_sub_type)
  50.                 attachment.set_payload(data)
  51.                 encoders.encode_base64(attachment)
  52.                 attachment.add_header('Content-Disposition', 'attachment', filename=filename)
  53.                 message_root.attach(attachment)
  54.  
  55.         message_content.attach(MIMEText(html_to_text.handle(body_html), 'plain'))
  56.         message_content.attach(MIMEText(body_html, 'html'))
  57.  
  58.         smtpserver = smtplib.SMTP_SSL(settings.EMAIL_HOST, settings.EMAIL_PORT)
  59.         smtpserver.ehlo()
  60.         smtpserver.login(settings.EMAIL_HOST_USER, settings.EMAIL_HOST_PASSWORD)
  61.  
  62.         # send email
  63.         smtpserver.sendmail(settings.EMAIL_HOST_USER, to_address, message_root.as_string())
  64.         smtpserver.quit()
  65.     except Exception as exc:
  66.         logger.error('Error(%s:%s) sending email with subject "%s" to "%s"' % (exc.__class__.__name__, str(exc), subject, to_address))
  67.         raise exc
  68.     return True
  69.  
  70.  
  71. @app.task(bind=True, time_limit=600, soft_time_limit=520, max_retries=10, compression='bzip2', rate_limit='20/h')
  72. def send_email_task(self, to_address, subject, body_html, images=None, attachments=None, APP_ROOT=None ):
  73.     try:
  74.         return send_email(to_address, subject, body_html, images, attachments, APP_ROOT=APP_ROOT)
  75.     except (MemoryError, SoftTimeLimitExceeded) as exc:
  76.         if isinstance(exc, MemoryError):
  77.             logger.error('MemoryError while attempting to send email with subject "%s" to "%s". Scheduling retry.' % (subject, to_address))
  78.         else:
  79.             logger.error('Exceeded Soft Time Limit attempting to send email with subject "%s" to "%s". Scheduling retry.' % (subject, to_address))
  80.         raise self.retry(exc=exc)
  81.     except MaxRetriesExceededError as exc:
  82.         logger.error('Retry limit reached attempting to send email with subject "%s" to "%s". Will not retry.' % (subject, to_address))
  83.         return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement