Exemple #1
0
    def pks_from_emails(self, val):
        key = self.to_field_name or 'pk'

        try:
            self.queryset.filter(**{key: val})
            return val
        except (ValueError, TypeError):
            validate_email(val)
            return get_model_by_email(Recipient, val).pk
Exemple #2
0
    def test_get_by_email_existing(self):
        """Helper should return existing sender by e-mail address"""
        sender = Sender(email='*****@*****.**',
                        first_name='First',
                        last_name='Last')
        sender.save()

        fetched = get_model_by_email(Sender, '*****@*****.**')
        self.assertEqual(sender, fetched)
Exemple #3
0
def inbound_mail(request):
    """Parse an inbound Mailgun event (https://documentation.mailgun.com/
    quickstart-receiving.html) and save the data as models"""
    if not verify_mailgun_token(request.POST.get('token'),
                                request.POST.get('timestamp'),
                                request.POST.get('signature')):
        return HttpResponseForbidden('Failed Mailgun token validation.')

    required_fields = (
        'sender',
        'To',
        'Date',
    )
    missing_fields = [x for x in required_fields if x not in request.POST]

    if missing_fields:
        return HttpResponseBadRequest('Missing a requied field.')

    # Parse the out sender/recipient fields
    sender_address = parseaddr(request.POST.get('sender'))
    recipient_addresses = getaddresses(request.POST.get('To').split(','))

    if sender_address[1].split('@')[1] not in \
            settings.FOIATRACKER_ALLOWED_DOMAINS:
        msg = '"%s" is not authorized to use FOIAtracker.' % sender_address[1]
        return HttpResponseForbidden(msg)

    # Make a timezone-aware datetime from the Date field
    date_field = request.POST.get('Date')
    parsed_from_email = parsedate_tz(date_field)
    if parsed_from_email is not None:
        parsed_timestamp = mktime_tz(parsed_from_email)
        parsed_datetime = datetime.fromtimestamp(parsed_timestamp)
    else:
        parsed_datetime = datetime.now()
    sent = tz_aware_date(parsed_datetime)

    # Create a model for the email
    email = InboundEmail.objects.create(
        raw=request.POST.get('body-plain', ''),
        text=request.POST.get('stripped-text', ''),
        html=request.POST.get('body-html', ''),
        sent=sent,
        sender=get_model_by_email(Sender, sender_address[1]),
        subject=request.POST.get('subject', ''))

    # Setup M2M relationships for email recipeints
    for address in recipient_addresses:
        # For addresses that aren't e-mails, like 'undisclosed-recipients'
        if '@' not in address[1]:
            continue

        if address[1].split('@')[1] in settings.FOIATRACKER_ALLOWED_DOMAINS:
            continue

        recipient = get_model_by_email(Recipient, address[1])
        email.recipients.add(recipient)

    email.save()

    # Send a message to let the user know we're ready to classify
    tasks.email_prompt(email.pk)

    # Save file attachments to S3 and attach them to the message
    attachment_count = request.POST.get('attachment-count')

    if attachment_count is not None:
        try:
            num_attachments = int(attachment_count)

            for attachment_num in range(1, num_attachments + 1):
                attachment_key = 'attachment-%s' % attachment_num
                attached_file = request.FILES.get(attachment_key)

                if attached_file is None:
                    continue

                EmailAttachment.objects.create(
                    email=email,
                    stored_file=attached_file,
                    content_type=attached_file.content_type,
                    size=attached_file.size)
        except ValueError:
            pass

    return HttpResponse()
Exemple #4
0
 def test_get_by_email_new_no_name(self):
     """Helper should create new sender when e-mail doesn't match, changing
     None to '' """
     fetched = get_model_by_email(Sender, '*****@*****.**')
     self.assertEqual(fetched.email, '*****@*****.**')
Exemple #5
0
 def test_get_by_email_new(self):
     """Helper should create new sender when passed e-mail doesn't match"""
     fetched = get_model_by_email(Sender, '*****@*****.**')
     self.assertEqual(fetched.email, '*****@*****.**')