Tree Tree - 8 months ago 19
Linux Question

Sending HTML mail using a shell script

How can I send an HTML email using a shell script?


First you need to compose the message. The bare minimum is composed of these two headers:

MIME-Version: 1.0
Content-Type: text/html

... and the appropriate message body:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">

<p>Hello, world!</p>


Once you have it, you can pass the appropriate information to the mail command:

body = '...'

echo $body | mail \
-a "From:" \
-a "MIME-Version: 1.0" \
-a "Content-Type: text/html" \
-s "This is the subject" \

This is an oversimplified example, since you also need to take care of charsets, encodings, maximum line length... But this is basically the idea.

Alternatively, you can write your script in Perl or PHP rather than plain shell.


A shell script is basically a text file with Unix line endings that starts with a line called shebang that tells the shell what interpreter it must pass the file to, follow some commands in the language the interpreter understands and has execution permission (in Unix that's a file attribute). E.g., let's say you save the following as hello-world:


echo Hello, world!

Then you assign execution permission:

chmod +x hello-world

And you can finally run it:


Whatever, this is kind of unrelated to the original question. You should get familiar with basic shell scripting before doing advanced tasks with it. Here you are a couple of links about bash, a popular shell: