Sending mail from linux

Отправка почты из командной строки 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_url=»smtp://smtp_user@smtp.mail.ru:465″
set smtp_pass = password
set ssl_verify_host = no
set ssl_verify_dates = no
set ssl_starttls = no
set ssl_force_tls = yes

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

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

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

Источник

16 Command Examples to Send Email From The Linux Command Line

In this post you’ll learn how to send emails from the Linux command line. I’ll show the most often used commands, SMTP configuration and terminal options.

Whether you are a developer working non-stop in the Linux command line or a server administrator wanting logs or other data extracted from administered systems, knowing how to send email from the command line is greatly useful.

In this post, you’ll find examples of how to send email from the terminal. We’ll look at custom configurations and touch on how to set up SMTP connections to email accounts or email service providers. I’ll show you how to install the necessary console mailer packages and provide background for command line options based on the package’s manuals.

Читайте также:  Заправка картриджа сам 104

Setting Up Command Line Mailer Packages

All the mailer packages throughout the tutorial are available through Debian’s Advanced Package Manager so the installation steps in the example below may be used for all the showcased packages.

Please note that these pieces of software may be installed by other default package managers such as yum or dnf depending on your Linux system distribution.

In most cases, either sendmail or postfix is available in each Linux distribution out-of-the-box or at least that’s what similar blog posts say. Either I’m unlucky or the others were wrong, but I had to install one manually. However, you definitely need one of them for email delivery.

Setting Up Sendmail with SSMTP Package

I’ll continue with sendmail and the SSMTP package. SSMTP contains the sendmail package under the hood as you’ll see and it facilitates the configuration, which is pretty hard for sendmail otherwise.

Step 1. Check if Command Line Mailer Package is Installed

Type in the mailer package’s name just the way you would run the command, to check if it’s available:

If the package is installed, the command runs, and the prompt changes — while trying to execute the command — and you’ll see a blinking cursor followed by the message Recipient names must be specified in the case of sendmail . Conclusion: the package is installed.

If the package is NOT installed, you’ll receive a warning message and a suggestion how to install it:

In this example, I tried if the sendmail command works. After we add the SSMTP package, this command and the ssmtp command will both work and change the command prompt in the terminal. Let’s look at that!

Step 2. Installing Sendmail Command Line Mailer Package

As the terminal output suggested, we need to run the Advanced Package Manager’s install command — usually with root permission — to install the necessary package. As mentioned before, the configurations are much simpler for sendmail when you abstract away the complexity of the configuration. That can be done with SSMTP:

Step 3. Verify the Installation

After the installation completed, you can check if sendmail is able to forward messages. Type the below code in the terminal:

It should send out the email if everything works correctly. Here the «hello» string piped to the sendmail command will be the subject of the sent message, while the defined email address is naturally the recipient of the email.

You run the command. and, oops: sendmail: Cannot open mailhub:25 . The reason for this is that we didn’t provide mailhub settings at all. In order to forward messages, you need an SMTP server configured. That’s where SSMTP performs really well: you just need to edit its configuration file once, and you are good to go.

Step 4. Configuring SSMTP

Let’s locate the config file at /etc/ssmtp/ssmtp.conf . Here, you should put the code below to configure an SMTP relay:

This means that you set up an external service that will actually forward
your emails. When you provide credentials to Gmail for example, you’ll see the messages sent from the terminal in your mailbox’s ‘Sent mail’ directory. The configurations look similar with other services too.

This was the basic configuration for sendmail and the installation steps for any frequently used command line mailer package. Next, we’ll jump on installing and trying out various other packages.

Sending Email Using the SSMTP Command

This is a nice little tool we just configured for mail delivery. As its man page suggests, it’s a minimalistic emulator of sendmail . As such, SSMTP allows users to transfer emails through an SMTP server from the Linux command line. It provides the means to connect to a mailhub with a proper configuration file. If your config file was set up right, all your worries regarding command line email sending can disappear.

Basic Implementation of the SSTMP command:

If you just use SSMTP, the command should look as follows:

Following the ssmtp command, you should put the recipient address, then you can include a file that will show in the email body. Here you can define headers for the message, list further recipients and set the content type. This way you can send HTML emails. SSMTP will interpret your message and use the provided values properly. Here is an example of an HTML you might send:

You can’t really give further options with SSMTP as they are not respected by its minimalistic design.

Troubleshooting:

