Mail from linux server

Отправка почты из командной строки Linux

Подготовка

Для начала устанавливаем утилиту для отправки почты. В противном случае мы увидим ошибку mail: command not found.

В Debian / Ubuntu:

apt-get install mailutils

В CentOS / Red Hat:

yum install mailx

Синтаксис

Можно отправить сообщение следующей командой:

echo «Test text» | mail -s «Test title» master@dmosk.ru

* в данном примере будет отправлено письмо на электронный адрес master@dmosk.ru с темой Test title и телом письма — Test text.

Если при отправке возникли проблемы, можно проверить логи следующей командой:

Примеры использования командной строки для email-отправки

1. Отправка письма с вложением

Для разных типов дистрибутива Linux команды могут отличаться.

а) для CentOS / Red Hat:

echo ‘Attachment’ | mail -s ‘Subject attachment message’ -a /var/log/maillog master@dmosk.ru

echo ‘Attachment’ | mail -s ‘Subject attachment message’ -a /var/log/maillog -a /var/log/maillog2 master@dmosk.ru

echo ‘Attachment’ | mail -s ‘Subject attachment message’ -A /var/log/maillog -A /var/log/maillog2 master@dmosk.ru

* где /var/log/maillog и /var/log/maillog2 — файлы, которые будут прикреплены к письму. Обратите внимание, что обе команды отличаются по регистру опции a и A — все зависит от версии и сборки Linux (в каких-то нужно использовать маленькую, в каких-то — большую). Также обратите внимание, что в примере для Ubuntu мы отправим 2 файла — для этого просто добавляем к команде еще одну опцию прикрепления файла.

2. Несколько получателей

Для отправки письма нескольким получателям, просто перечисляем их через запятую:

echo «Test text» | mail -s «Test title» master@dmosk.ru,shmaster@dmosk.ru

* в данном примере мы отправил письмо на ящики master@dmosk.ru и shmaster@dmosk.ru.

3. Отправка с копией

Отправить копию на адрес master2@dmosk.ru:

echo «Test copy» | mail -s «Test copy title» master@dmosk.ru -c master2@dmosk.ru

Отправить скрытую копию на адрес master3@dmosk.ru:

echo «Test hidden copy» | mail -s «Test hidden copy title» master@dmosk.ru -b master3@dmosk.ru

4. Указать отправителя

В CentOS / Red Hat:

echo «Test text» | mail -s «Test title» -r postmaster@dmosk.ru master@dmosk.ru

В Debian / Ubuntu:

echo «Test text» | mail -s «Test title» master@dmosk.ru -aFrom:postmaster@dmosk.ru

5. Отправка через другой SMTP сервер

а) Для Ubuntu / Debian:

echo «Test text» | mail -s «Test title» -a «Smtp: smtp.mail.ru:25» -a «From: postmaster@dmosk.ru» -a «Return-path: postmaster@dmosk.ru» master@dmosk.ru

б) Для CentOS / Red Hat:

echo «Test text» | mail -s «Test title» -S smtp=»smtp.mail.ru:25″ master@dmosk.ru

Однако, если сторонний почтовый сервер работает по шифрованному каналу и требует аутентификацию, необходимо ввести следующее:

echo «Test text» | mail -v -s «Test title» -S smtp=»smtp.dmosk.ru:587″ -S smtp-use-starttls -S smtp-auth=login -S smtp-auth-user=»master@dmosk.ru» -S smtp-auth-password=»password» -S ssl-verify=ignore -S nss-config-dir=/etc/pki/nssdb -S from=postmaster@dmosk.ru master@dmosk.ru

* где smtp.dmosk.ru — сервер smtp; 587 — порт для подключения к серверу отправки; smtp-use-starttls указывает на использование шифрования через TLS; smtp-auth=login задает аутентификацию с использованием логина и пароля; smtp-auth-user и smtp-auth-password — соответственно логин и пароль; ssl-verify=ignore отключает проверку подлинности сертификата безопасности; nss-config-dir указывает на каталог с базами nss; from задает поле FROM

