Skip to content

// frameworks and platforms

Via API

Django email verification with pingutil

Django's EmailField checks syntax only, so a signup form will happily accept a temp-mail address or a mistyped domain, and the first email you send bounces. Putting the pingutil call in the form's clean_email method turns those into ordinary form errors, shown next to the field like any other validation message.

Where it connects: Django form field cleaning: clean_email() on the signup Form

What goes wrong without it

  • EmailField accepts anything shaped like an address, including mailinator domains and gmial.com typos.
  • Our trial abuse comes from the same handful of throwaway services, and the list we hard-coded is out of date.
  • We want work emails routed to sales, but we cannot tell a company address from a personal one in the form.

What you can do with Django and pingutil

  • Field errors for throwaway addresses

    Raise forms.ValidationError from clean_email when verdict.is_spam is true. Django renders it next to the email field and form.is_valid() returns False, so the view never creates the user.

  • Typo suggestions from the mailbox check

    When /v1/verify says invalid and returns did_you_mean, include the suggestion in the error message so the user can correct it in one step.

  • Route work emails after signup

    Keep the lookup category on the form and read it in the view after is_valid(): company addresses can be pushed to your CRM, free webmail ones to self-serve onboarding.

Set it up

  1. 1

    Create an API key in the pingutil dashboard and expose it as settings.PINGUTIL_KEY, read from the environment.

  2. 2

    Configure a cache backend (Redis, Memcached or the database cache) so the 429 backoff and domain categories are shared across workers.

  3. 3

    Add a clean_email method to your signup Form that calls /v1/lookup with skip_enrichment: True and raises ValidationError on verdict.is_spam.

  4. 4

    Optionally call /v1/verify in the same method and raise ValidationError with the did_you_mean hint when status is invalid.

  5. 5

    In the view, call form.is_valid() as usual and save form.email_check with the new user.

accounts/forms.py
# accounts/forms.py  (Django 5.x / 6.x)
import logging

import requests
from django import forms
from django.conf import settings
from django.core.cache import cache

log = logging.getLogger(__name__)
API = "https://pingutil.com/v1"
session = requests.Session()  # keeps the TLS connection warm between requests


def pingutil(path, payload, timeout):
    """Parsed JSON, or None when pingutil is slow, down or rate limited (fail open)."""
    if cache.get("pingutil:backoff"):
        return None
    try:
        r = session.post(
            f"{API}{path}",
            json=payload,
            timeout=timeout,  # (connect, read) in seconds
            headers={"Authorization": f"Bearer {settings.PINGUTIL_KEY}"},
        )
    except requests.RequestException:
        return None
    if r.status_code == 429:
        try:
            wait = int(r.json().get("retry_after_seconds", 60))
        except ValueError:
            wait = 60
        cache.set("pingutil:backoff", True, timeout=max(wait, 1))
        return None
    if r.status_code == 401:
        log.error("pingutil rejected the API key")
    return r.json() if r.ok else None


class SignupForm(forms.Form):
    email = forms.EmailField()
    password = forms.CharField(widget=forms.PasswordInput, min_length=12)

    def clean_email(self):
        email = self.cleaned_data["email"].strip().lower()
        domain = email.rsplit("@", 1)[1]

        # Domain category is cached for a day; the per-address verdict never is.
        if cache.get(f"pingutil:category:{domain}") == "disposable":
            raise forms.ValidationError("Please use a permanent email address.", code="disposable")

        lookup = pingutil("/lookup", {"input": email, "skip_enrichment": True}, (1, 2))
        if lookup:
            cache.set(f"pingutil:category:{lookup['domain']}", lookup["category"], 86400)
            if lookup["verdict"]["is_spam"]:
                raise forms.ValidationError(
                    "This email address can't be used. Please use a different one.", code="spam"
                )

        check = pingutil("/verify", {"email": email}, (1, 5))
        if check and check["status"] == "invalid":
            hint = f" Did you mean {check['did_you_mean']}?" if check["did_you_mean"] else ""
            raise forms.ValidationError("That mailbox does not exist." + hint, code="mailbox")

        # Read in the view after is_valid(): route work emails, queue risky/unknown for review.
        self.email_check = {
            "category": lookup["category"] if lookup else None,
            "status": check["status"] if check else None,
        }
        return email

What to do with each result

pingutil resultAction in Django
verdict.is_spam: trueRaise forms.ValidationError(code="spam"); the form re-renders with the error.
status: invalid with did_you_meanRaise ValidationError that includes the suggested address.
category: companyAfter is_valid(), create a lead in your CRM or assign the account to sales.
status: risky or unknownSave the user with a flag and hold trial credits until the confirmation link is clicked.

Limits to plan for

  • clean_email runs inside the request, so the worker waits on pingutil. The (connect, read) timeouts bound each call; requests' read timeout is per read, not a total deadline, so keep the values small.
  • Mailbox checks cannot confirm catch-all domains or servers that refuse to answer: those come back risky or unknown, never valid.
  • Per-account defaults: 60 requests a minute, 300 verified addresses and 2,000 lookups a day (3,000 and 30,000 a month). A 429 sets the cache backoff and the form passes the address through. Those are Free plan limits; Enterprise has custom limits.

Django documentation

Django is a trademark of its owner. This integration uses Django's documented extension points; it is not an official Django app.

Common questions

Should this be a model validator or a form clean method?
A form clean method. Model validators also run on admin edits and in full_clean calls from scripts, where an HTTP call to an external API is usually unwanted. The signup form is the one place a new address enters.
Does this work with Django REST Framework?
Yes, the same helper fits a serializer's validate_email method; raise serializers.ValidationError instead of forms.ValidationError.

Stop bad addresses in Django today

Sign in with your email, create an API key and paste it into the step above. Test on a few real addresses first: the live demo shows exactly what your Django setup will receive.