hackerbase/src/util-mail.scm

78 lines
2 KiB
Scheme

;;
;; util-mail.scm
;;
;; Helper for sending emails.
;;
;; ISC License
;;
;; Copyright 2023 Brmlab, z.s.
;; Dominik Pantůček <dominik.pantucek@trustica.cz>
;;
;; Permission to use, copy, modify, and/or distribute this software
;; for any purpose with or without fee is hereby granted, provided
;; that the above copyright notice and this permission notice appear
;; in all copies.
;;
;; THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
;; WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
;; WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
;; AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
;; CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
;; OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
;; NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
;; CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
;;
(declare (unit util-mail))
(module
util-mail
(
*mailto-override*
send-mail
)
(import scheme
(chicken base)
(chicken keyword)
(chicken string)
util-io
util-utf8
util-string)
;; All emails go to this override
(define *mailto-override* (make-parameter #f))
;; Ensures the subject has proper encoding
(define (encode-subject subj)
(if (string-utf8? subj)
(string-append "=?UTF-8?Q?"
(string->qp subj)
"?=")
subj))
;; Sends an email using the UNIX mail(1) utility.
(define (send-mail body-lines . args)
(let ((from (get-keyword #:from args))
(to (get-keyword #:to args))
(subject (get-keyword #:subject args)))
(when (not to)
(error 'send-mail "requires #:to argument"))
(when (not subject)
(error 'send-mail "requires #:subject argument"))
(let* ((tos (if (list? to)
to
(list to)))
(real-tos (if (*mailto-override*)
(list (*mailto-override*))
tos)))
(apply process-send/recv
"mail"
(append (if from
(list "-r" from)
'())
(list "-s" (encode-subject subject))
real-tos)
body-lines))))
)