]> git.cworth.org Git - notmuch-wiki/commitdiff
Add some code to automatically encrypt a message when possible
authorDamien Cassou <damien@cassou.me>
Wed, 28 Mar 2018 12:34:41 +0000 (14:34 +0200)
committerDamien Cassou <damien@cassou.me>
Wed, 28 Mar 2018 12:34:41 +0000 (14:34 +0200)
emacstips.mdwn

index f5b418c6700cec7588040ed85a4b80248ceb528e..215a6725305ace684514b579f974059dd6293f4e 100644 (file)
@@ -455,6 +455,42 @@ Alternatively, you may prefer to use `mml-secure-message-sign-pgpmime` instead
 of `mml-secure-sign-pgpmime` to sign the whole message instead of just one
 part.
 
+If you want to automatically encrypt outgoing messages if the keyring
+contains a public key for every recipient, you can add something like
+that to your `.emacs` file:
+
+    (defun message-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-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)))
+
+    (add-hook 'message-send-hook #'message-sign-encrypt-if-all-keys-available
+
 ### Troubleshooting message-mode gpg support
 
 - If you have trouble with expired subkeys, you may have encountered