При возникновении проблем, можно воспользоваться программой mutt. Сначала поставим ее.

а) если используем CentOS / Red Hat:

yum install mutt

б) если используем Ubuntu / Debian:

apt-get install mutt

Теперь можно пользоваться. Синтаксис:

echo «Текст сообщения» | mutt -s «Тема» [дополнительные опции] —

Примеры использования Mutt

1. Отправить вложение:

echo «Attachment» | mutt -s «subject» -a /var/log/maillog — master@dmosk.ru

* где /var/log/maillog — файл, который будет прикреплен к письму.

2. Указать отправителя:

echo «Mail From» | mutt -s «subject» -e ‘my_hdr From: Дмитрий

* данной командой mutt отправит письмо от postmaster@dmosk.ru.

3. Отправка через другой сервер.

Для начала, открываем файл с конфигурацией Mutt:

* в данном примере мы отправим всю нашу почту через узел smtp.mail.ru, порт 25.

Также можно добавить при необходимости:

set smtp_user = user
set smtp_pass = password
set ssl_verify_host = no
set ssl_verify_dates = no
set ssl_starttls = no
set ssl_force_tls = no

  • smtp_user — имя учетной записи, под которой нужно авторизоваться на SMTP.
  • smtp_pass — пароль для аутентификации.
  • ssl_verify_host — нужно ли проверять валидность сертификата.
  • ssl_verify_dates — нужно ли проверять дату действия сертификата.
  • ssl_starttls — нужно ли использовать STARTTLS.
  • ssl_force_tls — нужно ли принудительное использование TLS.

Теперь можно отправлять письмо:

echo «Mail From» | mutt -s «subject» -e ‘my_hdr From: Дмитрий

Источник

Лучшие почтовые серверы Linux

Электронная почта — это не просто веб-сайт, на котором вы можете обмениваться сообщениями, такой как ВКонтакте или Facebook. Это более сложный механизм, который работает с помощью собственного протокола. В сети почтовые клиенты отправляют письма на почтовый сервер, затем они уже направляются к адресату.

Именно потому мы можем отправлять почту всем адресатам, независимо от их домена, mail, gmail, yandex и т д. На низком уровне эти сервисы работают по одному протоколу. Чтобы отправить сообщение почтовый сервер использует программу MTA (Mail Transfer Agent). В этой статье мы собрали лучшие почтовые серверы для Linux.

Лучшие почтовые серверы для Linux

MTA — это приложение, которое определяет маршруты и передает электронную почту от одного узла в сети к другому. Для этого используется протокол SMTP — Simple Mail Transfer Protocol или простой протокол передачи почты. Для отправки почты используется почтовый клиент, он может отправлять и получать письма от почтового сервера и тоже использует SMTP, но это необязательно MTA. MTA работают на сервере, а на компьютерах используются почтовые клиенты, такие как Mozilla Thunderbird, Evolution, Outlook и т д.

1. Sendmail

Почтовый сервер Sendmail теперь известный как Proofpoint, после того как Proofpoint Inc. приобрела Sendmail Inc. На сегодняшний день — это самый популярный и самый старый MTA для операционной системы Linux. Если сравнивать Sendmail и более современные почтовые серверы, то здесь есть много ограничений.

Настройка сервера очень сложная, а система безопасности слабая, поэтому были разработаны альтернативные почтовые серверы. Но все же он достаточно хорошо справляется со своей задачей. Продолжим наш обзор почтовых серверов linux более современными вариантами. Этот почтовый сервер очень часто использовался в связке с интерпретатором языка программирования PHP для отправки почты.

Читайте также:  Panasonic kx mb2000 linux driver

2. Postfix

Postfix — это ещё один популярный почтовый сервер с открытым исходным кодом, который был разработан компанией Wietse Zweitze Venema для собственного почтового сервера, когда он работал в научно-исследовательском отделе IBM. Он составляет сильную конкуренцию для очень популярного Sendmail и может работать на всех Unix подобных системах.