In case you run into the following error on the command line:

that’s likely because Gmail is not treating SSMTP as a secure application. To get rid of this error, you need to change the settings in your Gmail account – you can look up more information on potential risks there as well.

Sending Email Using the Sendmail Command

For quite some time now sendmail is the classical mail transfer agent from the world of UNIX. It was first introduced in 1979 and its highly-configurable nature and scalability made it the default go-to for server administrators.

We’ve already seen how to send basic emails by the ssmtp command, so let’s see the difference using sendmail :

I threw in the -v argument, which will make the communication between the mail server and your mail transfer agent visible.

There are plenty of configurations that you can use if you set up your own mail server and implement sendmail on it. However, that is out of the scope of this article. We will return to the topic in an upcoming one. Stay tuned.

Читайте также:  Dhcp linux сервер это

Sending Email Using CURL Command

This tool is also tremendously common for data transfer from a server. It supports many protocols, like HTTP, FTP, POP3 or SMTP. The CURL package is used widely around the globe, one main reason is that it has native PHP implementation and PHP was the default server-side scripting language for a long time.

Installation:

Check if the package is already installed. If not run the below:

When you’re done, you can access the cheat sheet for the available options for CURL by running curl -h . The more detailed version is accessible by either man curl or curl —manual . If you want to gain in-depth knowledge using cURL, there’s this handy Ebook that contains everything you would ever want to know.

Basic implementation for email sending with CURL:

In order to send an email with CURL, you need to set up SMTP connection. Most often Google’s or Yahoo’s outgoing mail servers are used for testing email sending with SMTP. Please note that you must turn on access for less secure apps in Gmail settings and similar additional security settings may apply for Yahoo as well.

In the terminal command snippet above, the —url and —user parameters define the SMTP connection settings. The password section for —user parameter is your account’s password for the given email address. Naturally, you could also use cloud email service providers. I will show that using Mailgun in the following section.

Advanced implementation for email sending with CURL:

Working with email delivery platforms, you first need to obtain an API key. In this tutorial, I’ll show CURL email sending example using Mailgun, so if you get stuck during the registration process follow this setup guide to get on the right track.

The syntax is pretty straightforward. You may have noticed before, but you need to end each line of the command with \ characters. This is a line continuation character, the command can be run without them all in one line as well. The other thing to remember is the -F option. An excerpt from the man page:

As I encouraged before, it’s a good practice to dive into the manuals when using these command line mailer commands. As the CURL manual says, basically you’re creating a form to send. Each line is an entry given as a name=content pair. When you attach files from your local machine, you need an @ in front of the file name.

This is how the delivered email will look like:

You could do the same using most of the other email delivery platforms, like Sendgrid for example.

Sending HTML email from the command line with CURL:

You can apply the same logic of building a form in a text file, which enables you to send HTML messages easily:

If you run the simple command from the first example.

. and direct the —upload-file parameter to the updated text file (mail.txt in our case), the received message will show the HTML content.

Troubleshooting:

You may need the —insecure switch, which allows CURL to perform «insecure» SSL connections and transfers. CURL will return an error message if the remote server is using a self-signed certificate, or if the remote server certificate is not signed by a CA listed in the CA cert file.

Sending Email Using Swaks command

As their documentation states, Swaks is a flexible, scriptable, transaction-oriented SMTP test tool. It is able to handle SMTP features and extensions such as TLS, authentication, and pipelining and multiple version of the SMTP protocols. It also supports multiple transport methods including UNIX-domain sockets, internet-domain sockets, and pipes to spawned processes.

Installation:

Basic implementation for email sending with Swaks:

In order to connect to an SMTP account you need to provide the server -s , the user -au , the password -ap and the address -t (where you want to send your mail) flags. The -tls flag is also important if you connect on port 587 .

The credentials can also be provided via command line prompts, if you only specify to authenticate -a , not filling in the user and password through command line options.

Advanced implementation for email sending with Swaks:

There are other options which we will not touch now. Let’s head to our next mailer package!

Sending Email Using the Mutt Command

Mutt is different from the previous email clients, as it is a feature-rich command line email client. You can use it for reading emails from the Linux terminal, connecting to local user mailboxes or to POP/IMAP servers. Mutt supports several mailbox formats such as mbox, MH, maildir, MMDF, full control of message headers during email composition, and multiple message tagging and colors to handle messages.

