Linux smtp send email

Отправка почты из командной строки 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. Отправить вложение:

Читайте также:  Closing the windows form

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: Дмитрий

Источник

Send mail from command line with external smtp server on Linux

Send mail via SMTP servers

The default mail command on the Linux terminal, uses the local smtp server (mta) on port 25 to send emails. However at times you need to specify an external smtp server to use for sending mails.

For example you have just setup an smtp server, like Postfix or Exim, then you would want to test it out to check if it is receiving and relaying emails properly or not.

Being able to send mails from command line using this external smtp server is quick rather than having to setup a mail client like Thunderbird on your local machine.

There are 2 command line utilites called mailx and swaks that can be used to send mails using external smtp server. These are quite useful when you need to send emails from a bash script in an automated manner.

1. mailx command

The mailx command is available from many different packages like mailutils, heirloom-mailx etc. First you need to use the aptitude command to search the mailx package available for your system. Here is an example

To find out which mailx command your system is using, run the readlink command. Here is a sample output.

Not all mailx variants can use external smtp servers to send mail. Only the one that comes from the s-nail package (pulled by heirloom-mailx) can do it.

We shall be using heirloom-mailx since it allows to specify smtp connection details in a single command and issue and email quickly.

Now send an email with an external smtp server like this —

Here is a step by step version of the same command —

Make sure to use the correct settings, like port number, authentication mechanism etc. The command would produce verbose output giving full details of the smtp communication that goes on behind, making it very easy to test and debug.

Note: The package heirloom-mailx was removed from Ubuntu version 18 onwards. Now you have to install the s-nail package.

The s-nail command is the same as heirloom mailx command. Just the name is different. Run the same command above by replacing mailx with s-nail and it should work.

If you are using the latest version of s-nail (14.9.x) the syntax for specifying the smtp server details might be slightly different. Check the latest manual here

2. Swaks command

Swaks (Swiss army knife for SMTP) is a simple command line tool that can be used to test smtp servers to check if they are doing they job properly. It supports TLS as well.

Install swaks on Ubuntu/Debian with the following command

Now send the email

All the options are pretty self explanatory. The «—server» option specifies the external SMTP server to use, «—auth» specifies the type of authentication. The «-tls» option tells swaks to use STARTTLS.

Читайте также:  Windows media services support

Check the man page for more options.

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected] .

5 thoughts on “ Send mail from command line with external smtp server on Linux ”

telnet your.smtp.server 25
HELO your.ip
MAIL FROM:
RCPT TO:
DATA
Subject: YOUR SUBJECT
Your message then end with a point
.
(then disconnect)

I use Thunderbird as a mail client and have been experimenting with sending mail through Thunderbird via the bash command line. I want to be able to send an email within a bash script.

I can successfully make Thunderbird open a compose window to send a mail, but I really want it to happen in the background with NO human interaction. Is there an option I can give Thunderbird on the command line to send the message straight away ?

This is what I’ve got so far :-

thunderbird -compose “preselectid=id3,[email protected],subject=’Dropbox Sync Log `date +%D`’,body=’`cat

I fully realise I don’t need to attach a file as well as catting it into the message. I’ve just left it in to show that attachments are possible from the command line, that’s all.

If someone knows how to make Thunderbird actually send the email from the command line instead of opening a window in Thunderbird client, I’d be delighted to hear from you.

Thanks a lot. very useful.

–body is required for swaks in order to read message body from standard input; otherwise the default body of “This is a test mailing” will be used.

[QUOTE from man]
–body [body-specification]
Specify the body of the email. The default is “This is a test
mailing”. If no argument to –body is given, prompt to supply one
interactively. If ‘-‘ is supplied, the body will be read from
standard input. If any other text is provided and the text
represents an open-able file, the content of that file is used as
the body. If it does not represent an open-able file, the text
itself is used as the body.

If the message is forced to MIME format (see –attach) the argument
to this option will be included unencoded as the first MIME part.
Its content-type will always be text/plain.

Hi, great examples to connect to a smtp server from command line. I also like this: https://github.com/gasparfm/gscripts/blob/master/gemail.sh It uses sendmail (you can have nullmailer configured to connect to a smtp server). The best of it is that you can send attachments.

I use it to send by emails files generated directly on a server.

Источник

How to Send Email via SMTP Server from Linux Command Line (with SSMTP)

In the Global word, we always want to keep connected to everyone. To accomplish this email is also a very popular method to send and receive information. Linux systems also provide tools to send emails from the command line which is used to get system details, to send emails from shell scripts etc.

When we simply send email from Linux terminal, email sends as system [email protected] Some of the SMTP servers can block these emails or mark them as spam. So we need a process which maximizes the email delivery to the inbox. Using this article we are configuring our server to send email from SMTP servers like Gmail, Amazon SES etc. This article will help you setup SSMTP server and send email through Gmail servers.

Step 1 – Install SSMTP Server

SSMTP service packages are available under EPEL repository, So make you have EPEL yum repository configured in your system.

Step 2 – Configure SSMTP

Now edit SSMTP configuration file and add the following values. For this tutorial, I am using the Gmail SMTP server. If you also want to set up with Gmail, make sure you have an email account with Gmail.

Читайте также:  Драйвера hp deskjet 3050 для windows 10

Change the following values in the configuration file

The above details are as followings,

  • mailhub: your smtp server host/ip with port.
  • UseSTARTTLS: Set it Yes if SMTP server uses TLS else No.
  • AuthUser: Use Gmail ID here
  • AuthPass: Use Gmail ID’s password
  • TLS_CA_File: This may required some time, If you face issue like “send-mail: Cannot open smtp.gmail.com:587”

Step 3 – Send Test Email

Now test the setup by sending a test email to an email address. First compose the mail in text file like:

Add email content, for example:

Then send email to “[email protected]” using the ssmtp command:

Let’s check your mailbox for the new email.

Step 4 — Setup SSMTP as Default

Now set SSMTP as your default mail server, So that you can simply use mail command to send emails through SSMTP.

Источник

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.

Источник

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