Linux send email to smtp

How to send mail from the command line?

Re Out of date answers: I got this answer below to work, sending from a gmail account, after enabling «Less secure app access» in gmail settings, in 2020.

16 Answers 16

sudo apt-get install ssmtp 
gksu gedit /etc/ssmtp/ssmtp.conf 
root=username@gmail.com mailhub=smtp.gmail.com:465 rewriteDomain=gmail.com AuthUser=username AuthPass=password FromLineOverride=YES UseTLS=YES 
ssmtp recepient_name@gmail.com 
To: recipient_name@gmail.com From: username@gmail.com Subject: Sent from a terminal! Your content goes here. Lorem ipsum dolor sit amet, consectetur adipisicing. (Notice the blank space between the subject and the body.) 

You can also put the text in file and send it as follows:

ssmtp recipient_name@gmail.com < filename.txt 

@oadams not very safe. Use 2-step verification to lower your risk, or use a mail gateway that doesn't require a password, like your ISP's.

Don't install ssmtp on a server with postfix installed. Postfix will be removed. Instead, just use sendmail user@example.com < file.txt which will work with either postfix or ssmtp.

Another weird thing that I wanted to share here is, it didn't worked for me when I had a long/complex password but worked when I modified it to a simple password, strange but true. I also heard the same from someone else but tried it after lots of unsuccessful attempts to send mail & as soon as I simplified the password, to my surprise, it just worked 😉

If Gmail doesn't allow your server to access, login to Gmail on the server with command line browser. askubuntu.com/questions/460022/using-terminal-as-a-web-browser

