Tuesday, September 08, 2020

Searching GMail From GNUS

Using GMail Search Operators In GNUS

1 Executive Summary

I have been using the following to search GMail from GNUS for over 8 years now. The recent announcement of the nnselect back-end reminded me that I had never gotten to writing this up formally, So here goes. With the described solution in place, you can search your GMail from within GNUS using the same GMail Search operators that you're familiar with from within your Web Browser, e.g. searches of the form from: foo, subject:bar, after:date and combinations of the above.

2 Background

You can read email with GNUS, and many people read GMail with GNUS, however, the details of GMail setup with GNUS wont fit this margin. For my own GMail setup using Ceasar's excellent auth-xoauth2 package, see file gnus-gmail-prepare.el.

3 Leveraging GNUS Back-end NNIR To Search GMail

GMail is accessed from GNUS using the imap protocol. The imap specification defines a set of standard search operators; GMail itself defines a slightly different and arguably easier to use set of search operators. Module gm-nnir himplements both the standard IMap search operator as well as GMail's search operators; in practice, I have mostly only used the GMail Search operators in the last 8 years since implementing this module.

Without further ado, here is the code to enable GMail Search:

(defun gm-nnir-group-make-gmail-group (query)
  "Use GMail search syntax.
See https://support.google.com/mail/answer/7190?hl=en for syntax. "
  (interactive "sGMail Query: ")  
  (let ((nnir-imap-default-search-key "imap")
        (q (format "X-GM-RAW \"%s\"" query)))
    (cond
     ((gnus-group-group-name)           ; Search current group
      (gnus-group-make-nnir-group
       nil                              ; no extra params needed
       `(nnir-specs (nnir-query-spec (query ,q)))))
     (t (error "Not on a group.")))))

I bind the above to / by using

(define-key gnus-group-mode-map "/" 'gm-nnir-group-make-gmail-group)

4 Example Of Use

I am subscribed to list emacs-devel@gnu.org and email sent to that list gets GMail Label emacs-devel. In Gnus, I open that label as group emacs-devel@gnu.org. Typing / on the group line and entering

from:rms after:2020/09/01

in the minibuffer results in the following:

1.1 Re: Good first issues to contribute Richard Stallman 05-Sep [5.3k]
2.1 Lars Ingebrigtsen is now one of the Emacs maintainers Richard Stallman 06-Sep [4.9k]
3.1 Re: A new user perspective about "Changes for emacs 28" Richard Stallman 07-Sep [5.5k]
4.5 Re: Changes for emacs 28 Richard Stallman 07-Sep [5.3k]
5.1  Richard Stallman 07-Sep <6.2k>
6.1  Richard Stallman 07-Sep <6.0k>
7.1  Richard Stallman 07-Sep <5.5k>
8.1  Richard Stallman 07-Sep <5.7k>

The search above creates an ephemeral group with matching messages appearing as shown above, you can read messages, reply to them and do anything else that you might ordinarily do within the GNUS interface.