Здесь позаимствовано много свойств Sendmail, но есть и множество отличий и улучшений. Postfix быстрый, безопасный и легкий в настройке. Согласно статистике более 30% всех почтовых серверов на данный момент используют Postfix.

3. Exim

Свободный почтовый сервер для операционных систем на базе ядра Linux, а также BSD. Он написан на Си и очень производительный, поэтому может использоваться для отправки огромного количества писем. К тому же сейчас он активно развивается, прост в настройке и поддерживает большое количество баз данных.

4. Qmail

Qmail — еще один свободный и современный сервер отправки электронной почты с открытым исходным кодом. Он простой, надежный и эффективный, предлагает широкие возможности безопасности. Разрабатывался Qmail как альтернатива для Sendmail и написан он на Си. Поэтому показывает неплохую производительность. Из преимуществ в нём встроены дополнительные механизмы управления списками рассылки, а также фильтрации спама.

5. Dwarf Mail Server

Уже довольно старый, но всё равно функциональный почтовый сервер, написанный на Java. Он поддерживает протоколы работы почты SMTP, POP3 и IMAP4. Подходит как для обычных пользователей, которым нужен простой почтовый сервер, так и для разработчиков. Работает на всех платформах, поддерживающих Java и не требует тратить много времени на настройку.

6. MailerQ

Это современный и высокопроизводительный почтовый сервер позволяющий отправлять и переправлять очень большое количество почты. Но у него есть один значительный недостаток. Он платный. Версия для установки на один сервер стоит 10 тысяч евро на данный момент. Зато он поддерживает мониторинг в реальном времени, позволяет показывать детальную статистику о попытках отправки почты, очередях, и логах ошибок.

7. Courier Mail Server

Этот почтовый сервер распространяется под лицензией GPL и поэтому он полностью бесплатен для использования. Он известен своей модульностью, его компоненты для работы с IMAP, или система фильтрации почты Maildrop могут быть установлены и использованы отдельно от всего остального. Сам почтовый сервер написан на C++ и Perl и может работать в Linux, MacOS и FreeBSD. Поддерживаются такие протоколы как ESMTP, IMAP, POP3 и SMAP.

8. Apache James Server

Это ещё один почтовый сервер, написанный на Java и развиваемый организацией Apache Software Foundation. Он поддерживает протоколы SMTP, LMTP, POP3, IMAP, JMAP а также ManageSieve. Проект понемногу развивается и сейчас он предназначен для работы на Java машине 11 версии. Сервер можно использовать в качестве SMTP релея или для доставки почты по локальным ящикам, причём поддерживаются как локальные учётные записи, так и виртуальные почтовые ящики.

Выводы

В этой статье мы рассмотрели как передается электронная почта по сети, а также лучшие почтовые серверы Linux. Для обработки почты на Losst используется Postfix. А какой почтовый сервер используете вы? Какой считаете лучшим? Почему? Напишите в комментариях!

Источник

5 Ways to Send Email From Linux Command Line

We all know the importance of emails these days for information transfer. There are many free emails service providers which we used for use like Gmail, Yahoo, RediffMail etc, which provides a web interface for sending and receiving emails. But this is not enough, sometimes we also required to send emails from system command line. This tutorial will provide you multiple ways to send emails from the Linux command line. This is useful for sending email through our shell scripts, cronjobs etc.

There are various ways to send emails from the command line but here I am sharing few options used by most users. You can use anyone option given below to send email from Linux command line.

1. Using ‘sendmail’ Command

Sendmail is a most popular SMTP server used in most of Linux/Unix distribution. Sendmail allows sending email from command line. Use below instructions to send email using ‘sendmail‘ command.

Created a file with email content:

Subject: line will be used as subject for email.

Now send email using the following command.

2. Using ‘mail’ Command

mail command is most popular command to send emails from Linux terminal. Use few of below examples to send an email.

  • -s is used for defining subject for email.

