Search code examples
pythonemaildkim

How can I verify an emails DKIM signature in Python?


Given a raw email, how can I validate the DKIM signature with Python?

Ideally I’d like more than just a pass / fail result, I’d like to know details of any issues.

I’ve found the dkimpy package, but the API isn’t obvious to me.


Solution

  • For a simple pass/fail validation:

    import dkim # dkimpy
    
    # Returns True/False
    res = dkim.verify(mail_data.encode())
    

    For something more nuanced you can do this:

    d = dkim.DKIM(mail_data.encode(), logger=None, minkey=1024, timeout=5, tlsrpt=False)
    
    # 
    try:
        d.verify()
        # If it fails, a `dkim.ValidationError` exception will be thrown with details
    except dkim.ValidationError as e:
        print(e)
    
    # dkim.ValidationError: body hash mismatch (got b'PXUrNdoTzGcLtd4doJs+CufsiNvxoM5Q3SUPGi00C+I=', expected b'ax9SInd7Z3AQjRzcZSnY6UK392QEvjnKrjhAnsqfDnM=')