Something went wrong. Try again.
nixos/home-manager config
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144"""Read the user's Gmail over IMAP.
Searches use Gmail's own search syntax, so queries behave as they do in theGmail search box. The mailbox is opened read-only, so nothing is marked read."""
import argparseimport emailimport email.headerimport htmlimport imaplibimport osimport reimport sysimport timefrom pathlib import Path
class GmailError(Exception): pass
def connect(): user = os.environ.get("GMAIL_USER") password_file = os.environ.get("GMAIL_APP_PASSWORD_FILE") if not user or not password_file: raise GmailError("GMAIL_USER and GMAIL_APP_PASSWORD_FILE must be set.") imap = imaplib.IMAP4_SSL("imap.gmail.com") imap.login(user, Path(password_file).read_text().strip()) # UK accounts call it "[Google Mail]/All Mail", so find it by its flag. _, boxes = imap.list() all_mail = next(b.decode().rsplit(' "/" ', 1)[1] for b in boxes if b"\\All" in b) imap.select(all_mail, readonly=True) return imap
def search(imap, query): """UIDs of messages matching a Gmail search query, newest first.""" quoted = '"' + query.replace("\\", "\\\\").replace('"', '\\"') + '"' _, data = imap.uid("SEARCH", "X-GM-RAW", quoted) return list(reversed(data[0].split()))
def fetch(imap, uid): """A message and the time Gmail received it.""" _, parts = imap.uid("FETCH", uid, "(INTERNALDATE BODY.PEEK[])") received = time.mktime(imaplib.Internaldate2tuple(parts[0][0])) return email.message_from_bytes(parts[0][1]), received
def header(message, name): return str(email.header.make_header(email.header.decode_header(message.get(name, ""))))
def body_text(message): """The message's plain-text body, or its HTML body with the markup removed.""" parts = sorted( (p for p in message.walk() if p.get_content_maintype() == "text"), key=lambda p: p.get_content_subtype() != "plain", ) if not parts: return "" text = parts[0].get_payload(decode=True).decode(parts[0].get_content_charset() or "utf-8", errors="replace") if parts[0].get_content_subtype() == "html": text = re.sub(r"<!--[\s\S]*?-->|<(style|script)[\s\S]*?</\1>|<[^>]+>", " ", text) text = html.unescape(text) return re.sub(r"[ \t]+", " ", re.sub(r"\n\s*\n+", "\n\n", text)).strip()
def cmd_search(imap, args): uids = search(imap, args.query)[:args.limit] for uid in uids: message, received = fetch(imap, uid) when = time.strftime("%Y-%m-%d %H:%M", time.localtime(received)) print(f"{uid.decode()} {when} {header(message, 'From')} | {header(message, 'Subject')}") if not uids: print("No messages match.")
def cmd_read(imap, args): message, received = fetch(imap, args.uid.encode()) for name in ("From", "To", "Date", "Subject"): print(f"{name}: {header(message, name)}") print() text = body_text(message) print(text[:args.max_chars] + ("\n[truncated]" if len(text) > args.max_chars else ""))
def cmd_code(imap, args): """Print the code from the newest matching message received after --since.""" pattern = re.compile(rf"(?<![#\w])(\d{{{args.digits}}})(?!\w)") deadline = time.time() + args.wait while True: for uid in search(imap, args.query): message, received = fetch(imap, uid) # Allow for Gmail's clock running behind this one. if received < args.since - 60: break m = pattern.search(body_text(message)) if m: print(m.group(1)) return if time.time() >= deadline: raise SystemExit(1) time.sleep(10) imap.noop()
def main(): p = argparse.ArgumentParser(prog="gmail", description=__doc__.splitlines()[0]) sub = p.add_subparsers(dest="cmd", required=True)
s = sub.add_parser("search", help="list messages matching a Gmail search query, newest first") s.add_argument("query") s.add_argument("--limit", type=int, default=10) s.set_defaults(fn=cmd_search)
s = sub.add_parser("read", help="print one message by the UID that `search` shows") s.add_argument("uid") s.add_argument("--max-chars", type=int, default=4000) s.set_defaults(fn=cmd_read)
s = sub.add_parser("code", help="print a one-time code from the newest matching message; exits 1 if none arrives") s.add_argument("query") s.add_argument("--since", type=float, default=0, help="ignore messages received before this Unix time") s.add_argument("--wait", type=float, default=0, help="seconds to keep checking for a new message") s.add_argument("--digits", type=int, default=6) s.set_defaults(fn=cmd_code)
args = p.parse_args() try: imap = connect() except (GmailError, OSError, imaplib.IMAP4.error) as e: print(f"error: {e}", file=sys.stderr) sys.exit(2) try: args.fn(imap, args) finally: imap.logout()
if __name__ == "__main__": main()