Sign emails with DKIM

5 years ago by David Grudl  

DKIM (DomainKeys Identified Mail) is a trustworthy email technology that also helps detect spoofed messages. The sent message is signed by the SMTP server with the private key of the sender's domain and this signature is stored in the email header. The recipient's server compares this signature with the public key stored in the domain's DNS records. By matching the signature, it is shown that the email actually originated from the sender's domain and that the message was not modified during the transmission of the message.

Nette\Mail supports DKIM since version 3.1. The usage is very simple:

$options = [
	'domain' => 'myweb.com',
	'selector' => 'lovenette',
	'privateKey' => file_get_contents('dkim.priv'),
//	'passPhrase' => '****',
	'testMode' => true,
];

$mailer = new Nette\Mail\SendmailMailer; // or SmtpMailer
$mailer->setSigner(new Nette\Mail\DkimSigner($options));
$mailer->send($mail);

Or you can use the configuration file:

mail:
	dkim:
		domain: myweb.com
	    selector: lovenette
	    privateKey: %appDir%/cert/dkim.priv
	    passPhrase: ...
	    testMode: ...

The selector is any alphanumeric lowercased string that is part of the DNS record.

You can generate a private and public key pair using openssl:

openssl genrsa -out dkim.priv 1024
openssl rsa -in dkim.priv -pubout > dkim.pub

You publish the public key by creating a TXT record in the DNS for the hostname created by concatenating the selector, the literal string ._domainkey. and the domain name. Using our example, that would be lovenette._domainkey.myweb.com. In some administrations the domain is already pre-filled.

The value of the TXT record can be created by concatenating the literal string v=DKIM1;t=s;k=rsa;p= and the public key that you copy from dkim.pub file. Remove the surrounding -----BEGIN PUBLIC KEY----- lines and wrap the key into a single long line:

v=DKIM1;t=s;k=rsa;p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDi5y95Mi8FZ8LOSmi7nA/EFhn4a4/Zq3BnnmPFdu1IvduDwMGRrRW5V9FKjXvr4AnUq7eMLRtEdWYRpR9BXLdCWiJ2N4yKJG7SEEir8DMYOGGeqJZoR/kWFiG++GW++sdhfukFflPusJjrWr+4Pc4/qxMSrqUk/rVdsSlTDDRy/QIDAQAB

You can use the MailTester service to check your DKIM settings.