2

I want to create a script that will be able to send mail easily with the user choices.

I did this but it does not work

mail_sender ()
{
    echo " - FROM : "
    read from
    echo " - TO : "
    read to
    echo " - Subject : "
    read subject
    echo " - Message : "
    read message
    telnet localhost 25
    ehlo triton.itinet.fr
    mail from: $from
    rcpt to: $to
    data
    subject: $subject
    $message
    .
}

Do you have an idea ?

Michael003
  • 420
  • 2
  • 6
  • 15
  • 2
    Does it show any error message? – Jdamian Nov 28 '16 at 10:59
  • 2
    I think you should learn about [bash here documents](http://www.gnu.org/software/bash/manual/bash.html#Here-Documents). – Jdamian Nov 28 '16 at 11:02
  • 2
    Do you know the [mailx command](http://stackoverflow.com/questions/2282506/how-can-i-send-an-email-through-unix-mailx-command)? – Jdamian Nov 28 '16 at 11:04
  • It does not recognized the commands because when I type telnet localhost 25, it's part of a new prompt, so my commands are not entered – Michael003 Nov 28 '16 at 11:23
  • 1
    You are trying to pass telnet instructions through a bash script. This is absolutely not how it works. Have a look at `expect`. – Aserre Nov 28 '16 at 11:23

2 Answers2

2

Redirect to telnet a here-document:

mail_sender ()
{
    echo " - FROM : "
    read from
    echo " - TO : "
    read to
    echo " - Subject : "
    read subject
    echo " - Message : "
    read message
    telnet localhost 25 << EOF
ehlo triton.itinet.fr
mail from: $from
rcpt to: $to
data
subject: $subject
$message
.
EOF
}

The content of the here-document will be redirected to telnet, effectively executing these SMTP commands in the mail server's shell.

It's important that the lines within the here-document don't have any indentation at all (no spaces or tabs at the start of the lines). Notice that the indentation looks kind of broken in the way I wrote it above, halfway in mail_sender. It has to be this way, because that's how here-documents work.

You can read more about here-documents and input redirection in man bash.

janos
  • 120,954
  • 29
  • 226
  • 236
  • 1
    Should probably use `-r` on `read`, to allow messages that contain literal backslashes; and maybe clear IFS, to allow leading whitespace. – Charles Duffy Nov 29 '16 at 22:30
0

I've only used it for the simplest of testing:

http://www.jetmore.org/john/code/swaks/

but it boasts:

Completely scriptable configuration, with option specification via environment variables, configuration files, and command line

so no need to re-invent the wheel here..

Thufir
  • 8,216
  • 28
  • 125
  • 273