msmtp requires a minimal setup for sending emails via SMTP compared to sendmail. Here is a configuration for you to send emails from a web host to an external SMTP server. Prior to doing that, you must check whether there is a clear communication channel between your web host and the SMTP server. You can use Telnet.
Set up msmtp
You are going to set msmtp as an MTA. Hence, you need to remove all other MTAs such as postfix and sendmail:
$ sudo apt-get --purge autoremove postfix sendmail
Install msmtp and related utilities:
$ sudo apt-get install msmtp msmtp-mta mailutils
Configure msmtp:
$ sudo nano /etc/msmtprc
# Set default values for all following accounts.
defaults
# Use the mail submission port 587 instead of the SMTP port 25.
port 587
# Always use TLS.
tls on
# Set a list of trusted CAs for TLS. The default is to use system settings, but
# you can select your own file.
tls_trust_file /etc/ssl/certs/ca-certificates.crt
# The SMTP server
account mx
host mail.mx.example
from admin@mx.example
auth on
user admin@mx.example
password 123456
# Set default account to mx
account default: mx
# Map local users to mail addresses
aliases /etc/aliases
You need to change some of the values above with your own. The msmtp configuration is actually a list of commands which are executed top down. The account command defines the name of the subsequent email account details. You can give it any name. The commands host, from, auth, user and password defines the email account details. You can get more explanation and other options from the msmtp documentation.
Install mailx so that you can use mail:
$ sudo apt-get install bsd-mailx
Set msmtp as MTA:
$ sudo nano /etc/mail.rc
append the following:
set mta=/usr/bin/msmtp
Setup aliases so that the system services such as cronjobs will redirect system user emails to the external SMTP server:
$ sudo nano /etc/aliases
# Send root to John
root: john_doe@mx.example
# Send everything else to admin
default: admin@mx.example
$ sudo nano /etc/mail.rc
append:
alias root root<john_doe@mx.example>
Test
$ msmtp -d joe@mx.example <<END
> From: Admin <admin@mx.example>
> To: joe@mx.example
> Subject: test
>
> test
> END
Note: Some email servers like Gmail insist the From email address. Otherwise, the email will be rejected.
If msmtp hangs at the following:
...
reading recipients from the command line
$ mail -s "Hi root" root <<END
> Testing msmtp from ${HOSTNAME} with mail command
> END
$ mail -s "Hi there" someone@gmail.com <<END
> Testing msmtp from ${HOSTNAME} with mail command
> END
PHP Mail
$ sudo nano /etc/php/7.3/apache2/php.ini
sendmail_path = "/usr/bin/msmtp -t"
$ sudo service apache2 restart
if (mail("your@email.com", "Test email from PHP", "msmtp as sendmail for PHP"))
echo "Successful";
else
echo "Failed";
Comments
Post a Comment