@@ -0,0 +1,2517 @@
+import logging%0Aimport requests%0Afrom django.conf import settings%0Afrom django.core.management.base import BaseCommand, CommandError%0Afrom campaign.models import BlacklistEntry%0A%0Alogger = logging.getLogger('django.campaign')%0A%0A%0Aclass Command(BaseCommand):%0A    %22%22%22%0A    This command fetches all bounces from the Mailgun API and stores them%0A    in the local blacklist. This ensures that campaign doesn't send a mail to a%0A    bad recipient address more than once and that helps improving%0A    the deliverability rate.%0A%0A    This backend assumes, that your Mailgun API-Key is configured in::%0A%0A        settings.MAILGUN_API_KEY%0A%0A    Additionally you need to set all domains, for which bounces should%0A    be collected in::%0A%0A        settings.MAILGUN_DOMAINS%0A%0A    %22%22%22%0A    help = %22fetch bounces from mailgun and store in local blacklist%22%0A%0A    def handle(self, *args, **options):%0A        processed = 0%0A        valid = 0%0A        domain_list = getattr(settings, 'MAILGUN_DOMAINS', %5B%5D)%0A%0A        if not len(domain_list):%0A            raise CommandError('you need to confgure the MAILGUN_DOMAINS setting')%0A%0A        for domain in domain_list:%0A            try:%0A                api_url = getattr(settings, 'MAILGUN_API_URL', 'https://api.mailgun.net/v3/%25s/bounces') %25 domain%0A                x, y = self._fetch_rejects(api_url)%0A                processed += x%0A                valid += y%0A            except Exception as e:%0A                logger.error('Mailgun error: %25s - %25s' %25 (e.__class__, e))%0A                raise CommandError(e)%0A%0A        self.stdout.write(%22processed: %25s%22 %25 processed)%0A        self.stdout.write(%22valid: %25s%22 %25 valid)%0A%0A    def _fetch_rejects(self, url):%0A        processed = 0%0A        valid = 0%0A%0A        auth = (%22api%22, settings.MAILGUN_API_KEY)%0A        response = requests.get(url, auth=auth)%0A%0A        if response.status_code == 200:%0A            for reject in response.json()%5B'items'%5D:%0A                processed += 1%0A                if int(reject%5B'code'%5D) %3E= 500:%0A                    valid += 1%0A                    BlacklistEntry.objects.get_or_create(%0A                        email=reject%5B'address'%5D,%0A                        defaults=%7B'reason': reject%5B'error'%5D%7D%0A                    )%0A        else:%0A            logger.warning('Mailgun response: %25s' %25 result.status_code)%0A%0A        pagination = response.json()%5B%22paging%22%5D%0A        if pagination.get(%22next%22) != pagination.get(%22previous%22):%0A            x, y = self._fetch_rejects(pagination.get(%22next%22))%0A            processed += x%0A            valid += y%0A%0A        return processed, valid%0A

add management command to fetch bounces from mailgun api