(t
'message)))))
+(defun message-all-recipients ()
+ "Return a list of all recipients in the message, looking at TO, CC and BCC.
+
+Each recipient is in the format of `mail-extract-address-components'."
+ (mapcan (lambda (header)
+ (let ((header-value (message-fetch-field header)))
+ (and
+ header-value
+ (mail-extract-address-components header-value t))))
+ '("To" "Cc" "Bcc")))
+
+(defun message-all-epg-keys-available-p ()
+ "Return non-nil if the pgp keyring has a public key for each recipient."
+ (require 'epa)
+ (let ((context (epg-make-context epa-protocol)))
+ (catch 'break
+ (dolist (recipient (message-all-recipients))
+ (let ((recipient-email (cadr recipient)))
+ (when (and recipient-email (not (epg-list-keys context recipient-email)))
+ (throw 'break nil))))
+ t)))
+
+(defun message-sign-encrypt-if-all-keys-available ()
+ "Add MML tag to encrypt message when there is a key for each recipient.
+
+Consider adding this function to `message-send-hook' to
+systematically send encrypted emails when possible."
+ (when (message-all-epg-keys-available-p)
+ (mml-secure-message-sign-encrypt)))
+
\f
;;;
(require 'ert)
(require 'ert-x)
+(require 'cl-lib)
+
(ert-deftest message-mode-propertize ()
(with-temp-buffer
(unwind-protect
(should (string= stripped-was
(message-strip-subject-trailing-was with-was)))))))
+(ert-deftest message-all-recipients ()
+ (ert-with-test-buffer (:name "message")
+ (insert "To: Person 1 <p1@p1.org>, Person 2 <p2@p2.org>\n")
+ (insert "CC: Person 3 <p3@p3.org>, Person 4 <p4@p4.org>\n")
+ (insert "BCC: Person 5 <p5@p5.org>, Person 6 <p6@p6.org>\n")
+ (should (equal (message-all-recipients)
+ '(("Person 1" "p1@p1.org")
+ ("Person 2" "p2@p2.org")
+ ("Person 3" "p3@p3.org")
+ ("Person 4" "p4@p4.org")
+ ("Person 5" "p5@p5.org")
+ ("Person 6" "p6@p6.org"))))))
+
+(ert-deftest message-all-epg-keys-available-p ()
+ (let ((person1 '("Person 1" "p1@p1.org"))
+ (person2 '("Person 2" "p2@p2.org"))
+ (person3 '("Person 3" "p3@p3.org"))
+ (recipients nil)
+ (keyring '("p1@p1.org" "p2@p2.org")))
+ (cl-letf (((symbol-function 'epg-list-keys)
+ (lambda (_ email) (cl-find email keyring :test #'string=)))
+ ((symbol-function 'message-all-recipients)
+ (lambda () recipients)))
+
+ (setq recipients (list))
+ (should (message-all-epg-keys-available-p))
+
+ (setq recipients (list person1))
+ (should (message-all-epg-keys-available-p))
+
+ (setq recipients (list person1 person2))
+ (should (message-all-epg-keys-available-p))
+
+ (setq recipients (list person3))
+ (should-not (message-all-epg-keys-available-p))
+
+ (setq recipients (list person1 person3))
+ (should-not (message-all-epg-keys-available-p))
+
+ (setq recipients (list person3 person1))
+ (should-not (message-all-epg-keys-available-p))
+
+ (setq recipients (list person1 person2 person3))
+ (should-not (message-all-epg-keys-available-p)))))
(provide 'message-mode-tests)