-
-
Notifications
You must be signed in to change notification settings - Fork 740
/
send_mail
executable file
·142 lines (106 loc) · 2.25 KB
/
send_mail
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#!/bin/bash
HOSTNAME=$(hostname -f)
LINE_BREAK=""
FOOTER="This message was generated by StackStorm action `basename $0` running on `hostname`"
# Allow user to provide a custom sendmail binary for more flexibility and easier
# testing
SENDMAIL_BINARY=$1
if [ "${SENDMAIL_BINARY}" = "None" ]; then
# If path to the sendmail binary is not provided, try to find one in $PATH
SENDMAIL=`which sendmail`
if [ $? -ne 0 ]; then
echo "Unable to find sendmail binary in PATH" >&2
exit 2
fi
MAIL="$SENDMAIL -t"
else
MAIL="${SENDMAIL_BINARY}"
fi
shift
if [[ $1 =~ '@' ]]; then
FROM=$1
else
FROM="$1@${HOSTNAME}"
fi
shift
TO=$1
shift
SUBJECT=$1
shift
SEND_EMPTY_BODY=$1
shift
CONTENT_TYPE=$1
shift
BODY="$1"
shift
IFS=',' read -ra ATTACHMENTS <<< "$@"
if [[ -z $ATTACHMENTS ]]; then
ATTACHMENTS=""
fi
if [[ "${CONTENT_TYPE}" = "text/html" ]]; then
LINE_BREAK="<br><br>"
else
LINE_BREAK=""
fi
get_mimetype(){
# warning: assumes that the passed file exists
file --mime-type "$1" | sed 's/.*: //'
}
trimmed="${BODY// }"
if [[ -z $trimmed && $SEND_EMPTY_BODY -eq 1 ]] || [[ -n $trimmed ]]; then
{
cat <<EOF
TO: ${TO}
FROM: ${FROM}
SUBJECT: =?UTF-8?B?$(echo ${SUBJECT} | base64 -w 0)?=
EOF
if [[ -n $ATTACHMENTS ]]; then
boundary="ZZ_/afg6432dfgkl.94531q"
cat <<EOF
Content-Type: multipart/mixed; boundary="${boundary}"
EOF
for file in "${ATTACHMENTS[@]}"; do
[ ! -f "$file" ] && echo "Warning: attachment ${file} not found, skipping" >&2 && continue
mimetype=$(get_mimetype "$file")
cat <<EOF
--${boundary}
Content-Type: ${mimetype}
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="$(basename $file)"
EOF
base64 "$file"
echo
done
cat <<EOF
--${boundary}
Content-Type: ${CONTENT_TYPE}; charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-Disposition: inline
EOF
else
cat <<EOF
Content-Type: ${CONTENT_TYPE}; charset=UTF-8
EOF
fi
cat <<EOF
${BODY}
${LINE_BREAK}
${FOOTER}
EOF
if [[ -n $ATTACHMENTS ]]; then
cat <<EOF
--${boundary}--
EOF
fi
} | ${MAIL}
fi
if [ $? -ne 0 ]; then
echo "Failed to send mail to ${TO}"
exit 2
elif [[ -z $trimmed && $SEND_EMPTY_BODY -eq 0 ]]; then
echo "Nothing to send"
exit 0
else
echo "Successfully sent mail to ${TO}"
exit 0
fi