This question already has answers here:
Sending HTML mail using a shell script
(13 answers)
How do I send a file as an email attachment using Linux command line?
(25 answers)
Closed 4 years ago.
I want to send a html message with Mailx. When I try the following command
mailx -s "Subject" user#gmail.com < email.html
I get the content of email.html in plain text. In the message the header Content-Type is set to text/plain. The -a option tries to send a file so I didn't find out how to modify the header. This answer almost worked, it sets well the Content-Type to text/html but doesn't substitute the default Content-Type which is text/plain.
mailx -s "$(echo -e "This is the subject\nContent-Type: text/html")" user#gmail.com < email.html
gives this result :
From: send#gmail.com
To: user#gmail.com
Subject: This is the subject
Content-Type: text/html
Message-ID: <538d7b66.Xs0x9HsxnJKUFWuI%maikeul06#gmail.com>
User-Agent: Heirloom mailx 12.4 7/29/08
MIME-Version: 1.0
boundary="=_538d7b66.z5gaIQnlwb1f/AOkuuC+GwF1evCaG/XIHQMbMMxbY6satTjK"
This is a multi-part message in MIME format.
--=_538d7b66.z5gaIQnlwb1f/AOkuuC+GwF1evCaG/XIHQMbMMxbY6satTjK
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
Content-Disposition: inline
<html>
<body>
<p>Helo wolrd</p>
</body>
</html>
PS : I also tried with uuencode. When I try to display the message in the webmail I get a blank page...
It's easy, if your mailx command supports the -a (append header) option:
$ mailx -a 'Content-Type: text/html' -s "my subject" user#gmail.com < email.html
If it doesn't, try using sendmail:
# create a header file
$ cat mailheader
To: user#gmail.com
Subject: my subject
Content-Type: text/html
# send
$ cat mailheader email.html | sendmail -t
There are many different versions of mail around. When you go beyond mail -s subject to1#address1 to2#address2
With some mailx implementations, e.g. from mailutils on Ubuntu or
Debian's bsd-mailx, it's easy, because there's an option for that.
mailx -a 'Content-Type: text/html' -s "Subject" to#address <test.html
With the Heirloom mailx, there's no convenient way. One possibility
to insert arbitrary headers is to set editheaders=1 and use an
external editor (which can be a script).
## Prepare a temporary script that will serve as an editor.
## This script will be passed to ed.
temp_script=$(mktemp)
cat <<'EOF' >>"$temp_script"
1a
Content-Type: text/html
.
$r test.html
w
q
EOF
## Call mailx, and tell it to invoke the editor script
EDITOR="ed -s $temp_script" heirloom-mailx -S editheaders=1 -s "Subject" to#address <<EOF
~e
.
EOF
rm -f "$temp_script"
With a general POSIX mailx, I don't know how to get at headers.
If you're going to use any mail or mailx, keep in mind that
This isn't portable even within a given Linux distribution. For example, both Ubuntu and Debian have several alternatives for mail and mailx.
When composing a message, mail and mailx treats lines beginning with ~ as commands. If you pipe text into mail, you need to arrange for this text not to contain lines beginning with ~.
If you're going to install software anyway, you might as well install something more predictable than mail/Mail/mailx. For example, mutt. With Mutt, you can supply most headers in the input with the -H option, but not Content-Type, which needs to be set via a mutt option.
mutt -e 'set content_type=text/html' -s 'hello' 'to#address' <test.html
Or you can invoke sendmail directly. There are several versions of sendmail out there, but they all support sendmail -t to send a mail in the simplest fashion, reading the list of recipients from the mail. (I think they don't all support Bcc:.) On most systems, sendmail isn't in the usual $PATH, it's in /usr/sbin or /usr/lib.
cat <<'EOF' - test.html | /usr/sbin/sendmail -t
To: to#address
Subject: hello
Content-Type: text/html
EOF
I had successfully used the following on Arch Linux (where the -a flag is used for attachments) for several years:
mailx -s "The Subject $(echo -e \\\nContent-Type: text/html)" user#gmail.com < email.html
This appended the Content-Type header to the subject header, which worked great until a recent update. Now the new line is filtered out of the -s subject. Presumably, this was done to improve security.
Instead of relying on hacking the subject line, I now use a bash subshell:
(
echo -e "Content-Type: text/html\n"
cat mail.html
) | mail -s "The Subject" -t user#gmail.com
And since we are really only using mailx's subject flag, it seems there is no reason not to switch to sendmail as suggested by #dogbane:
(
echo "To: user#gmail.com"
echo "Subject: The Subject"
echo "Content-Type: text/html"
echo
cat mail.html
) | sendmail -t
The use of bash subshells avoids having to create a temporary file.
EMAILCC=" -c user1#dominio.cl,user2#dominio.cl"
TURNO_EMAIL="user#dominio.cl"
mailx $EMAILCC -s "$(echo "Status: Control Aplicactivo \nContent-Type: text/html")" $TURNO_EMAIL < tmp.tmp
Well, the "-a" mail and mailx in Centos7 is "attach file" not "append header." My shortest path to a solution on Centos7 from here:
stackexchange.com
Basically:
yum install mutt
mutt -e 'set content_type=text/html' -s 'My subject' me#my.com < msg.html
If you use AIX try this
This will attach a text file and include a HTML body
If this does not work catch the output in the /var/spool/mqueue
#!/usr/bin/kWh
if (( $# < 1 ))
then
echo "\n\tSyntax: $(basename) MAILTO SUBJECT BODY.html ATTACH.txt "
echo "\tmailzatt"
exit
fi
export MAILTO=${1-noreply#visweb.co.za}
MAILFROM=$(whoami)
SUBJECT=${2-"mailzatt"}
export BODY=${3-/apps/bin/attch.txt}
export ATTACH=${4-/apps/bin/attch.txt}
export HST=$(hostname)
#export BODY="/wrk/stocksum/report.html"
#export ATTACH="/wrk/stocksum/Report.txt"
#export MAILPART=`uuidgen` ## Generates Unique ID
#export MAILPART_BODY=`uuidgen` ## Generates Unique ID
export MAILPART="==".$(date +%d%S)."===" ## Generates Unique ID
export MAILPART_BODY="==".$(date +%d%Sbody)."===" ## Generates Unique ID
(
echo "To: $MAILTO"
echo "From: mailmate#$HST "
echo "Subject: $SUBJECT"
echo "MIME-Version: 1.0"
echo "Content-Type: multipart/mixed; boundary=\"$MAILPART\""
echo ""
echo "--$MAILPART"
echo "Content-Type: multipart/alternative; boundary=\"$MAILPART_BODY\""
echo ""
echo ""
echo "--$MAILPART_BODY"
echo "Content-Type: text/html"
echo "Content-Disposition: inline"
cat $BODY
echo ""
echo "--$MAILPART_BODY--"
echo ""
echo "--$MAILPART"
echo "Content-Type: text/plain"
echo "Content-Disposition: attachment; filename=\"$(basename $ATTACH)\""
echo ""
cat $ATTACH
echo ""
echo "--${MAILPART}--"
) | /usr/sbin/sendmail -t
Related
I'm trying to get the output of an awk command to be formatted into a JSON. I don't have much experience with awk or regex to get this to format correctly. The script is taking raw data from Apache by tailing the access logs and parsing out the data I want using awk.
I've spent about an hour googling and trying different formats. The best setup I currently have is the following code.
awk:
awk -F " " '{
print "{\"ipAddr\":\"" $1 "\",\"reqType\":\"" $4 "\",\"reqItem\":\"" $5
"\",\"reqStatus\":\"" $7 "\",\"reqUrl\":\"" $8 "\"}"
}' temp1.log >> hmReq.log;
The output I'm currently getting is:
{"{\"ipAddr\":\"my.ip.Addr\",
\"reqType\":\"GET\",
\"reqItem\":\"/contact\",
\"reqStatus\":\"200\",
\"reqUrl\":\"\"https://www.example.com/\"\"}":""}
I'm trying to get it to be like so:
{
"ipAddr":"123.456.789.0",
"reqType":"GET",
"reqItem":"/contact",
"reqStatus":"200",
"reqUrl":"www.com"
}
Any help is greatly appreciated!
EDIT:
This is the entire script:
inotifywait -m ~/hmLogs/a2access.log -e modify | while read path action file; do
cd ~/hmLogs
tail -n1 a2access.log >> temp1.log;
awk -F " " '{
print "{\"ipAddr\":\"" $1 "\",\"reqType\":\"" $4 "\",\"reqItem\":\""
$5 "\",\"reqStatus\":\"" $7 "\",\"reqUrl\":\""
$8 "\"}"}' temp1.log >> hmReq.log;
curl -s -w "\n" -d #hmReq.log -X POST http://localhost:8080/logs >> hmRes.log;
rm hmReq.log;
rm temp1.log;
cd -;
done;
Sample of raw data input from apache2/access.log:
161.69.99.11 [01/Aug/2019:03:59:35 +0000] GET /static/js/2.59e222c7.chunk.js HTTP/1.1 200 "https://www.tjbrackett.com/"
Literally my first Linux script so I'm sure I'm doing something wrong.
EDIT 2:
This is the contents of temp1.log before and after the awk.
Before:
76.20.106.208 [01/Aug/2019:17:08:40 +0000] GET /static/media/rock.1bacda84.jpg HTTP/1.1 200 "https://www.tjbrackett.com/about"
After:
76.20.106.208 [01/Aug/2019:17:08:40 +0000] GET /static/media/rock.1bacda84.jpg HTTP/1.1 200 "https://www.tjbrackett.com/about"
EDIT 3:
It seems the output is correct but for whatever reason, the response from the Express app is being weird. Also, the only issue now is that there is an extra set of quotations around the URL.
I am trying to send an email as html.
#!/bin/sh
#MAIL_LIST="gangadhar.n#xx.com"
MAIL_SENDER=foo
fnSendEmail(){
echo ${BODY}| mail -r $MAIL_SENDER -s "$(echo "$MAIL_SUBJECT\nContent-Type: text/html")" "$MAIL_LIST"
}
MAIL_SUBJECT="Test email"
BODY="<html><body><div><h2>Hi All</h2><hr></div></body></html>";
fnSendEmail $BODY $MAIL_SENDER $MAIL_SUBJECT $MAIL_LIST
I am receiving email but html tags and Content type also visible in mails as below.
Subject as
"Test email\nContent-Type: text/html"
Email body as:
<html><body><div><h2>Hi All</h2><hr></div></body></html> NOTICE TO RECIPIENT: If you are not the intended recipient of this e-mail, you are prohibited from sharing, copying, or otherwise using or disclosing its contents. If you have received this e-mail in error, please notify the sender immediately by reply e-mail and permanently delete this e-mail and any attachments without reading, forwarding or saving them. Thank you.
Thank you in advance
I have done it using sendmail
#MAIL_LIST1="Gangadhar.N#xx.com"
MAIL_SENDER=dap
fnSendEmail(){
(
echo To: $MAIL_LIST
echo Cc: $MAIL_LIST
echo From: dap53
echo "Content-Type: text/html; "
echo Subject: $MAIL_SUBJECT
echo
echo $BODY
) | /usr/sbin/sendmail -t
}
MAIL_SUBJECT="Test email"
BODY="<html><body>Sample</body></html>"
fnSendEmail $BODY $MAIL_SENDER $MAIL_SUBJECT $MAIL_LIST
Use option -a to append content-type header, -s is for subject, change your fnSendEmail to following it should work
fnSendEmail(){
echo ${BODY}| mail -r $MAIL_SENDER -a "Content-type: text/html" -s "$(echo "$MAIL_SUBJECT\n")" "$MAIL_LIST"
}
I was wondering how to parse the CURL JSON output from the server into variables.
Currently, I have -
curl -X POST -H "Content: agent-type: application/x-www-form-urlencoded" https://www.toontownrewritten.com/api/login?format=json -d username="$USERNAME" -d password="$PASSWORD" | python -m json.tool
But it only outputs the JSON from the server and then have it parsed, like so:
{
"eta": "0",
"position": "0",
"queueToken": "6bee9e85-343f-41c7-a4d3-156f901da615",
"success": "delayed"
}
But how do I put - for example the success value above returned from the server into a variable $SUCCESS and have the value as delayed & have queueToken as a variable $queueToken and 6bee9e85-343f-41c7-a4d3-156f901da615 as a value?
Then when I use-
echo "$SUCCESS"
it shows this as the output -
delayed
And when I use
echo "$queueToken"
and the output as
6bee9e85-343f-41c7-a4d3-156f901da615
Thanks!
Find and install jq (https://stedolan.github.io/jq/). jq is a JSON parser. JSON is not reliably parsed by line-oriented tools like sed because, like XML, JSON is not a line-oriented data format.
In terms of your question:
source <(
curl -X POST -H "$content_type" "$url" -d username="$USERNAME" -d password="$PASSWORD" |
jq -r '. as $h | keys | map(. + "=\"" + $h[.] + "\"") | .[]'
)
The jq syntax is a bit weird, I'm still working on it. It's basically a series of filters, each pipe taking the previous input and transforming it. In this case, the end result is some lines that look like variable="value"
This answer uses bash's "process substitution" to take the results of the jq command, treat it like a file, and source it into the current shell. The variables will then be available to use.
Here's an example of Extract a JSON value from a BASH script
#!/bin/bash
function jsonval {
temp=`echo $json | sed 's/\\\\\//\//g' | sed 's/[{}]//g' | awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}' | sed 's/\"\:\"/\|/g' | sed 's/[\,]/ /g' | sed 's/\"//g' | grep -w $prop`
echo ${temp##*|}
}
json=`curl -s -X GET http://twitter.com/users/show/$1.json`
prop='profile_image_url'
picurl=`jsonval`
`curl -s -X GET $picurl -o $1.png`
A bash script which demonstrates parsing a JSON string to extract a
property value. The script contains a jsonval function which operates
on two variables, json and prop. When the script is passed the name of
a twitter user it attempts to download the user's profile picture.
You could use perl module on command line:
1st, ensure they is installed, under debian based, you could
sudo apt-get install libjson-xs-perl
But for other OS, you could install perl modules via CPAN (the Comprehensive Perl Archive Network):
cpan App::cpanminus
cpan JSON::XS
Note: You may have to run this with superuser privileges.
then:
curlopts=(-X POST -H
"Content: apent-type: application/x-www-form-urlencoded"
-d username="$USERNAME" -d password="$PASSWORD")
curlurl=https://www.toontownrewritten.com/api/login?format=json
. <(
perl -MJSON::XS -e '
$/=undef;my $a=JSON::XS::decode_json <> ;
printf "declare -A Json=\047(%s)\047\n", join " ",map {
"[".$_."]=\"".$a->{$_}."\""
} qw|queueToken success eta position|;
' < <(
curl "${curlopts[#]}" $curlurl
)
)
The line qw|...| let you precise which variables you want to be driven... This could be replaced by keys $a, but could have to be debugged as some characters is forbiden is associative arrays values names.
echo ${Json[queueToken]}
6bee9e85-343f-41c7-a4d3-156f901da615
echo ${Json[eta]}
0
I am facing problems in sending html mail with attachemnt.I will able to send mail with
attachment (plain text ) using mailx -s and uuencode command and also html mail
without attachment using sendmail option.
However I am not able to send html mail along with attachment.
Either one of it is working (html mail or attachment)
Below are the different ways I have tried. Could you please help me in resolving the same.
1) Failed because of illegal option base64
#!/usr/bin/ksh
export MAILTO="abc#abc.com"
export SUBJECT="Mail Subject"
export BODY="card_summary_mail.html"
export ATTACH="query5_result.csv"
(
echo "To: $MAILTO"
echo "Subject: $SUBJECT"
echo "MIME-Version: 1.0"
echo 'Content-Type: multipart/mixed; boundary="-q1w2e3r4t5"'
echo
echo '---q1w2e3r4t5'
echo "Content-Type: text/html"
echo "Content-Disposition: inline"
cat $BODY
echo '---q1w2e3r4t5'
echo 'Content-Type: application; name="'$(basename $ATTACH)'"'
echo "Content-Transfer-Encoding: base64"
echo 'Content-Disposition: attachment; filename="'$(basename $ATTACH)'"'
uuencode --base64 $ATTACH $(basename $ATTACH)
echo '---q1w2e3r4t5--'
) | /usr/lib/sendmail $MAILTO
2)
cib-sokay2{u384283}323:cat test_html2.sh
{
uuencode query5_result.csv query5_result.csv > attachment.txt
cat mail.html attachment.txt > attachment2.html
} | /usr/lib/sendmail -t abc#abc.com
-----------------------------------------------
3)
cib-sokay2{u384283}324:cat test_html3.sh
export MAILTO="abc#abc.com"
export CONTENT="mail.html"
export CONTENT_F="attachment.txt"
export SUBJECT="TEST EMAIL: TESTING HTML"
BOUNDARY='=== This is the boundary between parts of the message. ==='
{
print - "From: Someone <$MAILFROM>"
print - "To: Someone <${MAILTO}>"
print - 'Subject:' $SUBJECT
print - 'MIME-Version: 1.0'
print - 'Content-Type: MULTIPART/MIXED; '
print - ' BOUNDARY='\"$BOUNDARY\"
print -
print - ' This message is in MIME format. But if you can see this,'
print - " you aren't using a MIME aware mail program. You shouldn't "
print - ' have too many problems because this message is entirely in'
print - ' ASCII and is designed to be somewhat readable with old '
print - ' mail software.'
print -
print - "--${BOUNDARY}"
print - 'Content-Type: TEXT/PLAIN; charset=US-ASCII'
print -
cat $CONTENT
print -
print -
print - "--${BOUNDARY}"
print - 'Content-Type: TEXT/PLAIN; charset=US-ASCII; name='${CONTENT}
print - 'Content-Disposition: attachment; filename='${CONTENT_F}
print -
cat ${CONTENT}
print -
print - "--${BOUNDARY}--"
} | /usr/lib/sendmail ${MAILTO}
------------------------------------------------------------
cib-sokay2{u384283}326:cat test_html4.sh
#!/usr/bin/ksh
export MAILTO="abc#abc.com"
export CONTENT="mail.html"
export SUBJECT="subject of email"
(
echo "Subject: $SUBJECT"
# This appears in the mail body
cat $CONTENT
# The next line creates the attachment with a suitable extension to read
# with Windows notepad
unix2dos "attachment.txt" | uuencode myattach.txt
echo "."
) | /usr/lib/sendmail $MAILTO
-------------------------------------
Your first attempt is fairly close. Your second attempt seems to write something to a file which is then abandoned, and you feed empty input to sendmail. Your third attempt has a grave error in the MIME boundary and some peculiarities (why do you put the same content twice?), but is basically fairly similar to the first. Your fourth attempt looks fairly reasonable but old-fashioned, but could have failed because of false assumptions about how things need to be formatted (for example, if $CONTENT does not start with an empty line, your contents would go smack dab in the message headers, creating illegal headers and probably being rejected).
Assuming you have a command base64 on your system (it is included in GNU Coreutils since 6.0, almost ten years back), just replace the uuencode call with that, and fix the various minor formatting errors. Here is a refactored script which hopefully catches most of them.
#!/bin/sh
# No need to export anything, we are not passing these to child processes
MAILTO="abc#abc.com"
SUBJECT="Mail Subject"
BODY="card_summary_mail.html"
ATTACH="query5_result.csv"
( cat <<____HERE
To: $MAILTO
Subject: $SUBJECT
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="-q1w2e3r4t5"
... You could put a MIME preamble here but nobody ever reads it ...
---q1w2e3r4t5
Content-Type: text/html
Content-Disposition: inline
X-Notice: you need an empty line before the body here:
____HERE
cat "$BODY"
# also notice empty line at beginning of next snippet
cat <<____THERE
---q1w2e3r4t5
X-Notice: just "application" is incompletely specified
Content-Type: application/octet-stream; name="$(basename "$ATTACH")"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="$(basename "$ATTACH")"
X-Notice: another empty line
____THERE
base64 "$ATTACH"
echo '---q1w2e3r4t5--'
) | /usr/lib/sendmail "$MAILTO"
However, assembling your own MIME structure gets tired really fast -- I would recommend looking for a command-line MUA with proper attachment support (mutt is popular; some modern mail/mailx clones have similar facilities, but it's not standard).
Also, there is nothing ksh-specific here, so I changed the shebang.
Your first attempt is almost correct. Just replace --base64 by -m as shown below:
#!/usr/bin/ksh
export MAILTO="abc#abc.com"
export SUBJECT="Mail Subject"
export BODY="card_summary_mail.html"
export ATTACH="query5_result.csv"
(
echo "To: $MAILTO"
echo "Subject: $SUBJECT"
echo "MIME-Version: 1.0"
echo 'Content-Type: multipart/mixed; boundary="-q1w2e3r4t5"'
echo
echo '---q1w2e3r4t5'
echo "Content-Type: text/html"
echo "Content-Disposition: inline"
cat "$BODY"
echo '---q1w2e3r4t5'
echo 'Content-Type: application; name="'$(basename "$ATTACH")'"'
echo "Content-Transfer-Encoding: base64"
echo 'Content-Disposition: attachment; filename="'$(basename "$ATTACH")'"'
uuencode -m "$ATTACH" "$(basename "$ATTACH")"
echo '---q1w2e3r4t5--'
) | /usr/lib/sendmail $MAILTO
i need to use a ksh language, for create a script to forward an e-mail, with html content in the body, could you help me with a tutorial, or a example easy script?
Thanks in advance.
http://unixnair.blogspot.com.au/2011/09/how-to-send-email-with-html-formatting.html
#!/usr/bin/ksh
# Script to send html email
# Written by Madhu
FROM="madhu#tarikida.com"
TO="madhu#tarikida.com"
SUBJECT="This email has html contents"
CONTENTS="/home/madhu/scripts/mail_text.html"
HEADER="From: ${FROM} \
\nTo: ${TO} \
\nSubject: \"$SUBJECT\" \
\nContent-Type: text/html; charset=us-ascii \
\nContent-Transfer-Encoding: 7bit \
\nMIME-Version: 1.0"
#echo $HEADER;
( echo $HEADER; cat $CONTENTS ) | /usr/sbin/sendmail -t