PageRenderTime 37ms CodeModel.GetById 28ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 0ms

/askbot/utils/mail.py

https://github.com/chandankumar2199/askbot-devel
Python | 137 lines | 112 code | 3 blank | 22 comment | 6 complexity | 3a9e52354351398987ca8170d219e3bf MD5 | raw file
  1"""functions that send email in askbot
  2these automatically catch email-related exceptions
  3"""
  4import smtplib
  5import logging
  6from django.core import mail
  7from django.conf import settings as django_settings
  8from askbot.conf import settings as askbot_settings
  9from askbot import exceptions
 10from askbot import const
 11#todo: maybe send_mail functions belong to models
 12#or the future API
 13def prefix_the_subject_line(subject):
 14    """prefixes the subject line with the
 15    EMAIL_SUBJECT_LINE_PREFIX either from
 16    from live settings, which take default from django
 17    """
 18    prefix = askbot_settings.EMAIL_SUBJECT_PREFIX.strip()
 19    if prefix != '':
 20        subject = prefix + ' ' + subject
 21    return subject
 22
 23def extract_first_email_address(text):
 24    """extract first matching email address
 25    from text string
 26    returns ``None`` if there are no matches
 27    """
 28    match = const.EMAIL_REGEX.search(text)
 29    if match:
 30        return match.group(0)
 31    else:
 32        return None
 33
 34def thread_headers(post, orig_post, update):
 35    suffix_id = django_settings.SERVER_EMAIL
 36    if update == const.TYPE_ACTIVITY_ASK_QUESTION:
 37       id = "NQ-%s-%s" % (post.id, suffix_id)
 38       headers = {'Message-ID': id}
 39    elif update == const.TYPE_ACTIVITY_ANSWER:
 40       id = "NA-%s-%s" % (post.id, suffix_id)
 41       orig_id = "NQ-%s-%s" % (orig_post.id, suffix_id)
 42       headers = {'Message-ID': id,
 43                  'In-Reply-To': orig_id}
 44    elif update == const.TYPE_ACTIVITY_UPDATE_QUESTION:
 45       id = "UQ-%s-%s-%s" % (post.id, post.last_edited_at, suffix_id)
 46       orig_id = "NQ-%s-%s" % (orig_post.id, suffix_id)
 47       headers = {'Message-ID': id,
 48                  'In-Reply-To': orig_id}
 49    elif update == const.TYPE_ACTIVITY_COMMENT_QUESTION:
 50       id = "CQ-%s-%s" % (post.id, suffix_id)
 51       orig_id = "NQ-%s-%s" % (orig_post.id, suffix_id)
 52       headers = {'Message-ID': id,
 53                  'In-Reply-To': orig_id}
 54    elif update == const.TYPE_ACTIVITY_UPDATE_ANSWER:
 55       id = "UA-%s-%s-%s" % (post.id, post.last_edited_at, suffix_id)
 56       orig_id = "NQ-%s-%s" % (orig_post.id, suffix_id)
 57       headers = {'Message-ID': id,
 58                  'In-Reply-To': orig_id}
 59    elif update == const.TYPE_ACTIVITY_COMMENT_ANSWER:
 60       id = "CA-%s-%s" % (post.id, suffix_id)
 61       orig_id = "NQ-%s-%s" % (orig_post.id, suffix_id)
 62       headers = {'Message-ID': id,
 63                  'In-Reply-To': orig_id}
 64    else:
 65       # Unknown type -> Can't set headers
 66       return {}
 67
 68    return headers
 69
 70def send_mail(
 71            subject_line = None,
 72            body_text = None,
 73            recipient_list = None,
 74            activity_type = None,
 75            related_object = None,
 76            headers = None,
 77            raise_on_failure = False,
 78        ):
 79    """
 80    todo: remove parameters not relevant to the function
 81    sends email message
 82    logs email sending activity
 83    and any errors are reported as critical
 84    in the main log file
 85
 86    related_object is not mandatory, other arguments
 87    are. related_object (if given, will be saved in
 88    the activity record)
 89
 90    if raise_on_failure is True, exceptions.EmailNotSent is raised
 91    """
 92    prefix = askbot_settings.EMAIL_SUBJECT_PREFIX.strip() + ' '
 93    try:
 94        assert(subject_line is not None)
 95        subject_line = prefix + subject_line
 96        msg = mail.EmailMessage(
 97                        subject_line, 
 98                        body_text, 
 99                        django_settings.DEFAULT_FROM_EMAIL,
100                        recipient_list,
101                        headers = headers
102                    )
103        msg.content_subtype = 'html'
104        msg.send()
105        if related_object is not None:
106            assert(activity_type is not None)
107    except Exception, error:
108        logging.critical(unicode(error))
109        if raise_on_failure == True:
110            raise exceptions.EmailNotSent(unicode(error))
111
112def mail_moderators(
113            subject_line = '',
114            body_text = '',
115            raise_on_failure = False):
116    """sends email to forum moderators and admins
117    """
118    from django.db.models import Q
119    from askbot.models import User
120    recipient_list = User.objects.filter(
121                    Q(status='m') | Q(is_superuser=True)
122                ).filter(
123                    is_active = True
124                ).values_list('email', flat=True)
125    recipient_list = set(recipient_list)
126
127    from_email = ''
128    if hasattr(django_settings, 'DEFAULT_FROM_EMAIL'):
129        from_email = django_settings.DEFAULT_FROM_EMAIL
130
131    try:
132        mail.send_mail(subject_line, body_text, from_email, recipient_list)
133        pass
134    except smtplib.SMTPException, error:
135        logging.critical(unicode(error))
136        if raise_on_failure == True:
137            raise exceptions.EmailNotSent(unicode(error))