Installation:

Basic implementation for email sending with mutt:

By this time you won’t be surprised by the structure of the command. You can provide an empty message body with :

Advanced implementation for email sending with mutt:

For sending email including attachments, you need the -a flag. This way you can send useful files, like system logs, to a specified address.

You could also send HTML email if the file extension you add to the message body is in HTML format. Mutt will recognize the file type and resolve it so it won’t send your HTML as plain text:

Читайте также:  Картридер что это для чего нужен

This is it for email sending with mutt. If you have it on your machine, I’d suggest to try out how you can work with incoming configuring your mailbox and handling incoming messages. If you do so, please share your thoughts in the comment section below. I welcome any opinion about the packages shown in the tutorial.

Sending Email Using the Mailx Command

The Mailutils is a compound package for multiple use cases. It’s designed to serve regular users, system administrators, and developers. We’ll only touch on its basic functionalities regarding email forwarding. If you are interested in more features, check out its man page.

Installation:

Basic implementation for email sending with mailx:

The mailx package has 2 equal command syntax ( mail and mailx both work in the exact same way). The most simplistic command consists of the mail/mailx command and the address to send the mail to, but you would probably include the subject and at least some text-based message body. Such a command should look like this:

By using the echo command and piping the output to the mail command, you can avoid mailx’s additional prompts for Cc addresses and the message body.

Advanced implementation for email sending with mailx:

For the advanced example, we will send a full-fledged HTML email again. We need to provide the email HTML file of our choice with the character and add the «append flag» with the content type. The full code looks as follows:

You can also set a return address with —return-address= , which may be useful. Another useful option, which I couldn’t resolve to work with HTML email parallel, is to provide attachments in the same message: -A «mail.txt» . Though you can list multiple recipients, only a single attachment can be attached. You could configure external SMTP server if that fancies you.

Using Telnet Alternative Openssl Command

Telnet is an interactive communication protocol for communication with another host. It could be used to open an SMTP connection to another server and transfer email messages. However, as the protocol is not secured, most servers will reject this communication type. This is where Openssl comes into the picture as it’s built with SSL/TLS security included. It is invoked similarly to telnet with a host argument, and it performs an open command implicitly:

I indented the inputs you need to provide while the communication channel is open. These inputs are self-explanatory, but one thing I need to detail is the password hash. It can be a base64 encoded hash, which you can obtain with the following command: echo -en ‘\000username@gmail.com\000gmailpassword’ | base64 . The escape characters from the string can’t be omitted. If you don’t have the base64 package installed, it is available through package managers.

As you can see above, this means of email sending only provides an interface for text-based messages, therefore it has its limitation in use cases. On the other hand, it shows all information exchanged with the mail server, which makes debugging really easy.

Troubleshooting Mail Problems

Check the mail logs

You need to locate your log file by navigating to the corresponding folder. I prefer to use my code editor (eg. Sublime Text) for this so I can have the logs with syntax highlight:

Depending on your current Linux distribution you may need to look at different source.
The log may contain useful information about deliverability problems. At this point, when you scroll to the bottom of this:

you can inspect if delivery is successful or understand why the process failed.
It can happen that your console shows no errors, but in the mail log you can see that the message was queued for delivery, so the process didn’t halt on your machine but probably was denied by the mail server you were trying to reach.

Running All Command in a Sequence

So, everything is ready for the final test. All the mailer terminal commands are gathered here in a script file. Once you downloaded the working folder with the script file in it, navigate to the containing folder and make the script executable: chmod u+x mail.sh . If you have all the files I provided ready, you can start testing the mailer commands shown in the tutorial. You just need to replace the » » to your test email address in the code and run ./mail.sh in the command line.

Once the script finishes running, your inbox will be filled with the test emails.

Summary

In this article, I showed you many ways to send email from the Linux command line. Hopefully, based on what you saw, you can install and configure these services on your machine yourself as well.

The post showed the most commonly used command line mailer packages and how to send emails with them, and in the end, I created a shell script that gathers all the commands used in the article. You can download the projects working files here, and if you install the packages introduced in the tutorial and also fill in your credentials and recipient details, you can run the script at your leisure.

Could you follow each step of the tutorial? Very well then, it makes me glad. In case you have questions or see an opportunity to improve the content further by your ideas, please head to the comment section below.

Источник

Поделиться с друзьями
КомпСовет
Adblock
detector