]> git.proxmox.com Git - mirror_acme.sh.git/blob - notify/smtp.sh
Merge pull request #4820 from acmesh-official/dev
[mirror_acme.sh.git] / notify / smtp.sh
1 #!/usr/bin/env sh
2
3 # support smtp
4
5 # Please report bugs to https://github.com/acmesh-official/acme.sh/issues/3358
6
7 # This implementation uses either curl or Python (3 or 2.7).
8 # (See also the "mail" notify hook, which supports other ways to send mail.)
9
10 # SMTP_FROM="from@example.com" # required
11 # SMTP_TO="to@example.com" # required
12 # SMTP_HOST="smtp.example.com" # required
13 # SMTP_PORT="25" # defaults to 25, 465 or 587 depending on SMTP_SECURE
14 # SMTP_SECURE="tls" # one of "none", "ssl" (implicit TLS, TLS Wrapper), "tls" (explicit TLS, STARTTLS)
15 # SMTP_USERNAME="" # set if SMTP server requires login
16 # SMTP_PASSWORD="" # set if SMTP server requires login
17 # SMTP_TIMEOUT="30" # seconds for SMTP operations to timeout
18 # SMTP_BIN="/path/to/python_or_curl" # default finds first of python3, python2.7, python, pypy3, pypy, curl on PATH
19
20 SMTP_SECURE_DEFAULT="tls"
21 SMTP_TIMEOUT_DEFAULT="30"
22
23 # subject content statuscode
24 smtp_send() {
25 SMTP_SUBJECT="$1"
26 SMTP_CONTENT="$2"
27 # UNUSED: _statusCode="$3" # 0: success, 1: error 2($RENEW_SKIP): skipped
28
29 # Load and validate config:
30 SMTP_BIN="$(_readaccountconf_mutable_default SMTP_BIN)"
31 if [ -n "$SMTP_BIN" ] && ! _exists "$SMTP_BIN"; then
32 _err "SMTP_BIN '$SMTP_BIN' does not exist."
33 return 1
34 fi
35 if [ -z "$SMTP_BIN" ]; then
36 # Look for a command that can communicate with an SMTP server.
37 # (Please don't add sendmail, ssmtp, mutt, mail, or msmtp here.
38 # Those are already handled by the "mail" notify hook.)
39 for cmd in python3 python2.7 python pypy3 pypy curl; do
40 if _exists "$cmd"; then
41 SMTP_BIN="$cmd"
42 break
43 fi
44 done
45 if [ -z "$SMTP_BIN" ]; then
46 _err "The smtp notify-hook requires curl or Python, but can't find any."
47 _err 'If you have one of them, define SMTP_BIN="/path/to/curl_or_python".'
48 _err 'Otherwise, see if you can use the "mail" notify-hook instead.'
49 return 1
50 fi
51 fi
52 _debug SMTP_BIN "$SMTP_BIN"
53 _saveaccountconf_mutable_default SMTP_BIN "$SMTP_BIN"
54
55 SMTP_FROM="$(_readaccountconf_mutable_default SMTP_FROM)"
56 SMTP_FROM="$(_clean_email_header "$SMTP_FROM")"
57 if [ -z "$SMTP_FROM" ]; then
58 _err "You must define SMTP_FROM as the sender email address."
59 return 1
60 fi
61 if _email_has_display_name "$SMTP_FROM"; then
62 _err "SMTP_FROM must be only a simple email address (sender@example.com)."
63 _err "Change your SMTP_FROM='$SMTP_FROM' to remove the display name."
64 return 1
65 fi
66 _debug SMTP_FROM "$SMTP_FROM"
67 _saveaccountconf_mutable_default SMTP_FROM "$SMTP_FROM"
68
69 SMTP_TO="$(_readaccountconf_mutable_default SMTP_TO)"
70 SMTP_TO="$(_clean_email_header "$SMTP_TO")"
71 if [ -z "$SMTP_TO" ]; then
72 _err "You must define SMTP_TO as the recipient email address(es)."
73 return 1
74 fi
75 if _email_has_display_name "$SMTP_TO"; then
76 _err "SMTP_TO must be only simple email addresses (to@example.com,to2@example.com)."
77 _err "Change your SMTP_TO='$SMTP_TO' to remove the display name(s)."
78 return 1
79 fi
80 _debug SMTP_TO "$SMTP_TO"
81 _saveaccountconf_mutable_default SMTP_TO "$SMTP_TO"
82
83 SMTP_HOST="$(_readaccountconf_mutable_default SMTP_HOST)"
84 if [ -z "$SMTP_HOST" ]; then
85 _err "You must define SMTP_HOST as the SMTP server hostname."
86 return 1
87 fi
88 _debug SMTP_HOST "$SMTP_HOST"
89 _saveaccountconf_mutable_default SMTP_HOST "$SMTP_HOST"
90
91 SMTP_SECURE="$(_readaccountconf_mutable_default SMTP_SECURE "$SMTP_SECURE_DEFAULT")"
92 case "$SMTP_SECURE" in
93 "none") smtp_port_default="25" ;;
94 "ssl") smtp_port_default="465" ;;
95 "tls") smtp_port_default="587" ;;
96 *)
97 _err "Invalid SMTP_SECURE='$SMTP_SECURE'. It must be 'ssl', 'tls' or 'none'."
98 return 1
99 ;;
100 esac
101 _debug SMTP_SECURE "$SMTP_SECURE"
102 _saveaccountconf_mutable_default SMTP_SECURE "$SMTP_SECURE" "$SMTP_SECURE_DEFAULT"
103
104 SMTP_PORT="$(_readaccountconf_mutable_default SMTP_PORT "$smtp_port_default")"
105 case "$SMTP_PORT" in
106 *[!0-9]*)
107 _err "Invalid SMTP_PORT='$SMTP_PORT'. It must be a port number."
108 return 1
109 ;;
110 esac
111 _debug SMTP_PORT "$SMTP_PORT"
112 _saveaccountconf_mutable_default SMTP_PORT "$SMTP_PORT" "$smtp_port_default"
113
114 SMTP_USERNAME="$(_readaccountconf_mutable_default SMTP_USERNAME)"
115 _debug SMTP_USERNAME "$SMTP_USERNAME"
116 _saveaccountconf_mutable_default SMTP_USERNAME "$SMTP_USERNAME"
117
118 SMTP_PASSWORD="$(_readaccountconf_mutable_default SMTP_PASSWORD)"
119 _secure_debug SMTP_PASSWORD "$SMTP_PASSWORD"
120 _saveaccountconf_mutable_default SMTP_PASSWORD "$SMTP_PASSWORD"
121
122 SMTP_TIMEOUT="$(_readaccountconf_mutable_default SMTP_TIMEOUT "$SMTP_TIMEOUT_DEFAULT")"
123 _debug SMTP_TIMEOUT "$SMTP_TIMEOUT"
124 _saveaccountconf_mutable_default SMTP_TIMEOUT "$SMTP_TIMEOUT" "$SMTP_TIMEOUT_DEFAULT"
125
126 SMTP_X_MAILER="$(_clean_email_header "$PROJECT_NAME $VER --notify-hook smtp")"
127
128 # Run with --debug 2 (or above) to echo the transcript of the SMTP session.
129 # Careful: this may include SMTP_PASSWORD in plaintext!
130 if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_2" ]; then
131 SMTP_SHOW_TRANSCRIPT="True"
132 else
133 SMTP_SHOW_TRANSCRIPT=""
134 fi
135
136 SMTP_SUBJECT=$(_clean_email_header "$SMTP_SUBJECT")
137 _debug SMTP_SUBJECT "$SMTP_SUBJECT"
138 _debug SMTP_CONTENT "$SMTP_CONTENT"
139
140 # Send the message:
141 case "$(basename "$SMTP_BIN")" in
142 curl) _smtp_send=_smtp_send_curl ;;
143 py*) _smtp_send=_smtp_send_python ;;
144 *)
145 _err "Can't figure out how to invoke '$SMTP_BIN'."
146 _err "Check your SMTP_BIN setting."
147 return 1
148 ;;
149 esac
150
151 if ! smtp_output="$($_smtp_send)"; then
152 _err "Error sending message with $SMTP_BIN."
153 if [ -n "$smtp_output" ]; then
154 _err "$smtp_output"
155 fi
156 return 1
157 fi
158
159 return 0
160 }
161
162 # Strip CR and NL from text to prevent MIME header injection
163 # text
164 _clean_email_header() {
165 printf "%s" "$(echo "$1" | tr -d "\r\n")"
166 }
167
168 # Simple check for display name in an email address (< > or ")
169 # email
170 _email_has_display_name() {
171 _email="$1"
172 echo "$_email" | grep -q -E '^.*[<>"]'
173 }
174
175 ##
176 ## curl smtp sending
177 ##
178
179 # Send the message via curl using SMTP_* variables
180 _smtp_send_curl() {
181 # Build curl args in $@
182 case "$SMTP_SECURE" in
183 none)
184 set -- --url "smtp://${SMTP_HOST}:${SMTP_PORT}"
185 ;;
186 ssl)
187 set -- --url "smtps://${SMTP_HOST}:${SMTP_PORT}"
188 ;;
189 tls)
190 set -- --url "smtp://${SMTP_HOST}:${SMTP_PORT}" --ssl-reqd
191 ;;
192 *)
193 # This will only occur if someone adds a new SMTP_SECURE option above
194 # without updating this code for it.
195 _err "Unhandled SMTP_SECURE='$SMTP_SECURE' in _smtp_send_curl"
196 _err "Please re-run with --debug and report a bug."
197 return 1
198 ;;
199 esac
200
201 set -- "$@" \
202 --upload-file - \
203 --mail-from "$SMTP_FROM" \
204 --max-time "$SMTP_TIMEOUT"
205
206 # Burst comma-separated $SMTP_TO into individual --mail-rcpt args.
207 _to="${SMTP_TO},"
208 while [ -n "$_to" ]; do
209 _rcpt="${_to%%,*}"
210 _to="${_to#*,}"
211 set -- "$@" --mail-rcpt "$_rcpt"
212 done
213
214 _smtp_login="${SMTP_USERNAME}:${SMTP_PASSWORD}"
215 if [ "$_smtp_login" != ":" ]; then
216 set -- "$@" --user "$_smtp_login"
217 fi
218
219 if [ "$SMTP_SHOW_TRANSCRIPT" = "True" ]; then
220 set -- "$@" --verbose
221 else
222 set -- "$@" --silent --show-error
223 fi
224
225 raw_message="$(_smtp_raw_message)"
226
227 _debug2 "curl command:" "$SMTP_BIN" "$*"
228 _debug2 "raw_message:\n$raw_message"
229
230 echo "$raw_message" | "$SMTP_BIN" "$@"
231 }
232
233 # Output an RFC-822 / RFC-5322 email message using SMTP_* variables.
234 # (This assumes variables have already been cleaned for use in email headers.)
235 _smtp_raw_message() {
236 echo "From: $SMTP_FROM"
237 echo "To: $SMTP_TO"
238 echo "Subject: $(_mime_encoded_word "$SMTP_SUBJECT")"
239 echo "Date: $(_rfc2822_date)"
240 echo "Content-Type: text/plain; charset=utf-8"
241 echo "X-Mailer: $SMTP_X_MAILER"
242 echo
243 echo "$SMTP_CONTENT"
244 }
245
246 # Convert text to RFC-2047 MIME "encoded word" format if it contains non-ASCII chars
247 # text
248 _mime_encoded_word() {
249 _text="$1"
250 # (regex character ranges like [a-z] can be locale-dependent; enumerate ASCII chars to avoid that)
251 _ascii='] $`"'"[!#%&'()*+,./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ~^_abcdefghijklmnopqrstuvwxyz{|}~-"
252 if echo "$_text" | grep -q -E "^.*[^$_ascii]"; then
253 # At least one non-ASCII char; convert entire thing to encoded word
254 printf "%s" "=?UTF-8?B?$(printf "%s" "$_text" | _base64)?="
255 else
256 # Just printable ASCII, no conversion needed
257 printf "%s" "$_text"
258 fi
259 }
260
261 # Output current date in RFC-2822 Section 3.3 format as required in email headers
262 # (e.g., "Mon, 15 Feb 2021 14:22:01 -0800")
263 _rfc2822_date() {
264 # Notes:
265 # - this is deliberately not UTC, because it "SHOULD express local time" per spec
266 # - the spec requires weekday and month in the C locale (English), not localized
267 # - this date format specifier has been tested on Linux, Mac, Solaris and FreeBSD
268 _old_lc_time="$LC_TIME"
269 LC_TIME=C
270 date +'%a, %-d %b %Y %H:%M:%S %z'
271 LC_TIME="$_old_lc_time"
272 }
273
274 ##
275 ## Python smtp sending
276 ##
277
278 # Send the message via Python using SMTP_* variables
279 _smtp_send_python() {
280 _debug "Python version" "$("$SMTP_BIN" --version 2>&1)"
281
282 # language=Python
283 "$SMTP_BIN" <<PYTHON
284 # This code is meant to work with either Python 2.7.x or Python 3.4+.
285 try:
286 try:
287 from email.message import EmailMessage
288 from email.policy import default as email_policy_default
289 except ImportError:
290 # Python 2 (or < 3.3)
291 from email.mime.text import MIMEText as EmailMessage
292 email_policy_default = None
293 from email.utils import formatdate as rfc2822_date
294 from smtplib import SMTP, SMTP_SSL, SMTPException
295 from socket import error as SocketError
296 except ImportError as err:
297 print("A required Python standard package is missing. This system may have"
298 " a reduced version of Python unsuitable for sending mail: %s" % err)
299 exit(1)
300
301 show_transcript = """$SMTP_SHOW_TRANSCRIPT""" == "True"
302
303 smtp_host = """$SMTP_HOST"""
304 smtp_port = int("""$SMTP_PORT""")
305 smtp_secure = """$SMTP_SECURE"""
306 username = """$SMTP_USERNAME"""
307 password = """$SMTP_PASSWORD"""
308 timeout=int("""$SMTP_TIMEOUT""") # seconds
309 x_mailer="""$SMTP_X_MAILER"""
310
311 from_email="""$SMTP_FROM"""
312 to_emails="""$SMTP_TO""" # can be comma-separated
313 subject="""$SMTP_SUBJECT"""
314 content="""$SMTP_CONTENT"""
315
316 try:
317 msg = EmailMessage(policy=email_policy_default)
318 msg.set_content(content)
319 except (AttributeError, TypeError):
320 # Python 2 MIMEText
321 msg = EmailMessage(content)
322 msg["Subject"] = subject
323 msg["From"] = from_email
324 msg["To"] = to_emails
325 msg["Date"] = rfc2822_date(localtime=True)
326 msg["X-Mailer"] = x_mailer
327
328 smtp = None
329 try:
330 if smtp_secure == "ssl":
331 smtp = SMTP_SSL(smtp_host, smtp_port, timeout=timeout)
332 else:
333 smtp = SMTP(smtp_host, smtp_port, timeout=timeout)
334 smtp.set_debuglevel(show_transcript)
335 if smtp_secure == "tls":
336 smtp.starttls()
337 if username or password:
338 smtp.login(username, password)
339 smtp.sendmail(msg["From"], msg["To"].split(","), msg.as_string())
340
341 except SMTPException as err:
342 # Output just the error (skip the Python stack trace) for SMTP errors
343 print("Error sending: %r" % err)
344 exit(1)
345
346 except SocketError as err:
347 print("Error connecting to %s:%d: %r" % (smtp_host, smtp_port, err))
348 exit(1)
349
350 finally:
351 if smtp is not None:
352 smtp.quit()
353 PYTHON
354 }
355
356 ##
357 ## Conf helpers
358 ##
359
360 #_readaccountconf_mutable_default name default_value
361 # Given a name like MY_CONF:
362 # - if MY_CONF is set and non-empty, output $MY_CONF
363 # - if MY_CONF is set _empty_, output $default_value
364 # (lets user `export MY_CONF=` to clear previous saved value
365 # and return to default, without user having to know default)
366 # - otherwise if _readaccountconf_mutable MY_CONF is non-empty, return that
367 # (value of SAVED_MY_CONF from account.conf)
368 # - otherwise output $default_value
369 _readaccountconf_mutable_default() {
370 _name="$1"
371 _default_value="$2"
372
373 eval "_value=\"\$$_name\""
374 eval "_name_is_set=\"\${${_name}+true}\""
375 # ($_name_is_set is "true" if $$_name is set to anything, including empty)
376 if [ -z "${_value}" ] && [ "${_name_is_set:-}" != "true" ]; then
377 _value="$(_readaccountconf_mutable "$_name")"
378 fi
379 if [ -z "${_value}" ]; then
380 _value="$_default_value"
381 fi
382 printf "%s" "$_value"
383 }
384
385 #_saveaccountconf_mutable_default name value default_value base64encode
386 # Like _saveaccountconf_mutable, but if value is default_value
387 # then _clearaccountconf_mutable instead
388 _saveaccountconf_mutable_default() {
389 _name="$1"
390 _value="$2"
391 _default_value="$3"
392 _base64encode="$4"
393
394 if [ "$_value" != "$_default_value" ]; then
395 _saveaccountconf_mutable "$_name" "$_value" "$_base64encode"
396 else
397 _clearaccountconf_mutable "$_name"
398 fi
399 }