One place for hosting & domains

      Postfix

      Cómo instalar y configurar Postfix como servidor SMTP de solo envío en Ubuntu 18.04


      El autor seleccionó la Free and Open Source Fund para recibir una donación como parte del programa Write for DOnations.

      Introducción

      Postfix es un agente de transferencia de correo (MTA), una aplicación que se utiliza para enviar y recibir correos electrónicos. Se puede configurar para que solo se pueda utilizar para enviar correos electrónicos mediante una aplicación local.  Esto es útil en situaciones en las que necesita enviar notificaciones por correo electrónico de sus aplicaciones de forma regular o, simplemente, si tiene mucho tráfico saliente que un proveedor de servicios de correo electrónico externo no permite.  También es una alternativa más ligera a la ejecución de un servidor SMTP completo que mantiene la funcionalidad necesaria.

      En este tutorial, instalará y configurará Postfix como servidor SMTP de solo envío. También solicitará certificados TLS gratuitos de Let´s Encrypt para su dominio y cifrará los correos electrónicos salientes con ellos.

      Requisitos previos

      • Un servidor de Ubuntu 18.04 configurado conforme a la Configuración inicial de servidores para Ubuntu 18.04, con un non-root user.
      • Un nombre de dominio registrado por completo. Para este tutorial, se utilizará your_domain en todo momento. Puede adquirir un nombre de dominio en Namecheap, obtener uno gratuito en Freenom o utilizar un registrador de dominios que elija.
      • Un registro DNS con your_domain orientado a la dirección IP pública de su servidor. Puede utilizar esta introducción al DNS de DigitalOcean para obtener más información sobre cómo agregarlos.

      Nota: El nombre de host de su servidor y el nombre de su Droplet deben coincidir con your_domain, dado que DigitalOcean establece registros de PTR automáticamente para la dirección IP del Droplet de acuerdo con su nombre.

      Puede verificar el nombre de host del servidor al escribir hostname en el símbolo del sistema. El resultado debe coincidir con el nombre que le dio al Droplet al crearlo.

      Paso 1: Instalar Postfix

      En este paso, instalará Postfix. Lo más rápido es instalar el paquete mailutils, que agrupa Postfix con algunos programas complementarios que usará para probar el envío de correos electrónicos.

      Primero, actualice la base de datos del paquete:

      A continuación, instale Postfix al ejecutar el siguiente comando:

      • sudo apt install mailutils

      Cerca del final del proceso de instalación, se le presentará la ventana de configuración de Postfix:

      Seleccione Internet Site en el menú y, luego, presione TAB para seleccionar<Ok>y, luego, presione ENTER.

      La opción predeterminada es Internet Site. Es la opción recomendada para su caso de uso, por lo tanto, presione TAB y, luego, ENTER. Si solo ve el texto de la descripción, presione TAB para seleccionar OK y, luego, ENTER.

      Si no se muestra automáticamente, ejecute el siguiente comando para iniciarlo:

      • sudo dpkg-reconfigure postfix

      Luego, recibirá otro mensaje de configuración con respecto a System mail name (el nombre de correo del sistema):

      Ingrese su nombre de dominio y, luego, presione TAB para seleccionar<Ok>y, luego, ENTER.

      El nombre de correo del sistema debe ser el mismo que el que asignó a su servidor al crearlo. Cuando termine, presione TAB y, luego, ENTER.

      Ahora, tiene Postfix instalado y está listo para comenzar a configurarlo.

      Paso 2: Configurar Postfix

      En este paso, configurará Postfix para enviar y recibir correos electrónicos únicamente del servidor en el que se está ejecutando; es decir, desde localhost.

      Para que eso suceda, Postfix se debe configurar para que escuche únicamente en la interfaz de bucle invertido, que es la interfaz de red virtual que utiliza el servidor para comunicarse internamente.  Para realizar los cambios necesarios, deberá editar el archivo de configuración principal de Postfix, denominado main.cf, que se encuentra en etc/postfix.

      Ábralo para modificarlo con su editor de texto favorito:

      • sudo nano /etc/postfix/main.cf

      Busque las siguientes líneas:

      /etc/postfix/main.cf

      . . .
      mailbox_size_limit = 0
      recipient_delimiter = +
      inet_interfaces = all
      . . .
      

      Establezca el valor de inet_interfaces en loopback-only:

      /etc/postfix/main.cf

      . . .
      mailbox_size_limit = 0
      recipient_delimiter = +
      inet_interfaces = loopback-only
      . . .
      

      Otra directiva que deberá modificar es mydestination, que se utiliza para especificar la lista de dominios que se entregan a través del transporte de entrega de correo local_transport. Por defecto, los valores son similares a los siguientes:

      /etc/postfix/main.cf

      . . .
      mydestination = $myhostname, your_domain, localhost.com, , localhost
      . . .
      

      Cambie la línea para que tenga el siguiente aspecto:

      /etc/postfix/main.cf

      . . .
      mydestination = localhost.$mydomain, localhost, $myhostname
      . . .
      

      Si su dominio, en realidad, es un subdominio y desea que los mensajes de correo electrónico se vean como si se enviaran del dominio principal, puede añadir la siguiente línea al final de main.cf:

      /etc/postfix/main.cf

      ...
      masquerade_domains = your_main_domain
      

      La configuración opcional de masquerade_domains especifica para qué dominios se eliminará la parte de subdominio en la dirección de correo electrónico.

      Cuando termine, guarde y cierre el archivo.

      Nota: Si aloja varios dominios en un único servidor, los demás también se pueden pasar a Postfix al utilizar la directiva mydestination.

      A continuación, reinicie Postfix al ejecutar el siguiente comando:

      • sudo systemctl restart postfix

      Configuró Postfix para que solo envíe correos electrónicos desde su servidor. Ahora, lo probará al enviar un mensaje de ejemplo a una dirección de correo electrónico.

      Paso 3: Probar el servidor SMTP

      En este paso, probará si Postfix puede enviar correos electrónicos a una cuenta de correo electrónico externa usando el comando mail, que es parte del paquete mailutils que instaló en el primer paso.

      Para enviar un correo electrónico de prueba, ejecute el siguiente comando:

      • echo "This is the body of the email" | mail -s "This is the subject line" your_email_address

      Puede cambiar el cuerpo y el asunto del correo electrónico a su gusto. Recuerde sustituir your_email_address por una dirección de correo electrónico válida a la que pueda acceder.

      Ahora, revise el correo en la dirección de correo electrónico a la que envió este mensaje. Debería ver el mensaje en su bandeja de entrada. Si no lo ve, revise su carpeta de correo no deseado. En este punto, los correos electrónicos que envía no están cifrados, lo que hace que los proveedores de servicios piensen que es probable que sean correos no deseados.  Configurará el cifrado más adelante, en el paso 5.

      Si recibe un error del comando mail, o si no recibió un mensaje después de un período prolongado, compruebe que la configuración de Postfix que modificó sea válida y que el nombre de su servidor y el nombre de host estén establecidos con el nombre de su dominio.

      Observe que, con esta configuración, la dirección del campo From de los correos electrónicos de prueba que envíe tendrá el formato your_user_name@your_domain​​, en el que your_user_name es el nombre del usuario del servidor con el que ejecutó el comando.

      En este punto, envió un correo electrónico desde su servidor y verificó que se haya recibido correctamente. En el siguiente paso, configurará el reenvío de correos electrónicos para root.

      Paso 4: Reenviar correos del sistema

      En este paso, configurará el reenvío de correos electrónicos para el root user a fin de que los mensajes generados por el sistema que se le envíen en su servidor se reenvíen a una dirección de correo electrónico externa.

      El archivo /etc/aliases contiene una lista de nombres alternativos de destinatarios de correo electrónico. Ábralo​​​ para editarlo:

      En su estado predeterminado, tiene el siguiente aspecto:

      /etc/aliases

      # See man 5 aliases for format
      postmaster:    root
      

      La única directiva presente especifica que los correos electrónicos generados por el sistema se envíen a root.

      Añada la siguiente línea al final del archivo:

      /etc/aliases

      ...
      root:          your_email_address
      

      Con esta línea, especifica que los correos electrónicos enviados al root user se reenvíen a una dirección de correo electrónico específica. Recuerde sustituir your_email_address por su dirección de correo electrónico personal. Cuando termine, guarde y cierre el archivo.

      Para que el cambio surta efecto, ejecute el siguiente comando:

      Al ejecutar newaliases, se creará una base de datos de alias que utiliza el comando mail, que se toman del archivo de configuración que acaba de editar.

      Compruebe que se envíen correos electrónicos al root user al ejecutar lo siguiente:

      • echo "This is the body of the email" | mail -s "This is the subject line" root

      Debería recibir el correo en su dirección de correo electrónico. Si no lo ve, revise su carpeta de correo no deseado.

      En este paso, configuró el reenvío de mensajes generados por el sistema a su dirección de correo electrónico. Ahora, habilitará el cifrado de mensajes para que todos los correos electrónicos que envíe su servidor estén protegidos contra alteraciones en tránsito y se consideren más legítimos.

      Paso 5: Habilitar el cifrado SMTP

      Ahora, habilitará el cifrado SMTP al solicitar un certificado TLS gratuito de Let´s Encrypt para su dominio (con Certbot) y configurará Postfix para que lo utilice al enviar mensajes.

      Ubuntu incluye Certbot en su repositorio de paquetes predeterminado, pero podría estar desactualizado. En su lugar, añadirá el repositorio oficial al ejecutar el siguiente comando:

      • sudo add-apt-repository ppa:certbot/certbot

      Presione ENTER cuando se le solicite que acepte. A continuación, actualice la caché del administrador de paquetes de su servidor:

      Por último, instale la última versión de Certbot:

      • sudo apt install certbot -y

      En los requisitos previos, instaló el firewall sencillo ufw como parte de la configuración inicial del servidor. Deberá configurarlo para que habilite el puerto HTTP 80 para que se pueda completar la verificación de dominios. Ejecute el siguiente comando para habilitarlo:

      El resultado tendrá el siguiente aspecto:

      Output

      Rule added Rule added (v6)

      Ahora que el puerto está abierto, ejecute Certbot para obtener un certificado:

      • sudo certbot certonly --standalone --rsa-key-size 4096 --agree-tos --preferred-challenges http -d your_domain

      Este comando le ordena a Certbot que emita certificados con un tamaño de clave RSA de 4096 bits, que ejecute un servidor web autónomo temporal (--standalone) para la verificación y que revise a través del puerto 80 (--preferred-challenges http). Recuerde sustituir your_domain por su dominio antes de ejecutar el comando e ingrese su dirección de correo electrónico cuando se le solicite hacerlo.

      El resultado tendrá un aspecto similar a este:

      Output

      Saving debug log to /var/log/letsencrypt/letsencrypt.log Plugins selected: Authenticator standalone, Installer None Obtaining a new certificate Performing the following challenges: http-01 challenge for `your_domain` Waiting for verification... Cleaning up challenges IMPORTANT NOTES: - Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/your_domain/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/your_domain/privkey.pem Your cert will expire on 2020-07-11. To obtain a new or tweaked version of this certificate in the future, simply run certbot again. To non-interactively renew *all* of your certificates, run "certbot renew" - If you like Certbot, please consider supporting our work by: Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate Donating to EFF: https://eff.org/donate-le

      Como se indica en las notas, su certificado y su archivo de clave privada se guardaron en /etc/letsencrypt/live/your_domain.

      Ahora que tiene su certificado, abra main.cf para editarlo:

      • sudo nano /etc/postfix/main.cf

      Busque la siguiente sección:

      /etc/postfix/main.cf

      # TLS parameters
      smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
      smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
      smtpd_use_tls=yes
      smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
      smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
      

      Modifíquelo para que se vea de esta manera, reemplazando your_domain por su dominio donde sea necesario, lo que actualizará su configuración de TLS para Postfix:

      /etc/postfix/main.cf

      # TLS parameters
      smtpd_tls_cert_file=/etc/letsencrypt/live/your_domain/fullchain.pem
      smtpd_tls_key_file=/etc/letsencrypt/live/your_domain/privkey.pem
      smtp_use_tls=yes
      smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
      smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
      

      Cuando termine, guarde y cierre el archivo.

      Aplique los cambios al reiniciar Postfix:

      • sudo systemctl restart postfix

      Ahora, vuelva a probar enviar un correo electrónico:

      • echo "This is the body of an encrypted email" | mail -s "This is the subject line" your_email_address

      A continuación, revise el correo de la dirección de correo electrónico que proporcionó. Es posible que vea el mensaje en su bandeja de entrada de inmediato, porque es mucho más probable que los proveedores de correo electrónico clasifiquen los mensajes no cifrados como correo no deseado.

      Puede consultar la información técnica sobre el mensaje de correo electrónico en su cliente para ver que el mensaje, efectivamente, está cifrado.

      Conclusión

      Ahora, tiene un servidor de correo electrónico de solo envío de Postfix. Cifrar todos los mensajes salientes es un buen primer paso para que los proveedores de correo electrónico no clasifiquen sus mensajes directamente como correo no deseado. Si está haciendo esto en un escenario de desarrollo, esta medida debería ser suficiente.

      Sin embargo, si desea enviar correos electrónicos a posibles usuarios del sitio (por ejemplo, correos de confirmación para la inscripción a un tablero de mensajes), considere establecer registros SPF para que los correos electrónicos de su servidor tengan más probabilidades de considerarse legítimos.



      Source link

      How To Install and Configure Postfix on Ubuntu 20.04


      Not using Ubuntu 20.04?


      Choose a different version or distribution.

      A previous version of this tutorial was written by Justin Ellingwood

      Introduction

      Postfix is a popular open-source Mail Transfer Agent (MTA) that can be used to route and deliver email on a Linux system. It is estimated that around 25% of public mail servers on the internet run Postfix.

      In this guide, you’ll learn how to install and configure Postfix on an Ubuntu 20.04 server. Then, you’ll test that Postfix is able to correctly route mail by installing s-nail, a Mail User Agent (MUA), also known as an email client.

      Note that the goal of this tutorial is to help you get Postfix up and running quickly with only some bare-bones email functionality. You won’t have a full featured email server by the end of this guide, but you will have some of the foundational components of such a setup to help you get started.

      Prerequisites

      In order to follow this guide, you’ll need the following:

      • A server running Ubuntu 20.04 to function as your Postfix mail server. This server should have a non-root user with sudo privileges and a firewall configured with UFW. You can follow our Ubuntu 20.04 initial server setup guide to set this up.
      • A Fully Qualified Domain Name pointed at your Ubuntu 20.04 server. You can find help on setting up your domain name with DigitalOcean by following our Domains and DNS Networking documentation. Be aware that if you plan on accessing mail from an external location, you will need to make sure you have an MX record pointing to your mail server as well.

      Note that this tutorial assumes that you are configuring a host that has the FQDN of mail.example.com. Wherever necessary, be sure to change example.com or mail.example.com to reflect your own FQDN.

      Step 1 — Installing Postfix

      Postfix is included in Ubuntu’s default repositories, so you can install it with APT.

      To begin, update your local apt package cache:

      Then install the postfix package with the following command. Note that here we pass the DEBIAN_PRIORITY=low environmental variable into this installation command. This will cause the installation process to prompt you to configure some additional options:

      • sudo DEBIAN_PRIORITY=low apt install postfix

      This installation process will open a series of interactive prompts. For the purposes of this tutorial, use the following information to fill in your prompts:

      • General type of mail configuration?: For this, choose Internet Site since this matches our infrastructure needs.
      • System mail name: This is the base domain used to construct a valid email address when only the account portion of the address is given. For instance, let’s say the hostname of your server is mail.example.com. You will likely want to set the system mail name to example.com so that, given the username user1, Postfix will use the address user1@example.com.
      • Root and postmaster mail recipient: This is the Linux account that will be forwarded mail addressed to root@ and postmaster@. Use your primary account for this. In this example case, sammy.
      • Other destinations to accept mail for: This defines the mail destinations that this Postfix instance will accept. If you need to add any other domains that this server will be responsible for receiving, add those here. Otherwise, the default will be sufficient.
      • Force synchronous updates on mail queue?: Since you are likely using a journaled filesystem, accept No here.
      • Local networks: This is a list of the networks for which your mail server is configured to relay messages. The default will work for most scenarios. If you choose to modify it, though, make sure to be very restrictive in regards to the network range.
      • Mailbox size limit: This can be used to limit the size of messages. Setting it to 0 disables any size restriction.
      • Local address extension character: This is the character that can be used to separate the regular portion of the address from an extension (used to create dynamic aliases). The default, + will work for this tutorial.
      • Internet protocols to use: Choose whether to restrict the IP version that Postfix supports. For the purposes of this tutorial, pick all.

      To be explicit, these are the settings used in this guide:

      • General type of mail configuration?: Internet Site
      • System mail name: example.com (not mail.example.com)
      • Root and postmaster mail recipient: The username of your primary Linux account (sammy in our examples)
      • Other destinations to accept mail for: $myhostname, example.com, mail.example.com, localhost.example.com, localhost
      • Force synchronous updates on mail queue?: No
      • Local networks: 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
      • Mailbox size limit: 0
      • Local address extension character: +
      • Internet protocols to use: all

      Note: If you need to ever return to change these settings, you can do so by typing:

      • sudo dpkg-reconfigure postfix

      The prompts will be pre-populated with your previous responses.

      When the installation process finishes, you’re ready to make a few updates to your Postfix configuration.

      Step 2 — Changing the Postfix Configuration

      Now you can adjust some settings that the package installation process didn’t prompt you for. Many of Postfix’s configuration settings are defined in the /etc/postfix/main.cf file. Rather than editing this file directly, you can use Postfix’s postconf command to query or set configuration settings.

      To begin, set the location for your non-root Ubuntu user’s mailbox. In this guide, we’ll use the Maildir format, which separates messages into individual files that are then moved between directories based on user action. The alternative option that isn’t covered in this guide is the mbox format, which stores all messages within a single file.

      Set the home_mailbox variable to Maildir/. Later, you will create a directory structure under that name within your user’s home directory. Configure home_mailbox by typing:

      • sudo postconf -e 'home_mailbox= Maildir/'

      Next, set the location of the virtual_alias_maps table, which maps arbitrary email accounts to Linux system accounts. Run the following command, which maps the table location to a hash database file named /etc/postfix/virtual:

      • sudo postconf -e 'virtual_alias_maps= hash:/etc/postfix/virtual'

      Now that you’ve defined the location of the virtual maps file in your main.cf file, you can create the file itself and begin mapping email accounts to user accounts on your Linux system. Create the file with your preferred text editor; in this example, we’ll use nano:

      • sudo nano /etc/postfix/virtual

      List any addresses that you wish to accept email for, followed by a whitespace and the Linux user you’d like that mail delivered to.

      For example, if you would like to accept email at contact@example.com and admin@example.com and would like to have those emails delivered to the sammy Linux user, you could set up your file like this:

      /etc/postfix/virtual

      contact@example.com sammy
      admin@example.com sammy
      

      After you’ve mapped all of the addresses to the appropriate server accounts, save and close the file. If you used nano, do this by pressing CTRL + X, Y, then ENTER.

      Apply the mapping by typing:

      • sudo postmap /etc/postfix/virtual

      Restart the Postfix process to be sure that all of your changes have been applied:

      • sudo systemctl restart postfix

      Assuming you followed the prerequisite Initial Server Setup guide, you will have configured a firewall with UFW. This firewall will block external connections to services on your server by default unless those connections are explicitly allowed, so you’ll have to add a firewall rule to allow an exception for Postfix.

      You can allow connections to the service by typing:

      With that, Postfix is configured and ready to accept external connections. However, you aren’t yet ready to test it out with a mail client. Before you can install a client and use it to interact with the mail being delivered to your server, you’ll need to make a few changes to your Ubuntu server’s setup.

      Step 3 — Installing the Mail Client and Initializing the Maildir Structure

      In order to interact with the mail being delivered, this step will walk you through the process of installing the s-nail package. This is a feature-rich variant of the BSD xmail client which can handle the Maildir format correctly.

      Before installing the client, though, it would be prudent to make sure your MAIL environment variable is set correctly. s-nail will look for this variable to figure out where to find mail for your user.

      To ensure that the MAIL variable is set regardless of how you access your account — whether through ssh, su, su -, or sudo, for example — you’ll need to set the variable in the /etc/bash.bashrc file and add it to a file within /etc/profile.d to make sure it is set for all users by default.

      To add the variable to these files, type:

      • echo 'export MAIL=~/Maildir' | sudo tee -a /etc/bash.bashrc | sudo tee -a /etc/profile.d/mail.sh

      To read the variable into your current session, source the /etc/profile.d/mail.sh file:

      • source /etc/profile.d/mail.sh

      With that complete, install the s-nail email client with APT:

      Before running the client, there are a few settings you need to adjust. Open the /etc/s-nail.rc file in your editor:

      At the bottom of the file, add the following options:

      /etc/s-nail.rc

      . . .
      set emptystart
      set folder=Maildir
      set record=+sent
      

      Here’s what these lines do:

      • set emptystart: allows the client to open even with an empty inbox
      • set folder=Maildir: sets the Maildir directory to the internal folder variable
      • set record=+sent creates a sent mbox file for storing sent mail within whichever directory is set as the folder variable, in this case Maildir

      Save and close the file when you are finished. You’re now ready to initialize your system’s Maildir structure.

      A quick way to create the Maildir structure within your home directory is to send yourself an email with the s-nail command. Because the sent file will only be available once the Maildir is created, you should disable writing to it for this initial email. Do this by passing the -Snorecord option.

      Send the email by piping a string to the s-nail command. Adjust the command to mark your Linux user as the recipient:

      • echo 'init' | s-nail -s 'init' -Snorecord sammy

      Note: You may get the following response:

      Output

      Can't canonicalize "/home/sammy/Maildir"

      This is normal and may only appear when sending this first message.

      You can can check to make sure the directory was created by looking for your ~/Maildir directory:

      You will see the directory structure has been created and that a new message file is in the ~/Maildir/new directory:

      Output

      /home/sammy/Maildir/: cur new tmp /home/sammy/Maildir/cur: /home/sammy/Maildir/new: 1463177269.Vfd01I40e4dM691221.mail.example.com /home/sammy/Maildir/tmp:

      Now that the directory structure has been created, you’re ready to test out the s-nail client by viewing the init message you sent and sending a message to an external email address.

      Step 5 — Testing the Client

      To open the client, run the s-nail command:

      In your console, you’ll see a rudimentary inbox with the init message waiting:

      Output

      s-nail version v14.9.15. Type `?' for help "/home/sammy/Maildir": 1 message 1 new >N 1 sammy@example.com 2020-05-19 15:40 14/392 init

      Press ENTER to display the message:

      Output

      [-- Message 1 -- 14 lines, 369 bytes --]: From sammy@example.com Tue May 19 15:40:48 2020 Date: Tue, 19 May 2020 15:40:48 +0000 To: sammy@example.com Subject: init Message-Id: <20160513220749.A278F228D9@mail.example.com> From: sammy@example.com init

      You can get back to the message list by typing h, and then ENTER:

      Output

      >R 1 sammy@example.com 2020-05-19 15:40 14/392 init

      Notice that the message now has a state of R, indicating that it’s been read.

      Since this message isn’t very useful, you can delete it by pressing d, and then ENTER:

      To get back to the terminal, type q and then ENTER:

      As a final test, check whether s-nail is able to correctly send email messages. To do this, you can pipe the contents of a text file into the s-nail process, like you did with the init message you sent in the previous step.

      Begin by writing a test message in a text editor:

      Inside, enter some text you’d like to send:

      ~/test_message

      Hello,
      
      This is a test.  Please confirm receipt!
      

      Save and close the file after writing your message.

      Then, use the cat command to pipe the message to the s-nail process. You can do so with the following example, which uses these options:

      • -s: This defines the subject line of the email message
      • -r: An optional change to the “From:” field of the email. By default, the Linux user you are logged in as will be used to populate this field. The -r option allows you to override this with a valid address, such as one of those you defined in the /etc/postfix/virtual file. To illustrate, the following command uses contact@example.com

      Also, be sure to change user@email.com to a valid email address which you have access to:

      • cat ~/test_message | s-nail -s 'Test email subject line' -r contact@example.com user@email.com

      Then, navigate to the inbox for the email address to which you sent the message. You will see your message waiting there almost immediately.

      Note: If the message isn’t in your inbox, it may have been delivered to your Spam folder.

      You can view your sent messages within your s-nail client. Start the interactive client again:

      From the email client, view your sent messages by typing:

      You’ll see output like this:

      Output

      +[/home/sammy/Maildir/]sent: 1 message 1 new ▸N 1 contact@example.com 2020-05-19 15:47 12/297 Test email subject line

      You can manage sent mail using the same commands you use for incoming mail.

      Conclusion

      You now have Postfix configured on your Ubuntu 20.04 server. Managing email servers can be a tough task for new system administrators, but with this configuration, you should have enough MTA email functionality to get yourself started.



      Source link

      How To Install and Configure Postfix as a Send-Only SMTP Server on Ubuntu 18.04


      The author selected the Free and Open Source Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Postfix is a mail transfer agent (MTA), an application used to send and receive email. It can be configured so that it can be used to send emails by local application only. This is useful in situations when you need to regularly send email notifications from your apps or simply have a lot of outbound traffic that a third-party email service provider won’t allow. It’s also a lighter alternative to running a full-blown SMTP server, while retaining the required functionality.

      In this tutorial, you’ll install and configure Postfix as a send-only SMTP server. You’ll also request free TLS certificates from Let’s Encrypt for your domain and encrypt the outbound emails using them.

      Prerequisites

      • One Ubuntu 18.04 server set up with the Initial Server Setup with Ubuntu 18.04, including creating a sudo non-root user.
      • A fully registered domain name. This tutorial will use your_domain throughout. You can purchase a domain name on Namecheap, get one for free on Freenom, or use the domain registrar of your choice.
      • An A DNS record with your_domain pointing to your server’s public IP address. You can follow this introduction to DigitalOcean DNS for details on how to add them.

      Note: Your server’s hostname and your Droplet’s name must match your_domain, because DigitalOcean automatically sets PTR records for the Droplet’s IP address according to its name.

      You can verify the server’s hostname by typing hostname at the command prompt. The output should match the name you gave the Droplet when it was being created.

      Step 1 — Installing Postfix

      In this step, you’ll install Postfix. The fastest way is to install the mailutils package, which bundles Postfix with a few supplementary programs that you’ll use to test sending email.

      First, update the package database:

      Then, install Postfix by running the following command:

      • sudo apt install mailutils

      Near the end of the installation process, you will be presented with the Postfix configuration window:

      Select Internet Site from the menu, then press TAB to select <Ok>, then ENTER

      The default option is Internet Site. That’s the recommended option for your use case, so press TAB, and then ENTER. If you only see the description text, press TAB to select OK, then ENTER.

      If it does not show up automatically, run the following command to start it:

      • sudo dpkg-reconfigure postfix

      After that, you’ll get another configuration prompt regarding the System mail name:

      Enter your domain name, then press TAB to select <Ok>, ENTER

      The System mail name must be the same as the name you assigned to your server when you were creating it. When you’ve finished, press TAB, followed by ENTER.

      You have now installed Postfix and are ready to start configuring it.

      Step 2 — Configuring Postfix

      In this step, you’ll configure Postfix to send and receive emails only from the server on which it is running on—that is, from localhost.

      For that to happen, Postfix needs to be configured to listen only on the loopback interface, the virtual network interface that the server uses to communicate internally. To make the changes, you’ll need to edit the main Postfix configuration file called main.cf, stored under etc/postfix.

      Open it for editing using your favorite text editor:

      • sudo nano /etc/postfix/main.cf

      Find the following lines:

      /etc/postfix/main.cf

      . . .
      mailbox_size_limit = 0
      recipient_delimiter = +
      inet_interfaces = all
      . . .
      

      Set the value of the inet_interfaces setting to loopback-only:

      /etc/postfix/main.cf

      . . .
      mailbox_size_limit = 0
      recipient_delimiter = +
      inet_interfaces = loopback-only
      . . .
      

      Another directive you’ll need to modify is mydestination, which is used to specify the list of domains that are delivered via the local_transport mail delivery transport. By default, the values are similar to these:

      /etc/postfix/main.cf

      . . .
      mydestination = $myhostname, your_domain, localhost.com, , localhost
      . . .
      

      Change the line to look like this:

      /etc/postfix/main.cf

      . . .
      mydestination = localhost.$mydomain, localhost, $myhostname
      . . .
      

      If your domain is actually a subdomain, and you’d want the email messages to look as if they were sent from the main domain, you can add the following line to the end of main.cf:

      /etc/postfix/main.cf

      ...
      masquerade_domains = your_main_domain
      

      The optional masquerade_domains setting specifies for which domains the subdomain part will be stripped off in the email address.

      When you are done, save and close the file.

      Note: If you’re hosting multiple domains on a single server, the other domains can also be passed to Postfix using the mydestination directive.

      Then, restart Postfix by running the following command:

      • sudo systemctl restart postfix

      You’ve configured Postfix to only send emails from your server. You’ll now test it by sending an example message to an email address.

      Step 3 — Testing the SMTP Server

      In this step, you’ll test whether Postfix can send emails to an external email account using the mail command, which is part of the mailutils package that you installed in the first step.

      To send a test email, run the following command:

      • echo "This is the body of the email" | mail -s "This is the subject line" your_email_address

      You can change the body and the subject of the email to your liking. Remember to replace your_email_address with a valid email address that you can access.

      Now, check the email address to which you sent this message. You should see the message in your inbox. If it’s not there, check your spam folder. At this point, all emails you send are unencrypted, which makes service providers think it’s likely spam. You’ll set up encryption later, in step 5.

      If you receive an error from the mail command, or you haven’t received a message after prolonged periods of time, check that the Postfix configuration you edited is valid and that your server’s name and hostname are set to your domain.

      Note that with this configuration, the address in the From field for the test emails you send will be in the form of your_user_name@your_domain, where your_user_name is the username of the server user you ran the command as.

      You have now sent an email from your server and verified that it’s successfully received. In the next step, you’ll set up email forwarding for root.

      Step 4 — Forwarding System Mail

      In this step, you’ll set up email forwarding for user root, so that system-generated messages sent to it on your server get forwarded to an external email address.

      The /etc/aliases file contains a list of alternate names for email recipients. Open it for editing:

      In its default state, it looks like this:

      /etc/aliases

      # See man 5 aliases for format
      postmaster:    root
      

      The only directive present specifies that system generated emails are sent to root.

      Add the following line to the end of the file:

      /etc/aliases

      ...
      root:          your_email_address
      

      With this line, you specify that emails sent to root end up being forwarded to an email address. Remember to replace your_email_address with your personal email address. When you are done, save and close the file.

      For the change to take effect, run the following command:

      Running newaliases will build up a database of aliases that the mail command uses, which are taken from the config file you just edited.

      Test that sending emails to root works by running:

      • echo "This is the body of the email" | mail -s "This is the subject line" root

      You should receive the email at your email address. If it’s not there, check your spam folder.

      In this step, you have set up forwarding system-generated messages to your email address. You’ll now enable message encryption, so that all emails your server sends are immune to tampering in transit and will be viewed as more legitimate.

      Step 5 — Enabling SMTP Encryption

      You’ll now enable SMTP encryption by requesting a free TLS certificate from Let’s Encrypt for your domain (using Certbot) and configuring Postfix to use it when sending messages.

      Ubuntu includes Certbot in their default package repository, but it may happen that it’s out of date. Instead, you’ll add the official repository by running the following command:

      • sudo add-apt-repository ppa:certbot/certbot

      Press ENTER when prompted to accept. Then, update your server’s package manager cache:

      Finally, install the latest version of Certbot:

      • sudo apt install certbot -y

      As part of the initial server setup in the prerequisites, you installed ufw, the uncomplicated firewall. You’ll need to configure it to allow the HTTP port 80, so that domain verification can be completed. Run the following command to enable it:

      The output will look like this:

      Output

      Rule added Rule added (v6)

      Now that the port is open, run Certbot to get a certificate:

      • sudo certbot certonly --standalone --rsa-key-size 4096 --agree-tos --preferred-challenges http -d your_domain

      This command orders Certbot to issue certificates with an RSA key size of 4096 bits, to run a temporary standalone web server (--standalone) for verification, and to check via port 80 (--preferred-challenges http). Remember to replace your_domain with your domain before running the command, and enter your email address when prompted.

      The output will be similar to this:

      Output

      Saving debug log to /var/log/letsencrypt/letsencrypt.log Plugins selected: Authenticator standalone, Installer None Obtaining a new certificate Performing the following challenges: http-01 challenge for `your_domain` Waiting for verification... Cleaning up challenges IMPORTANT NOTES: - Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/your_domain/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/your_domain/privkey.pem Your cert will expire on 2020-07-11. To obtain a new or tweaked version of this certificate in the future, simply run certbot again. To non-interactively renew *all* of your certificates, run "certbot renew" - If you like Certbot, please consider supporting our work by: Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate Donating to EFF: https://eff.org/donate-le

      As written in the notes, your certificate and private key file were saved under /etc/letsencrypt/live/your_domain.

      Now that you have your certificate, open main.cf for editing:

      • sudo nano /etc/postfix/main.cf

      Find the following section:

      /etc/postfix/main.cf

      # TLS parameters
      smtpd_tls_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
      smtpd_tls_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
      smtpd_use_tls=yes
      smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
      smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
      

      Modify it to look like this, replacing your_domain with your domain where necessary, which will update your TLS settings for Postfix:

      /etc/postfix/main.cf

      # TLS parameters
      smtpd_tls_cert_file=/etc/letsencrypt/live/your_domain/fullchain.pem
      smtpd_tls_key_file=/etc/letsencrypt/live/your_domain/privkey.pem
      smtp_use_tls=yes
      smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
      smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
      

      Once you’re done, save and close the file.

      Apply the changes by restarting Postfix:

      • sudo systemctl restart postfix

      Now, try sending an email again:

      • echo "This is the body of an encrypted email" | mail -s "This is the subject line" your_email_address

      Then, check the email address you provided. It’s possible that you’ll see the message in your inbox immediately, because email providers are much more likely to mark unencrypted messages as spam.

      You can check the technical info about the email message in your client to see that the message is indeed encrypted.

      Conclusion

      You now have a send-only email server, powered by Postfix. Encrypting all outgoing messages is a good first step to email providers not marking your messages as spam outright. If you are doing this in a development scenario, then this measure should be enough.

      However, if your use case is to send emails to potential site users (such as confirmation emails for a message board sign-up), you should look into setting up SPF records, so that your server’s emails are even more likely to be seen as legitimate.



      Source link