def send_campaign(self, campaign, fail_silently=False):
        from campaign.models import BlacklistEntry

        subject = campaign.template.subject
        text_template = template.Template(campaign.template.plain)
        if campaign.template.html is not None and campaign.template.html != "":
            html_template = template.Template(campaign.template.html)
        else:
            html_template = None

        recipients = []
        merge_vars = []

        for recipient_list in campaign.recipients.all():
            for recipient in recipient_list.object_list():
                # never send mail to blacklisted email addresses
                recipient_email = getattr(recipient,
                                          recipient_list.email_field_name)
                if not BlacklistEntry.objects.filter(
                        email=recipient_email).count(
                        ) and not recipient_email in recipients:
                    recipients.append({'email': recipient_email})

                    context = MailContext(recipient)
                    if campaign.online:
                        context.update({
                            'view_online_url':
                            reverse("campaign_view_online",
                                    kwargs={'object_id': campaign.pk}),
                            'site_url':
                            Site.objects.get_current().domain,
                            'recipient_email':
                            recipient_email
                        })
                    the_merge_vars = []
                    for k, v in context.flatten().items():
                        the_merge_vars.append({'name': k, 'content': v})
                    merge_vars.append({
                        'rcpt': recipient_email,
                        'vars': the_merge_vars
                    })

        from_email = self.get_from_email(campaign)

        try:
            mandrill_client = mandrill.Mandrill(settings.MANDRILL_API_KEY)
            message = {
                'auto_html': False,
                'auto_text': False,
                'from_email': from_email,
                'important': False,
                'inline_css': False,
                'merge': True,
                'merge_vars': merge_vars,
                'metadata': {
                    'capaign_id': campaign.pk
                },
                'preserve_recipients': False,
                'subject': subject,
                'text': text_template.render(Context()),
                'to': recipients,
                'track_opens': True,
                'view_content_link': False
            }

            if html_template:
                message['html'] = html_template.render(Context())

            # update data with user supplied values from settings
            message.update(getattr(settings, 'MANDRILL_API_SETTINGS', {}))

            result = mandrill_client.messages.send(message=message, async=True)
            return len(result)

        except mandrill.Error as e:
            logger.error('Mandrill error: %s - %s' % (e.__class__, e))
            if not fail_silently:
                raise e
Esempio n. 2
0
    def send_campaign(self, campaign, fail_silently=False):
        from campaign.models import BlacklistEntry

        subject = campaign.template.subject
        text_template = template.Template(campaign.template.plain)
        if campaign.template.html is not None and campaign.template.html != "":
            html_template = template.Template(campaign.template.html)
        else:
            html_template = None

        success_count = 0
        recipients = []
        recipient_vars = {}

        for recipient_list in campaign.recipients.all():
            for recipient in recipient_list.object_list():
                # never send mail to blacklisted email addresses
                recipient_email = getattr(recipient,
                                          recipient_list.email_field_name)
                if not BlacklistEntry.objects.filter(
                        email=recipient_email).count(
                        ) and not recipient_email in recipients:
                    recipients.append(recipient_email)

                    context = MailContext(recipient)
                    if campaign.online:
                        context.update({
                            'view_online_url':
                            reverse("campaign_view_online",
                                    kwargs={'object_id': campaign.pk}),
                            'site_url':
                            Site.objects.get_current().domain,
                            'recipient_email':
                            recipient_email
                        })
                    the_recipient_vars = {}
                    for k, v in context.flatten().items():
                        the_recipient_vars.update({k: v})
                    recipient_vars.update(
                        {recipient_email: the_recipient_vars})

        # assemble recipient data into batches of self.BATCH_SIZE
        batches = []
        batch_r = []
        batch_v = {}
        for r in recipients:
            batch_r.append(r)
            batch_v[r] = recipient_vars[r]
            if len(batch_r) >= self.BATCH_SIZE:
                batches.append((batch_r, batch_v))
                batch_r = []
                batch_v = {}
        if len(batch_r):
            batches.append((batch_r, batch_v))

        for recipients, recipient_vars in batches:
            from_email = self.get_from_email(campaign)
            from_domain = from_email.split('@')[-1]
            from_header = self.get_from_header(campaign, from_email)
            api_url = getattr(
                settings, 'MAILGUN_API_URL',
                'https://api.mailgun.net/v3/%s/messages') % from_domain
            auth = ("api", settings.MAILGUN_API_KEY)
            data = {
                'to': recipients,
                'from': from_header,
                'recipient-variables': json.dumps(recipient_vars),
                'subject': subject,
                'text': text_template.render(Context()),
            }

            if html_template:
                data['html'] = html_template.render(Context())

            # update data with user supplied values from settings
            data.update(getattr(settings, 'MAILGUN_API_SETTINGS', {}))

            try:
                result = requests.post(api_url, auth=auth, data=data)
                if result.status_code == 200:
                    success_count += len(recipients)
                else:
                    raise Exception(result.text)

            except Exception as e:
                logger.error('Mailgun error: %s - %s' % (e.__class__, e))
                if not fail_silently:
                    raise e

        return success_count