Also, you can send an attachment with this command. Use -a for mailx and -A for mailutils.

  • Here -a is used for attachments. Use -A for debian based systems, which uses mailutils package.

Also, we can add comma separated emails to send the email to multiple recipients together.

3. Using ‘mutt’ command

Mutt is basically used for reading emails from Linux terminal from local user mailboxes, also useful to read emails from POP/IMAP servers. Mutt command is little similar to mail command. Use few of below examples to send an email.

Send an email including an attachment

4. Using ‘SSMTP’ Command

sSMTP allows users to send emails from SMTP server from Linux command line. For example to send an email to user [email protected] use following command. Now type your subject of the email as below with keyword Subject. After that type your message to be sent to the user, After finishing your message press CTRL+d (^d) to send the email.

5. Using ‘telnet’ Command

As per my experience, all system administrators use telnet command to test remote port connectivity test or login to the server remotely. Most of the newbie in Linux doesn’t know that we can send email using telnet also, which is the better way to troubleshoot email sending problems. Below is an example of email sending.

Red marked text is the user input and remaining is the responses of that commands.

Thank you for using this article. We will add more ways soon with this list. We also request you to help me with more commands which you know and not listed above.

Источник

Install, Secure, Access and Configure Linux Mail Server (Postfix)

If you want to send or receive an email, you should have a mail server. In this post, we will discuss the Linux mail server and how the SMTP (Simple Mail Transfer Protocol) works as well as other mail-related protocols, like Post Office Protocol (POP) and Internet Message Access Protocol (IMAP) and the relationship between them.

Table of Contents

Linux SMTP server

SMTP defines how to send mail from one host to another; it is also system independent, which means the sender and receiver can have different operating systems.

Читайте также:  Виртуальный диск для windows 10 служба

SMTP requires only that a server can send straight ASCII text to another server, you can do this by connecting to the server on port 25, which is the standard SMTP port.

Most Linux distros today come with two of the most common implementations of SMTP, which are sendmail and Postfix.

Sendmail is a famous and free mail server, but it has a little complex design and less secure.

The Postfix took mail server implementation one step further; they developed it with security in mind.

Mail service components

The mail service on any mail server has three components:

Mail user agent (MUA): this component that the user sees and interacts with like Thunderbird and Microsoft Outlook, these user agents are responsible for reading mail and allowing you to compose mail.

Mail transport agent (MTA): this component is responsible for getting the mail from one site to another like Sendmail and Postfix.

Mail delivery agent (MDA): this component is responsible for distributing received messages on the local machine to the appropriate user mailbox like postfix-maildrop and Procmail.

Setup Email server

We chose the Postfix mail server, which is very popular and common among system administrators today.

Postfix is the default mail server on most modern Linux distros.

First, check if it is installed on your system or not:

If not installed, you can install Postfix mail server on Red Hat based distros like this:

Then start the postfix service and enable it on system startup:

On Debian based distros like Ubuntu, you can install it like this:

It will ask you to select the type of configuration of the Postfix mail server during the installation process.

Among the four choices No configuration, Internet site, Internet with smarthost, Satellite system, and Local only, we will choose No configuration option.

Configure Linux mail server

After installing the Postfix mail server, you will need to configure it; you can find most of its configuration files under the /etc/postfix/ directory.

You can find the main configuration for Postfix mail server in /etc/postfix/main.cf file.

This file contains a lot of options like:

myhostname

You can use this option for specifying the hostname of the mail server. This is the Internet hostname, which Postfix will receive emails on it.

The hostnames could be like mail.example.com, smtp.example.com.

mydomain

This option is the mail domain that you will be servicing, like example.com

The syntax is like this:

myorigin

All emails sent from this mail server will look as though it came from this option. You can set this to $mydomain value.

You can use any option value, just precede it with a $ like $mydomain.

mydestination

This option lists the domains that the Postfix server uses for incoming emails.

It can take values like this:

mail_spool_directory

