Skip to content

Instantly share code, notes, and snippets.

@rtrppl
Last active June 19, 2024 05:44
Show Gist options
  • Save rtrppl/1ffdc842a9b536c8f3a9ec583e4bca09 to your computer and use it in GitHub Desktop.
Save rtrppl/1ffdc842a9b536c8f3a9ec583e4bca09 to your computer and use it in GitHub Desktop.
Use Dired to pick attachments for mu4e
(defvar attachment-folder "~/Desktop/")
(defvar compose-buffer nil)
(with-eval-after-load 'mu4e
(define-key mu4e-compose-mode-map (kbd "C-c C-a") 'lt/mml-attach-file))
(with-eval-after-load 'dired
(define-key dired-mode-map (kbd "E") 'lt/process-marked-files-as-attachments))
(defun lt/mml-attach-file ()
"Opens a Dired buffer to select attachments. The keybinding to send these back to the email draft is E."
(interactive)
(setq compose-buffer (buffer-name))
(dired attachment-folder)
(revert-buffer)
(message "Press E to pick all marked files as attachments."))
(defun lt/process-marked-files-as-attachments ()
"Processes all marked files in the Dired buffer as attachments for mu4e."
(interactive)
(if (dired-get-marked-files)
(progn
(let ((marked-files (dired-get-marked-files)))
(dired-unmark-all-marks)
(with-temp-buffer
(dolist (file marked-files)
(insert "<\#part filename=\"" file "\">\n" "<\#\/part>"))
(setq attachments (buffer-string))))
(if compose-buffer
(lt/return-to-mu4e-draft)
(lt/create-new-mu4e-draft)))
(message "No files selected.")))
(defun lt/return-to-mu4e-draft ()
"Returns to the mu4e draft and inserts all attachments at point."
(revert-buffer)
(when compose-buffer
(switch-to-buffer compose-buffer)
(save-excursion (goto-char (point-max))
(insert "\n\n" attachments)))
(setq compose-buffer nil))
(defun lt/after-mu4e-compose (&rest _args)
"Function to run after a new mu4e compose buffer is created.
Accepts any number of arguments, but they are not used."
(run-with-timer 0.1 nil
(lambda ()
(with-current-buffer (current-buffer)
(when (and (eq major-mode 'mu4e-compose-mode)
(not buffer-read-only))
(save-excursion (goto-char (point-max))
(insert "\n" attachments)))))))
(defun lt/create-new-mu4e-draft ()
"Creates a new draft in mu4e and attaches the selected attachments."
(advice-add 'mu4e-compose-new :after #'lt/after-mu4e-compose)
(mu4e-compose-new)
(advice-remove 'mu4e-compose-new #'lt/after-mu4e-compose))
@mankoff
Copy link

mankoff commented Jun 18, 2024

I think attachments are supposed to be at the end of the email? Not sure about this. If so, I recommend L38 change to:

(save-excursion (goto-char (point-max))  (insert attachments)))

@rtrppl
Copy link
Author

rtrppl commented Jun 19, 2024

You are right. Also: save-excursion was made for this. Changed both inserts. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment