Postfix for Gmail

From NixOS Wiki

This is how to setup Postfix to use Gmail as a relay host, so it can send email via Gmail, e.g. for output of cronjobs etc.

Setup sops-nix


Make sure you can create secrets in /run/secrets before continuing.

Add a "postfix/sasl_passwd" secret

Create an app password specifically for this postfix installation at (logged in as you).

You end up with a 16 character string separated by spaces. Put that in a sops secret:

 nix-shell -p sops --run "sops /etc/nixos/sops-secrets.yaml"

Create this entry, using the 16 character string without spaces (Don't use the "abcdefghjklmnopq" string below. It won't work :-) ):

     sasl_passwd: '[]:587'

Configure Postfix

 sops.secrets."postfix/sasl_passwd".owner =;
 services.postfix = {
   enable = true;
   relayHost = "";
   relayPort = 587;
   config = {
     smtp_use_tls = "yes";
     smtp_sasl_auth_enable = "yes";
     smtp_sasl_security_options = "";
     smtp_sasl_password_maps = "texthash:${config.sops.secrets."postfix/sasl_passwd".path}";
     # optional: Forward mails to root (e.g. from cron jobs, smartd)
     # to me privately and to my work email:
     virtual_alias_maps = "inline:{ {,} }";


 sudo nixos-rebuild switch

Send an email explicitly to

 nix-shell -p mailutils --run \
   'echo "This is a test email." | mail -s "Test Email from NixOS"'

Send an email explicitly to root that gets sent to and (if you opted in for virtual_alias_maps)

 nix-shell -p mailutils --run \
   'echo "This is a test email." | mail -s "Test Email from NixOS to root" root'

Source / Credit

This post came out of this discussion.