D.3 Saving outgoing messages

Like mu4e-refile-folder, the variable mu4e-sent-folder can also be set to a function, in order to dynamically determine the save folder. One might, for example, wish to automatically put messages going to mailing lists into the trash (because you’ll receive them back from the list anyway). If you have set up the variable my-mu4e-mailing-lists as mentioned, you can use the following function to determine a ’sent’-folder:

(defun my-mu4e-sent-folder-function (msg)
  "Set the sent folder for the current message."
  (let ((from-address (message-field-value "From"))
        (to-address (message-field-value "To")))
    (cond
     ((string-match "my.address@account1.example.com" from-address)
      (if (member* to-address my-mu4e-mailing-lists
                   :test #'(lambda (x y)
                             (string-match (car y) x)))
          "/Trash"
        "/Account1/Sent"))
     ((string-match "my.address@gmail.com" from-address)
      "/Gmail/Sent Mail")
     (t (mu4e-ask-maildir-check-exists "Save message to maildir: ")))))

Note that this function doesn’t use (mu4e-message-field msg :maildir) to determine which account the message is being sent from. The reason is that the function in mu4e-sent-folder is called when you send the message, but before mu4e has created the message struct from the compose buffer, so that mu4e-message-field cannot be used. Instead, the function uses message-field-value, which extracts the values of the headers in the compose buffer. This means that it is not possible to extract the account name from the message’s maildir, so instead the from address is used to determine the account.

Again, the function shows three different possibilities: for the first account (my.address@account1.example.com) it uses my-mu4e-mailing-lists again to determine if the message goes to a mailing list. If so, the message is put in the trash folder, if not, it is saved in /Account1/Sent. For the second (Gmail) account, sent mail is simply saved in the Sent Mail folder.

If the from address is not associated with Account1 or with the Gmail account, the function uses mu4e-ask-maildir-check-exists to ask the user for a maildir to save the message in.