Python modules you should know: pydkim

May 08, 2012 at 04:40 PM | categories: Python, PyMYSK, Howto | View Comments

Next in our series of Python modules you should know is pydkim. This package is used to sign and verify email according to the DKIM standards from within Python programs.

Home page

Use

The pydkim module is a Python module that implements DKIM (DomainKeys Identified Mail) email signing and verification.

DomainKeys Identified Mail (DKIM) lets an organization take responsibility for a message that is in transit. Technically DKIM provides a method for validating a domain name identity that is associated with a message through cryptographic authentication.

Although DKIM is implemented in most MTA's, in some cases you have a setup where you do not want to run and manage an SMTP server yourself say for example if your Python application uses Amazon SES to send out email. So you can use pydkim within your email generation code to sign your messages before passing them to SES.

Installation

pip install pydkim

Usage

The package provides a command line interface as well as a Python Class.

Python Class

Sign a message

from email.message import Message

from dkim import sign

body = """Hi There,

This is a simple message that will be signed by pydkim

--The signer
"""
# compose a simple message
msg = Message()
msg['From'] = 'Sender <sender@topdog-software.com>'
msg['To'] = 'Recipient <recipient@example.com>'
msg['Subject'] = 'Test message'
msg.set_payload(body)

# sign the message
private_key = open('default.pem').read()
headers = ['To', 'From', 'Subject']
email = msg.as_string()
sig = sign(email, 'default', 'topdog-software.com', private_key, include_headers=headers)
print sig, email

Output:

DKIM-Signature: v=1; a=rsa-sha256; c=simple/simple;
 d=topdog-software.com; i=@topdog-software.com; q=dns/txt; s=default;
 t=1336488625; h=From : To : Subject;
 bh=skd2vA1wrCEzamCzKOvVKCaVhhpP1ihoQgGldgTSVUE=; b=vGQgSjJxkTZe+NZZl
lqszgxGshTcixlcfFos+XpLnAj1fnhA5SuBASoB4dVQUlVW76U5s9Dn1zSSsKH
6bCahl4oPqZaE5t6Ke5wpGwA+cBWZRrSuDDD/L8g9nYi04SVb+lMF9mJyQCeZj
pBtMomaOvGF8GNXsiKTFZR9RDv0wWw=
From: Sender <sender@topdog-software.com>
To: Recipient <recipient@example.com>
Subject: Test message

Hi There,

This is a simple message that will be signed by pydkim

--The signer

Verify a message (I use the same message signed above)

from dkim import verify

if verify(open('email.txt').read()):
    print "Email verified successfully"
True

Command line

Sign a message

dkimsign.py selector domain privatekeyfile [identity]

Verify a message

cat email.txt | dkimverify.py
echo $?

And there is more.

For details of the API please refer to the documentation. Happy DKIMing


blog comments powered by Disqus