How to Send HTML Email Using Linux Command Line

How to sent Email as HTML from bash script by using mail or mailx command (Centos/Redhat)

Try it via mail (do not forget to add your variables):

mail -a "Content-type: text/html" -s "HTML message" test@gmail.com << EOF
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Title</title>
</head>
<body>
<table>
<tr>
<td> Before </td>
<td> After </td>
<td> Differece </td>
</tr><tr>
<td> $_before </td>
<td> $_after </td>
<td> $difference </td>
</tr>
</table>
Before: $_before
After: $_after
Difference: $difference
</body>
</html>
EOF

If you need send from CentOS/RedHat via mailx use it:

mail -s "$(echo -e "HTML message\nContent-Type: text/html")" test@gmail.com << EOF

Try it for outlook:

mail -s "$(echo -e "HTML message\nContent-Transfer-Encoding: 7bit\nUser-Agent: Heirloom mailx 12.4 7/29/08\nMIME-Version: 1.0\nContent-Type: text/html; charset=us-ascii\nContent-Transfer-Encoding: 7bit")" test@outlook.com << EOF
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
<title>Title</title>
...

Sending HTML mail 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" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
</head>
<body>

<p>Hello, world!</p>

</body>
</html>

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

body = '...'

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

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.

Update

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:

#!/bin/sh

echo Hello, world!

Then you assign execution permission:

chmod +x hello-world

And you can finally run it:

./hello-world

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:

http://www.gnu.org/software/bash/manual/html_node/index.html

http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO.html



Related Topics



Leave a reply



Submit