Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to send mails by bash script via smtp?

I have postfix+dovecot. I want to make bash script which can use SMTP for this. I don't want use sendmail.

Is it possible? May be someone has some examples of code?

like image 595
Jason Avatar asked Apr 03 '12 17:04

Jason


People also ask

Can we send email from shell script?

Use “sendmail” command This is one of the most common email-sending commands used by Linux system operators. However, you will have to install the “sendmail” program to be able to run this command. Here, the email message is saved in a file named “mail.

How do I send an email in bash?

Run `mail' command by '-s' option with email subject and the recipient email address like the following command. It will ask for Cc: address. If you don't want to use Cc: field then keep it blank and press enter. Type the message body and press Ctrl+D to send the email.

How use SMTP command in Linux?

Look up the mail exchangers for the specified domain, and connect to the specified port (default: smtp). Look up the address(es) of the specified host, and connect to the specified port (default: smtp). Connect to the host at the specified address, and connect to the specified port (default: smtp).


1 Answers

Boy, when that gauntlet is thrown, it always bashes me right upside the head! :-)

#!/bin/sh

function checkStatus {
  expect=250
  if [ $# -eq 3 ] ; then
    expect="${3}"
  fi
  if [ $1 -ne $expect ] ; then
    echo "Error: ${2}"
    exit
  fi
}

MyHost=`hostname`

read -p "Enter your mail host: " MailHost
MailPort=25

read -p "From: " FromAddr

read -p "To: " ToAddr

read -p "Subject: " Subject

read -p "Message: " Message

exec 3<>/dev/tcp/${MailHost}/${MailPort}

read -u 3 sts line
checkStatus "${sts}" "${line}" 220

echo "HELO ${MyHost}" >&3

read -u 3 sts line
checkStatus "$sts" "$line"

echo "MAIL FROM: ${FromAddr}" >&3

read -u 3 sts line
checkStatus "$sts" "$line"

echo "RCPT TO: ${ToAddr}" >&3

read -u 3 sts line
checkStatus "$sts" "$line"

echo "DATA" >&3

read -u 3 sts line
checkStatus "$sts" "$line" 354

echo "Subject: ${Subject}" >&3
echo "${Message}" >&3
echo "." >&3

read -u 3 sts line
checkStatus "$sts" "$line"
like image 64
dldnh Avatar answered Oct 06 '22 11:10

dldnh