Most of the time you shouldn't need to configure an SMTP server you can simply use mail from the commandline (if it's not already present, install with sudo apt-get install mailutils ). (Or if you're on a server where sendmail is configured, etc)

marco@dagobah:~$ mail -v marco.ceppi.use@gmail.com Subject: Hello World! This is an email to myself. Hope all is well. . Cc: 

You terminate messages with a single . on line. That's when mail will prompt you for Cc: enter the information (or leave blank) and mail will then print out additional information on what it is attempting to do, as well as detailing the processing of connecting, transmitting, and receiving data from the mail server.

I would append the answer to include "sudo apt-get install mailutils" since it is not present on a clean Ubuntu 10.04 install. Also, terminating the message with a . on a single line didn't work. I had to "Ctrl-D" instead. Lastly, the message didn't go through!

@OlivierLalonde sudo apt-get install mailutils will install a SMTP server which is postfix , which might be a little overweighted for some people.

sendemail -f fromuser@gmail.com -t touser@domain.com -u subject -m "message" -s smtp.gmail.com:587 -o tls=yes -xu gmailaccount@gmail.com -xp gmailpassword 

If you don't want to specify your password in the command line (generally not a good thing to do), you can omit that parameter and sendemail will prompt you for the password. and display it on the screen, but at least it won't be in your command line history.

Читайте также:  Настройка экрана ubuntu linux

another way to not display it on the bash screen: save password to a file, then from file to environment variable, ex: pass=$(cat my_password); sendemail. -xp $name . and of course if you're calling it programmatically you can do something similar, ex: ruby system("sendemail . -xp #. ") also it might fail the first time, you should get an email to that account suggesting you "enable less secure apps" then it can work.

Try to install The Mutt E-mail Client. Other option is using emacs with gnus. Others options available too. IMHO, you should use more details in your questions, or several different answers to your question you will receive 🙂

You need an MTA to send mail. For this, use postfix:

sudo apt-get install postfix 
echo "test message" | mailx -s 'test subject' myemail@mydomain.com 

I wish it were really this simple, but unless you're someone very special, this isn't going to work. 99.9999% of ISPs will ignore mail from private postfix servers, because 9.99999 times out of 10 they're spammers.

@Cerin is right. I needed very simple mailing functionality for a cron job though. As a workaround, if you're receiving via a gmail account, you can set up a filter for the email (via keywords or the from address) and gmail will allow it to be sent.

mpack is excellent commandline way of sending file attachments.

mpack -s "file you wanted" ./data.pdf loser@supergoober.cn 

Install the package sendmail then type

sendmail -t receiver@example 

then write your email then press Ctrl+D

mail -s "subjet" -a "attchedfile_name" someone@dest_email.com 
cat "afile" | mail -s "subject" someone@dest_email.com 

If someone doesn't have the mail command, just run: sudo apt-get install mailutils in Ubuntu/Debian or yum install mailx in CentOS/Redhat

You can send an email from the command line with TelNet or NetCat.

hanoo@hp_laptop% nc 127.0.0.1 25 220 hp_laptop.localdomain ESMTP Postfix EHLO man 250 hp_laptop.localdomain MAIL FROM: 250 2.1.0 Ok RCPT TO: 250 2.1.5 Ok data 354 End data with . This is the body of my mail, this is the second line. . 250 2.0.0 Ok: queued as 9C12E7F404 

If you try to send e-mail from a system, whitch does not run an own e-mail-server (i. e. desktop system), you need to install something like nullmailer or esmtp, which forward your local mail to a "real" mail server.

Читайте также:  Linux убрать запрос пароля

As command line tools you can install mail or mailx (packages mailutils, heirloom-mailx or bsd-mailx). If you need attachments try biabam.

sudo apt-get install sharutils mailutils uuencode filename filename | mail user@example.com 

where filename is the same: it stands for input file and remote file.

I have never tried it but there is a mail command that can send mail. See man mail.

echo message | mail username@localhost 
mail name@mailserver.com -s "Attached file"  

It works with GNU Mailutils, check the website for more information.

sudo apt-get install ssmtp sudo -H gedit /etc/ssmtp/ssmtp.conf 

The following needs to be added there:

# The user that gets all the mails (UID < 1000, usually the admin) root=yourusernameofgmail@gmail.com # The mail server (where the mail is sent to), both port 465 or 587 should be acceptable # See also https://support.google.com/mail/answer/78799 mailhub=smtp.gmail.com:587 # The address where the mail appears to come from for user authentication. rewriteDomain=gmail.com # Use SSL/TLS before starting negotiation UseTLS=Yes UseSTARTTLS=Yes # Username/Password AuthUser=yourusernameofgmail AuthPass=yourGmailPassowrd AuthMethod=LOGIN # Email 'From header's can override the default domain? FromLineOverride=yes 
sudo -H gedit /etc/ssmtp/revaliases 
root:yourusernameofgmail@gmail.com:smtp.gmail.com:587 

Test it by running the following on terminal:

echo "Body of mail is abc" | mail -s "Subject is xyz" "someusername@gmail.com"` 

You can use cURL. Take a file like this:

From: Sunday To: Monday Subject: Tuesday Wednesday 
curl \ --netrc \ --mail-rcpt monday@gmail.com \ --upload-file a.txt \ smtps://smtp.gmail.com 

I want to add another quite simple yet interesting way to do, provided by AWS (link)

So, you need to prepare this text file, save it as input.txt . Please remember to change the values:

  • Replace example.com with your sending domain.
  • Replace Base64EncodedSMTPUserName with your base64-encoded SMTP username.
  • Replace Base64EncodedSMTPPassword with your base64-encoded SMTP password.
  • Replace sender@example.com with the email address you are sending from. This identity must be verified.
  • Replace recipient@example.com with the destination email address. If your Amazon SES account is still in the sandbox, this address must be verified.
EHLO example.com AUTH LOGIN Base64EncodedSMTPUserName Base64EncodedSMTPPassword MAIL FROM: sender@example.com RCPT TO: recipient@example.com DATA From: Sender Name To: recipient@example.com Subject: Amazon SES SMTP Test This message was sent using the Amazon SES SMTP interface. . QUIT 
openssl s_client -crlf -quiet -starttls smtp -connect smtp-server-endpoint:587 < input.txt 
openssl s_client -crlf -quiet -connect smtp-server-endpoint:465 < input.txt 

Impatient SMTP servers

If you face Client host rejected: Improper use of SMTP command pipelining errors, try waiting for the responses:

openssl s_client -crlf -quiet -starttls smtp -connect smtp.example.com:587 < \ <( echo "EHLO foo.tld" sleep 2 echo "AUTH LOGIN" sleep 2 echo "Base64EncodedSMTPUserName" sleep 2 echo "Base64EncodedSMTPPassword" sleep 2 echo "MAIL FROM: sender@example.com" sleep 2 echo "RCPT TO: recipient@example.com" sleep 2 echo "DATA" sleep 2 echo "Sender Name " echo "recipient@example.com" echo "Subject: Test" echo "" echo "Lorem Ipsum" echo "." echo "QUIT" ) 

Источник

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

Обновлено

Обновлено: 05.05.2022 Опубликовано: 31.03.2017

Подготовка

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

Синтаксис

* в данном примере будет отправлено письмо на электронный адрес master@dmosk.ru с темой Test title и телом письма — Test text. Если при отправке возникли проблемы, можно проверить логи следующей командой:

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

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

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. Несколько получателей

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

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

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

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

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

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

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

При возникновении проблем, можно воспользоваться программой mutt. Сначала поставим ее. а) если используем CentOS / Red Hat:

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

echo "Mail From" | mutt -s "subject" -e 'my_hdr From: Дмитрий ' -- master@dmosk.ru

* данной командой 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: Дмитрий ' -- master@dmosk.ru

Источник

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