Beispiel #1
0
    def notify_via_e_mail(self, sender, recipient_list, template, cc_list=[],
                          bcc_list=[], reply_to=None):
        """
        Send an email to the requester notifying them that their
        allocation has been processed.
        """
        if not sender and recipient_list:
            # TODO (shauno): log this problem
            raise Exception

        plaintext = get_template(template)
        ctx = Context({"request": self})
        text = plaintext.render(ctx)
        subject, body = text.split('')
        email = EmailMessage(
            subject.strip(),
            body,
            sender,
            recipient_list,
            cc=cc_list
        )

        if bcc_list:
            email.bcc = bcc_list

        if reply_to:
            email.headers = {'Reply-To': reply_to}

        email.send()
Beispiel #2
0
def send_notification(sender,
                      subject,
                      mail_content,
                      template_name,
                      recipient_list,
                      cc_list,
                      bcc_list,
                      reply_to=None):
    """
    send notification
    :param sender:
    :param subject:
    :param mail_content:
    :param template_name:
    :param recipient_list:
    :param cc_list:
    :param bcc_list:
    :param reply_to:
    """
    template = get_template(template_name)
    ctx = Context({'request': mail_content})
    message = template.render(ctx)
    email = EmailMessage(subject=subject,
                         body=message,
                         from_email=sender,
                         to=recipient_list)
    if cc_list:
        email.cc = cc_list
    if bcc_list:
        email.bcc = bcc_list
    if reply_to:
        email.headers = {'Reply-To': reply_to}
    email.send()
Beispiel #3
0
def contactmail(request):
    # Check if the page was reached legitimately.
    if not request.POST:
        raise Http404
    if not any(x in request.POST for x in ["name", "from", "topic", "msg"]):
        raise Http404

    from_email = request.POST["from"]
    subject = "ELASPIC: " + request.POST["topic"]

    message = "<i>From: " + html.strip_tags(request.POST["name"]) + "<br />"
    message += "Email: " + html.strip_tags(from_email) + "</i><br /><br />"
    message += "Topic: <b>" + html.strip_tags(
        request.POST["topic"]) + "</b><br /><br />"
    message += "Message: <br /><b>"
    message += html.strip_tags(request.POST["msg"]).replace("\n", "<br/>")
    message += "</b>"

    email = EmailMessage(
        subject,
        message,
        "*****@*****.**",
        [a[1] for a in settings.ADMINS],
    )
    email.headers = {
        "Reply-To": from_email,
        "From": "*****@*****.**"
    }
    email.content_subtype = "html"

    try:
        email.send()
    except Exception:
        error = True
        response = "Sorry, there was an error with your request. Please try again."
    else:
        error = False
        response = ("Your message has been successfully sent. "
                    "Allow us 2 business days to get back to you.")
    return HttpResponse(
        json.dumps({
            "response": response,
            "error": error
        }),
        content_type="application/json",
    )
Beispiel #4
0
def abuse_reports():
    '''
    Generate a report for abuse reports for campaigns sent
    over the last 4 weeks.
    This task is meant to be run once a week
    '''
    # Only run on production
    if settings.SITE_ENVIRONMENT != 'prod':
        return

    from datetime import datetime, timedelta
    from django.core.mail import EmailMessage
    from djangoplicity.mailinglists.models import MailChimpList
    from django.contrib.sites.models import Site

    email_from = '*****@*****.**'
    email_reply_to = '*****@*****.**'
    email_to = ['*****@*****.**', '*****@*****.**']

    #  Calculate the date 4 weeks ago
    start_date = datetime.today() - timedelta(weeks=4)
    #  Calculate the date one week ago
    week_ago = datetime.today() - timedelta(weeks=1)

    body = ''
    n_complaints = 0

    for ml in MailChimpList.objects.all():
        logger.debug('Will run campaigns.all for list %s', ml.list_id)
        try:
            response = ml.connection(
                'campaigns.all',
                get_all=True,
                list_id=ml.list_id,
                since_send_time=start_date.isoformat(),
                fields='campaigns.id,campaigns.settings.title')
        except HTTPError as e:
            logger.error('campaigns.all: %s', e.response.text)
            raise e

        if response['total_items'] == 0:
            continue

        content = ''

        for campaign in response['campaigns']:

            logger.debug('Will run reports.abuse_reports.all for campaign %s',
                         campaign['id'])
            try:
                response = ml.connection('reports.abuse_reports.all',
                                         campaign_id=campaign['id'],
                                         since_send_time=week_ago.isoformat())
            except HTTPError as e:
                logger.error('reports.abuse_reports.all: %s', e.response.text)
                raise e

            if response['total_items'] == 0:
                continue

            n_complaints += response['total_items']

            if not content:
                name = 'MailChimp List: %s' % ml.name
                content = '=' * len(name) + '\n'
                content += name + '\n'
                content += '=' * len(name) + '\n'

            title = 'Campaign: %s (%d complaints)' % (
                campaign['settings']['title'], response['total_items'])
            content += '\n' + title + '\n'
            content += '-' * len(title) + '\n'

            for complaint in response['abuse_reports']:
                try:
                    member = ml.connection(
                        'lists.members.get',
                        complaint['list_id'],
                        complaint['email_id'],
                    )
                except HTTPError as e:
                    logger.error('lists.members.get: %s', e.response.text)
                    raise e

                content += '%s Reason: %s' % (
                    member['email_address'],
                    member['unsubscribe_reason']) + '\n'

        body += content

    if body:
        logger.info('Sending report for %d complaints' % n_complaints)
        # Prepare the message:
        msg = EmailMessage()
        msg.headers = {'Reply-To': email_reply_to}
        msg.subject = '%d complaints reported in MailChimp for %s' % (
            n_complaints, Site.objects.get_current().domain)
        msg.from_email = email_from
        msg.to = email_to
        msg.body = body

        msg.send()
    else:
        logger.info('No Mailchimp Complaints found')