You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

331 lines
10 KiB

  1. #!/usr/bin/env sh
  2. # support smtp
  3. # Please report bugs to https://github.com/acmesh-official/acme.sh/issues/3358
  4. # This implementation uses either curl or Python (3 or 2.7).
  5. # (See also the "mail" notify hook, which supports other ways to send mail.)
  6. # SMTP_FROM="from@example.com" # required
  7. # SMTP_TO="to@example.com" # required
  8. # SMTP_HOST="smtp.example.com" # required
  9. # SMTP_PORT="25" # defaults to 25, 465 or 587 depending on SMTP_SECURE
  10. # SMTP_SECURE="none" # one of "none", "ssl" (implicit TLS, TLS Wrapper), "tls" (explicit TLS, STARTTLS)
  11. # SMTP_USERNAME="" # set if SMTP server requires login
  12. # SMTP_PASSWORD="" # set if SMTP server requires login
  13. # SMTP_TIMEOUT="30" # seconds for SMTP operations to timeout
  14. # SMTP_BIN="/path/to/curl_or_python" # default finds first of curl, python3, or python on PATH
  15. # subject content statuscode
  16. smtp_send() {
  17. _SMTP_SUBJECT="$1"
  18. _SMTP_CONTENT="$2"
  19. # UNUSED: _statusCode="$3" # 0: success, 1: error 2($RENEW_SKIP): skipped
  20. # Load config:
  21. SMTP_FROM="${SMTP_FROM:-$(_readaccountconf_mutable SMTP_FROM)}"
  22. SMTP_TO="${SMTP_TO:-$(_readaccountconf_mutable SMTP_TO)}"
  23. SMTP_HOST="${SMTP_HOST:-$(_readaccountconf_mutable SMTP_HOST)}"
  24. SMTP_PORT="${SMTP_PORT:-$(_readaccountconf_mutable SMTP_PORT)}"
  25. SMTP_SECURE="${SMTP_SECURE:-$(_readaccountconf_mutable SMTP_SECURE)}"
  26. SMTP_USERNAME="${SMTP_USERNAME:-$(_readaccountconf_mutable SMTP_USERNAME)}"
  27. SMTP_PASSWORD="${SMTP_PASSWORD:-$(_readaccountconf_mutable SMTP_PASSWORD)}"
  28. SMTP_TIMEOUT="${SMTP_TIMEOUT:-$(_readaccountconf_mutable SMTP_TIMEOUT)}"
  29. SMTP_BIN="${SMTP_BIN:-$(_readaccountconf_mutable SMTP_BIN)}"
  30. _debug "SMTP_FROM" "$SMTP_FROM"
  31. _debug "SMTP_TO" "$SMTP_TO"
  32. _debug "SMTP_HOST" "$SMTP_HOST"
  33. _debug "SMTP_PORT" "$SMTP_PORT"
  34. _debug "SMTP_SECURE" "$SMTP_SECURE"
  35. _debug "SMTP_USERNAME" "$SMTP_USERNAME"
  36. _secure_debug "SMTP_PASSWORD" "$SMTP_PASSWORD"
  37. _debug "SMTP_TIMEOUT" "$SMTP_TIMEOUT"
  38. _debug "SMTP_BIN" "$SMTP_BIN"
  39. _debug "_SMTP_SUBJECT" "$_SMTP_SUBJECT"
  40. _debug "_SMTP_CONTENT" "$_SMTP_CONTENT"
  41. # Validate config and apply defaults:
  42. # _SMTP_* variables are the resolved (with defaults) versions of SMTP_*.
  43. # (The _SMTP_* versions will not be stored in account conf.)
  44. if [ -n "$SMTP_BIN" ] && ! _exists "$SMTP_BIN"; then
  45. _err "SMTP_BIN '$SMTP_BIN' does not exist."
  46. return 1
  47. fi
  48. _SMTP_BIN="$SMTP_BIN"
  49. if [ -z "$_SMTP_BIN" ]; then
  50. # Look for a command that can communicate with an SMTP server.
  51. # (Please don't add sendmail, ssmtp, mutt, mail, or msmtp here.
  52. # Those are already handled by the "mail" notify hook.)
  53. for cmd in curl python3 python2.7 python pypy3 pypy; do
  54. if _exists "$cmd"; then
  55. _SMTP_BIN="$cmd"
  56. break
  57. fi
  58. done
  59. if [ -z "$_SMTP_BIN" ]; then
  60. _err "The smtp notify-hook requires curl or Python, but can't find any."
  61. _err 'If you have one of them, define SMTP_BIN="/path/to/curl_or_python".'
  62. _err 'Otherwise, see if you can use the "mail" notify-hook instead.'
  63. return 1
  64. fi
  65. _debug "_SMTP_BIN" "$_SMTP_BIN"
  66. fi
  67. if [ -z "$SMTP_FROM" ]; then
  68. _err "You must define SMTP_FROM as the sender email address."
  69. return 1
  70. fi
  71. _SMTP_FROM="$SMTP_FROM"
  72. if [ -z "$SMTP_TO" ]; then
  73. _err "You must define SMTP_TO as the recipient email address."
  74. return 1
  75. fi
  76. _SMTP_TO="$SMTP_TO"
  77. if [ -z "$SMTP_HOST" ]; then
  78. _err "You must define SMTP_HOST as the SMTP server hostname."
  79. return 1
  80. fi
  81. _SMTP_HOST="$SMTP_HOST"
  82. _SMTP_SECURE="${SMTP_SECURE:-none}"
  83. case "$_SMTP_SECURE" in
  84. "none") smtp_default_port="25" ;;
  85. "ssl") smtp_default_port="465" ;;
  86. "tls") smtp_default_port="587" ;;
  87. *)
  88. _err "Invalid SMTP_SECURE='$SMTP_SECURE'. It must be 'ssl', 'tls' or 'none'."
  89. return 1
  90. ;;
  91. esac
  92. _SMTP_PORT="${SMTP_PORT:-$smtp_default_port}"
  93. if [ -z "$SMTP_PORT" ]; then
  94. _debug "_SMTP_PORT" "$_SMTP_PORT"
  95. fi
  96. _SMTP_USERNAME="$SMTP_USERNAME"
  97. _SMTP_PASSWORD="$SMTP_PASSWORD"
  98. _SMTP_TIMEOUT="${SMTP_TIMEOUT:-30}"
  99. # Run with --debug 2 (or above) to echo the transcript of the SMTP session.
  100. # Careful: this may include SMTP_PASSWORD in plaintext!
  101. if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_2" ]; then
  102. _SMTP_SHOW_TRANSCRIPT="True"
  103. else
  104. _SMTP_SHOW_TRANSCRIPT=""
  105. fi
  106. # Send the message:
  107. case "$(basename "$_SMTP_BIN")" in
  108. curl) _smtp_send=_smtp_send_curl ;;
  109. py*) _smtp_send=_smtp_send_python ;;
  110. *)
  111. _err "Can't figure out how to invoke $_SMTP_BIN."
  112. _err "Check your SMTP_BIN setting."
  113. return 1
  114. ;;
  115. esac
  116. if ! smtp_output="$($_smtp_send)"; then
  117. _err "Error sending message with $_SMTP_BIN."
  118. if [ -n "$smtp_output" ]; then
  119. _err "$smtp_output"
  120. fi
  121. return 1
  122. fi
  123. # Save config only if send was successful:
  124. _saveaccountconf_mutable SMTP_BIN "$SMTP_BIN"
  125. _saveaccountconf_mutable SMTP_FROM "$SMTP_FROM"
  126. _saveaccountconf_mutable SMTP_TO "$SMTP_TO"
  127. _saveaccountconf_mutable SMTP_HOST "$SMTP_HOST"
  128. _saveaccountconf_mutable SMTP_PORT "$SMTP_PORT"
  129. _saveaccountconf_mutable SMTP_SECURE "$SMTP_SECURE"
  130. _saveaccountconf_mutable SMTP_USERNAME "$SMTP_USERNAME"
  131. _saveaccountconf_mutable SMTP_PASSWORD "$SMTP_PASSWORD"
  132. _saveaccountconf_mutable SMTP_TIMEOUT "$SMTP_TIMEOUT"
  133. return 0
  134. }
  135. # Send the message via curl using _SMTP_* variables
  136. _smtp_send_curl() {
  137. # curl passes --mail-from and --mail-rcpt directly to the SMTP protocol without
  138. # additional parsing, and SMTP requires addr-spec only (no display names).
  139. # In the future, maybe try to parse the addr-spec out for curl args (non-trivial).
  140. if _email_has_display_name "$_SMTP_FROM"; then
  141. _err "curl smtp only allows a simple email address in SMTP_FROM."
  142. _err "Change your SMTP_FROM='$SMTP_FROM' to remove the display name."
  143. return 1
  144. fi
  145. if _email_has_display_name "$_SMTP_TO"; then
  146. _err "curl smtp only allows simple email addresses in SMTP_TO."
  147. _err "Change your SMTP_TO='$SMTP_TO' to remove the display name(s)."
  148. return 1
  149. fi
  150. # Build curl args in $@
  151. case "$_SMTP_SECURE" in
  152. none)
  153. set -- --url "smtp://${_SMTP_HOST}:${_SMTP_PORT}"
  154. ;;
  155. ssl)
  156. set -- --url "smtps://${_SMTP_HOST}:${_SMTP_PORT}"
  157. ;;
  158. tls)
  159. set -- --url "smtp://${_SMTP_HOST}:${_SMTP_PORT}" --ssl-reqd
  160. ;;
  161. *)
  162. # This will only occur if someone adds a new SMTP_SECURE option above
  163. # without updating this code for it.
  164. _err "Unhandled _SMTP_SECURE='$_SMTP_SECURE' in _smtp_send_curl"
  165. _err "Please re-run with --debug and report a bug."
  166. return 1
  167. ;;
  168. esac
  169. set -- "$@" \
  170. --upload-file - \
  171. --mail-from "$_SMTP_FROM" \
  172. --max-time "$_SMTP_TIMEOUT"
  173. # Burst comma-separated $_SMTP_TO into individual --mail-rcpt args.
  174. _to="${_SMTP_TO},"
  175. while [ -n "$_to" ]; do
  176. _rcpt="${_to%%,*}"
  177. _to="${_to#*,}"
  178. set -- "$@" --mail-rcpt "$_rcpt"
  179. done
  180. _smtp_login="${_SMTP_USERNAME}:${_SMTP_PASSWORD}"
  181. if [ "$_smtp_login" != ":" ]; then
  182. set -- "$@" --user "$_smtp_login"
  183. fi
  184. if [ "$_SMTP_SHOW_TRANSCRIPT" = "True" ]; then
  185. set -- "$@" --verbose
  186. else
  187. set -- "$@" --silent --show-error
  188. fi
  189. raw_message="$(_smtp_raw_message)"
  190. _debug2 "curl command:" "$_SMTP_BIN" "$*"
  191. _debug2 "raw_message:\n$raw_message"
  192. echo "$raw_message" | "$_SMTP_BIN" "$@"
  193. }
  194. # Output an RFC-822 / RFC-5322 email message using _SMTP_* variables
  195. _smtp_raw_message() {
  196. echo "From: $_SMTP_FROM"
  197. echo "To: $_SMTP_TO"
  198. echo "Subject: $(_mime_encoded_word "$_SMTP_SUBJECT")"
  199. if _exists date; then
  200. echo "Date: $(date +'%a, %-d %b %Y %H:%M:%S %z')"
  201. fi
  202. echo "Content-Type: text/plain; charset=utf-8"
  203. echo "X-Mailer: acme.sh --notify-hook smtp"
  204. echo
  205. echo "$_SMTP_CONTENT"
  206. }
  207. # Convert text to RFC-2047 MIME "encoded word" format if it contains non-ASCII chars
  208. # text
  209. _mime_encoded_word() {
  210. _text="$1"
  211. # (regex character ranges like [a-z] can be locale-dependent; enumerate ASCII chars to avoid that)
  212. _ascii='] $`"'"[!#%&'()*+,./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ~^_abcdefghijklmnopqrstuvwxyz{|}~-"
  213. if expr "$_text" : "^.*[^$_ascii]" >/dev/null; then
  214. # At least one non-ASCII char; convert entire thing to encoded word
  215. printf "%s" "=?UTF-8?B?$(printf "%s" "$_text" | _base64)?="
  216. else
  217. # Just printable ASCII, no conversion needed
  218. printf "%s" "$_text"
  219. fi
  220. }
  221. # Simple check for display name in an email address (< > or ")
  222. # email
  223. _email_has_display_name() {
  224. _email="$1"
  225. expr "$_email" : '^.*[<>"]' >/dev/null
  226. }
  227. # Send the message via Python using _SMTP_* variables
  228. _smtp_send_python() {
  229. _debug "Python version" "$("$_SMTP_BIN" --version 2>&1)"
  230. # language=Python
  231. "$_SMTP_BIN" <<EOF
  232. # This code is meant to work with either Python 2.7.x or Python 3.4+.
  233. try:
  234. try:
  235. from email.message import EmailMessage
  236. except ImportError:
  237. from email.mime.text import MIMEText as EmailMessage # Python 2
  238. from smtplib import SMTP, SMTP_SSL, SMTPException
  239. from socket import error as SocketError
  240. except ImportError as err:
  241. print("A required Python standard package is missing. This system may have"
  242. " a reduced version of Python unsuitable for sending mail: %s" % err)
  243. exit(1)
  244. show_transcript = """$_SMTP_SHOW_TRANSCRIPT""" == "True"
  245. smtp_host = """$_SMTP_HOST"""
  246. smtp_port = int("""$_SMTP_PORT""")
  247. smtp_secure = """$_SMTP_SECURE"""
  248. username = """$_SMTP_USERNAME"""
  249. password = """$_SMTP_PASSWORD"""
  250. timeout=int("""$_SMTP_TIMEOUT""") # seconds
  251. from_email="""$_SMTP_FROM"""
  252. to_emails="""$_SMTP_TO""" # can be comma-separated
  253. subject="""$_SMTP_SUBJECT"""
  254. content="""$_SMTP_CONTENT"""
  255. try:
  256. msg = EmailMessage()
  257. msg.set_content(content)
  258. except (AttributeError, TypeError):
  259. # Python 2 MIMEText
  260. msg = EmailMessage(content)
  261. msg["Subject"] = subject
  262. msg["From"] = from_email
  263. msg["To"] = to_emails
  264. smtp = None
  265. try:
  266. if smtp_secure == "ssl":
  267. smtp = SMTP_SSL(smtp_host, smtp_port, timeout=timeout)
  268. else:
  269. smtp = SMTP(smtp_host, smtp_port, timeout=timeout)
  270. smtp.set_debuglevel(show_transcript)
  271. if smtp_secure == "tls":
  272. smtp.starttls()
  273. if username or password:
  274. smtp.login(username, password)
  275. smtp.sendmail(msg["From"], msg["To"].split(","), msg.as_string())
  276. except SMTPException as err:
  277. # Output just the error (skip the Python stack trace) for SMTP errors
  278. print("Error sending: %r" % err)
  279. exit(1)
  280. except SocketError as err:
  281. print("Error connecting to %s:%d: %r" % (smtp_host, smtp_port, err))
  282. exit(1)
  283. finally:
  284. if smtp is not None:
  285. smtp.quit()
  286. EOF
  287. }