There are two modes of delivery that Postfix mail server can use:

  • Directly to a user’s mailbox.
  • To a central spool directory, this way, the mail will be in /var/spool/mail with a file for each user.

mynetworks

This option allows you to configure what servers can relay through your Postfix server.

This option should take local addresses like local mail scripts on your server only.

Otherwise, spammers can utilize your mail server to relay their messages and your mail server blacklisted and as a result, you will not be able to receive many emails.

This option has the following syntax:

smtpd_banner

This variable sets the message the server will send when the client after a successful connection.

It is better to change the banner to something that gives no clue the server you are using.

inet_protocols

This option specifies the IP protocol version used for server connections.

If you change the configuration files for the Postfix mail server, you need to reload the service:

When you type any configuration, you may make a mistake, you can check for errors using the following command:

This tool will help you find exactly the line and the error so you can fix it.

Checking the mail queue

Sometimes the mail queues are filled up with messages. This happens due to many reasons, like network failure or any reason that can delay mail delivery.

To check the mail queue on your Linux mail server, use the following command:

This command shows the Postfix mail queue.

If your queue is filled up and the message takes several hours to process, then you should flush the mail queue.

Now, if you check your mail queue, you should find it empty.

Test Linux mail server

After configuring the Postfix mail server correctly, you should test your mail server.

The first step is to use a local mail user agent like mailx or mail, which is a symlink to mailx.

Try to send a mail to someone else on the same server, if this works, then send to a remote site.

Then try to receive a mail from a remote site.

If you have any problems, check the logs. The log file on Red Hat based distros in /var/log/maillog file and on Debian based distros in /var/log/mail.log file or as defined in the rsyslogd configuration.

I recommend you to review the Linux Syslog Server for a detailed explanation about logs and how to configure the rsyslogd.

If you still have problems, try checking your DNS settings and check your MX records using Linux network commands.

Secure mailboxes from spam using SpamAssassin

One of the ways to fight spam is to scan the mailboxes by some tool, searching for certain patterns associated with spam.

One of the best solutions is SpamAssassin, which is open-source.

You can install it like this:

Then start the service and enable it at startup:

Once you’ve installed it, you can check the configuration in

SpamAssassin determines if an email is spam or not based on the result of the different scripts scores.

If the message has a higher score, that means a higher possibility of the mail being spam.

In the configuration file, the parameter required_hits 5 indicates that SpamAssassin will mark an email as spam if its score is five or higher.

The report_safe option takes the values 0, 1, or 2. If set to 0, it means email marked as spam is sent as it is, only modifying the headers to show that it is spam.

If it takes the value 1 or 2, SpamAssassin generates a new report message, and it sends the message to the recipient.

Читайте также:  Как windows увидел ext4

The value 1 means the spam message is coded as content message/rfc822, while if the value is 2, that means the message is coded as text/plain content.

The text/plain is safer since some mail clients execute message/rfc822 and could infect the client computer.

Now we need to integrate it into Postfix. The simplest way to do this is probably by using procmail.

We’ll have to create a file, named

, and add the following content:

Then we edit Postfix configuration file /etc/postfix/main.cf and change

Finally, restart Postfix and SpamAssassin services:

However, SpamAssassin sometimes does not recognize spam messages that led to mailboxes filled with spam messages.

Fortunately, you can filter messages before they enter the Postfix server using Realtime Blackhole Lists (RBLs). That will decrease the load on your mail server and keep your mail server clean.

Open the configuration file of Postfix server /etc/postfix/main.cf and change smtpd_recipient_restrictions option and add the following options like this:

Then restart your postfix server:

The above RBLs are the common ones; you can find more lists on the web and try them.

Securing SMTP connection

It is better to transfer your SMTP traffic over TLS to protect it from Man In The Middle (MITM) attack.

First, we need to generate the certificate and the key using openssl command:

Then add the following option to Postfix configuration file /etc/postfix/main.cf:

Finally, restart your postfix service:

Now, you have to choose the TLS on your client when connecting to the server.

