Bash – Send email from a bash script using a separate postfix server

bashemailpostfix

I want to be able to send email from a bash script. I currently have a server running postfix that I use from my php server to send emails. I now want to be able to run a bash script from a third server and use the mail server to send the email as I don't want to have to have multiple servers that can send email.

Looking at this question, it appears I need to either install Python (this is a bare bones linux server without much installed) or use postfix in relay-only mode but I'm not sure what that means. Do I have to install postfix on this server and use it as a passthrough to my mail server? Are there other options for sending email to an external server from bash?

Best Answer

Well, if the emails you want to send are fairly basic, you could also just talk to your email server using basic SMTP commands and netcat.

The following bash script works just fine, it's pretty raw though...

#! /bin/bash

my_message="hello world, how's the weather today ?"
mail_srv_ip=127.0.0.1
mail_srv_port=25
recipient=jean-kevin@gmail.com

nc $mail_srv_ip $mail_srv_port << EOF
ehlo mail.script
mail from:<bashscript@local>
rcpt to:<$recipient>
data
subject: bash script email output
$message
.
quit
EOF

If the goal is to send the output of a bash script, it will work. $message can contain anything you want, smtp expects the end of the 'data' section to be marked by a line starting with a dot.