Esempio n. 3
0
    def send_campaign(self, campaign, fail_silently=False):
        from campaign.models import BlacklistEntry

        subject = campaign.template.subject
        text_template = template.Template(campaign.template.plain)
        if campaign.template.html is not None and campaign.template.html != u"":
            html_template = template.Template(campaign.template.html)
        else:
            html_template = None

        success_count = 0
        recipients = []
        recipient_vars = {}

        for recipient_list in campaign.recipients.all():
            for recipient in recipient_list.object_list():
                # never send mail to blacklisted email addresses
                recipient_email = getattr(recipient, recipient_list.email_field_name)
                if not BlacklistEntry.objects.filter(email=recipient_email).count() and not recipient_email in recipients:
                    recipients.append(recipient_email)

                    context = MailContext(recipient)
                    if campaign.online:
                        context.update({
                            'view_online_url': reverse("campaign_view_online", kwargs={'object_id': campaign.pk}),
                            'site_url': Site.objects.get_current().domain,
                            'recipient_email': recipient_email
                        })
                    the_recipient_vars = {}
                    for k, v in context.flatten().iteritems():
                        the_recipient_vars.update({k: v})
                    recipient_vars.update({recipient_email: the_recipient_vars})

        # assemble recipient data into batches of self.BATCH_SIZE
        batches = []
        batch_r = []
        batch_v = {}
        for r in recipients:
            batch_r.append(r)
            batch_v[r] = recipient_vars[r]
            if len(batch_r) >= self.BATCH_SIZE:
                batches.append((batch_r, batch_v))
                batch_r = []
                batch_v = {}
        if len(batch_r):
            batches.append((batch_r, batch_v))

        for recipients, recipient_vars in batches:
            from_email = self.get_from_email(campaign)
            from_domain = from_email.split('@')[-1]
            from_header = self.get_from_header(campaign, from_email)
            api_url = getattr(settings, 'MAILGUN_API_URL', 'https://api.mailgun.net/v3/%s/messages') % from_domain
            auth = ("api", settings.MAILGUN_API_KEY)
            data = {
                'to': recipients,
                'from': from_header,
                'recipient-variables': json.dumps(recipient_vars),
                'subject': subject,
                'text': text_template.render(Context()),
            }

            if html_template:
                data['html'] = html_template.render(Context())

            # update data with user supplied values from settings
            data.update(getattr(settings, 'MAILGUN_API_SETTINGS', {}))

            try:
                result = requests.post(api_url, auth=auth, data=data)
                if result.status_code == 200:
                    success_count += len(recipients)
                else:
                    raise Exception(result.text)

            except Exception as e:
                logger.error('Mailgun error: %s - %s' % (e.__class__, e))
                if not fail_silently:
                    raise e

        return success_count
Esempio n. 4
0
    def send_campaign(self, campaign, fail_silently=False):
        from campaign.models import BlacklistEntry

        subject = campaign.template.subject
        text_template = template.Template(campaign.template.plain)
        if campaign.template.html is not None and campaign.template.html != "":
            html_template = template.Template(campaign.template.html)
        else:
            html_template = None

        recipients = []
        merge_vars = []

        for recipient_list in campaign.recipients.all():
            for recipient in recipient_list.object_list():
                # never send mail to blacklisted email addresses
                recipient_email = getattr(recipient, recipient_list.email_field_name)
                if not BlacklistEntry.objects.filter(email=recipient_email).count() and not recipient_email in recipients:
                    recipients.append({'email': recipient_email})

                    context = MailContext(recipient)
                    if campaign.online:
                        context.update({'view_online_url': reverse("campaign_view_online", kwargs={
                                            'object_id': campaign.pk}),
                                        'site_url': Site.objects.get_current().domain,
                                        'recipient_email': recipient_email})
                    the_merge_vars = []
                    for k, v in context.flatten().items():
                        the_merge_vars.append({'name': k, 'content': v})
                    merge_vars.append({'rcpt': recipient_email, 'vars': the_merge_vars})

        from_email = self.get_from_email(campaign)

        try:
            mandrill_client = mandrill.Mandrill(settings.MANDRILL_API_KEY)
            message = {
             'auto_html': False,
             'auto_text': False,
             'from_email': from_email,
             'important': False,
             'inline_css': False,
             'merge': True,
             'merge_vars': merge_vars,
             'metadata': {'capaign_id': campaign.pk},
             'preserve_recipients': False,
             'subject': subject,
             'text': text_template.render(Context()),
             'to': recipients,
             'track_opens': True,
             'view_content_link': False
            }

            if html_template:
                message['html'] = html_template.render(Context())

            # update data with user supplied values from settings
            message.update(getattr(settings, 'MANDRILL_API_SETTINGS', {}))

            result = mandrill_client.messages.send(message=message, async=True)
            return len(result)

        except mandrill.Error as e:
            logger.error('Mandrill error: %s - %s' % (e.__class__, e))
            if not fail_silently:
                raise e