How to configure DKIM on Postfix server

Setting up DKIM (DomainKeys Identified Mail) on a server is essential for authenticating emails sent from that server. This ensures that the email content has not been altered during transit.

To get everything working properly, start by updating your packages and installing the necessary tools.

apt-get update
apt-get install opendkim opendkim-tools

Open the opendkim.conf file for configuration.

nano /etc/opendkim.conf

And add the following lines, taking care to replace the domain:

Socket  local:/var/spool/postfix/opendkim/opendkim.sock
Canonicalization        relaxed/simple
Mode                    svDomain                  mydomain.com
KeyFile                 /etc/opendkim/keys/mydomain.com/mail.private
Selector                mail

Create the folder that will hold the keys we will generate next.

mkdir -p /etc/opendkim/keys/mydomain.com

Then generate the set of keys.

opendkim-genkey -s mail -d mydomain.com -D /etc/opendkim/keys/mydomain.com

Assign the opendkim folder and its subfolders to the opendkim user.

chown -R opendkim: /etc/opendkim

Create the folder /var/spool/postfix/opendkim with the right permissions.

mkdir -m o-rwx /var/spool/postfix/opendkim

And change the ownership of the folder.

chown opendkim:opendkim /var/spool/postfix/opendkim

We will now configure Postfix to work with OpenDKIM. Edit the main.cf file and add these lines at the end.

nano /etc/postfix/main.cf

milter_protocol = 2
milter_default_action = accept
smtpd_milters = unix:opendkim/opendkim.sock
non_smtpd_milters = $smtpd_milters

Add the postfix user to the opendkim group.

adduser postfix opendkim

Restart OpenDKIM and Postfix to load the new configurations.

systemctl restart opendkim postfix

Read the mail.txt file that contains the DNS zone configuration.

cat /etc/opendkim/keys/mydomain.com/mail.txt

Copy the entire content of mail.txt, paste it into a notepad, and reformat it properly to make it compatible with a DNS provider. The problem is that the key gets split into two parts in mail.txt.

Example :
mail._domainkey IN      TXT     ( "v=DKIM1; h=sha256; k=rsa; "
"p=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
"YYYYYYYYYYYYYYYYYYY" )  ; ----- DKIM key mail for mydomain.com

Should become:

mail._domainkey IN TXT ("v=DKIM1; h=sha256; k=rsa; p=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXYYYYYYYYYYYYYYYYYYY")

Go to your DNS provider and add a new TXT entry containing the “clean” part we just made in the notepad.

From there, DKIM is functional and can be verified from sites like mxtoolbox or dnschecker. When they ask you to enter the selector, it refers to the Selector argument that we previously configured in the /etc/opendkim.conf file.

Leave a Comment