You will receive a warning when you send a mail the first time after changing the setting because the certificate is not signed.

Using Let’s Encrypt certificates

Let’s Encrypt is a free SSL certificate provider that enables you to encrypt your traffic.

Instead of using self-signed certificates that annoy your users about trusting them, you can use this good solution.

First, install letsencrypt:

Or if you are using Debian based distro, you can use the following command:

Then run letsencrypt like this:

You should replace yourdomain.com with your actual domain.

After answering the prompted questions about the contact email, the email server domain, and the license, everything should be OK now.

The certificates will be in:

One last thing you have to do, which is making postfix use those certificates, you can use the following commands:

Don’t forget to replace yourdomain.com with your actual domain.

Finally, restart your postfix server:

POP3 and IMAP protocol basics

So far we’ve seen how SMTP mail server sends and receives emails without problems, but consider the following situations:

  • Users need local copies of email for offline viewing.
  • mbox file format is not supported. The mbox format is used by many mail user agents like mailx and mutt.
  • Users cannot stay connected to a fast network to grab a local copy to read offline.
  • Some mail servers don’t give access to the shared mail spool directories for security reasons.

To handle these cases, you should use the mail access protocols.

The most common two popular mail access protocols are Post Office Protocol (POP) and Internet Message Access Protocol (IMAP).

The idea behind POP is very simple: A central Linux mail server remains online all the time and receives and store emails for all users. All received emails are queued on the server until a user grabs them.

When a user wants to send an email, the email client relays it through the central Linux mail server via SMTP normally.

Note that the SMTP server and the POP server can be on the same system without any problem. Most servers do this today.

Features like keeping a master copy of a user’s email on the server were missing, which led to the development of IMAP.

By using IMAP, your Linux mail server will support three modes of access:

  • The online mode is similar to having direct file system access to the Linux mail server.
  • The offline mode is similar to how POP works, where the client is disconnected from the network except when grabbing an email. In this mode, the server normally does not retain a copy of the email.
  • The disconnected mode works by allowing users to keep cached copies of their emails, and the server retains a copy of the email.

There are several implementations for IMAP and POP; the most popular one is the Dovecot server, which provides both protocols.

The POP3, POP3S, IMAP, and IMAPS listen on ports 110, 995, 143, and 993 respectively.

Installing Dovecot

Most Linux distros come with Dovecot preinstalled. However, you can install Dovecot in Red Hat based distros like this:

Debian based distros provide the IMAP and POP3 functionality in two separate packages, you can install them like this:

It will ask you to create self-signed certificates for using IMAP and POP3 over SSL/TLS. Select yes and enter the hostname for your system when prompted.

Then you can run the service and enable it at startup like this:

Configure Dovecot

The main configuration file for Dovecot is

Some Linux distros put the configuration under

directory and use the include directive to include the settings in the files.

You can use the following list of the parameters to configure Dovecot:

protocols: the protocols you want to support.

lmtp means local mail transfer protocol.

listen: IP addresses to listen on.

The asterisk means all ipv4 interfaces and :: means all ipv6 interfaces

userdb: user database for authenticating users.

passdb: password database for authenticating users.

mail_location: this entry in /etc/dovecot/conf.d/10-mail.conf file:

Secure Dovecot

Dovecot comes with generic SSL certificates and key files. Look at this file:

When a user tries to connect to dovecot server, it will show a warning because the certificates are not signed, you can purchase a certificate from a certificate authority if you want.

Or if you go with Let’s Encrypt certificates, you can point to them instead:

Don’t forget to open dovecot server ports in your iptables firewall by adding iptables rules for ports 110, 995, 143, 993, 25.

Or if you are using firewalld, you can do the following:

And again, for troubleshooting, you check the log files /var/log/messages, /var/log/maillog, and /var/log/mail.log files.

Linux mail server is one of the easiest servers to work with, especially the Postfix mail server.

I hope you find the post useful and interesting. Keep coming back.

Источник

Оцените статью