mail-ntfy.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. # /// script
  2. # dependencies = [
  3. # "requests",
  4. # ]
  5. # ///
  6. import requests
  7. import os
  8. import imaplib
  9. import email
  10. from email.header import decode_header
  11. user = os.environ.get("MAIL_USER")
  12. password = os.environ.get("MAIL_PASS")
  13. N = 15
  14. def send_ntfy():
  15. print("Checking for new email ... ")
  16. if not password:
  17. print("Please set your password in the MAIL_PASS environment variable")
  18. return
  19. if not user:
  20. print("Please set your user in the MAIL_USER environment variable")
  21. return
  22. conn = imaplib.IMAP4_SSL("box.unbl.ink")
  23. conn.login(user, password)
  24. status, messages = conn.select("INBOX")
  25. status, unread = conn.search(None, "UnSeen")
  26. try:
  27. unread = unread[0].decode()
  28. except IndexError:
  29. print("No new messages found")
  30. unread_list = unread.split(" ")
  31. if unread_list == ['']:
  32. print("No new messages found")
  33. return
  34. print(f"Found {len(unread_list)} unread emails")
  35. if unread_list:
  36. for msg_num in unread_list:
  37. # fetch the email message by ID
  38. res, msg = conn.fetch(msg_num, "(RFC822)")
  39. for response in msg:
  40. if isinstance(response, tuple):
  41. msg = email.message_from_bytes(response[1])
  42. subject, encoding = decode_header(msg["Subject"])[0]
  43. if isinstance(subject, bytes):
  44. subject = subject.decode(encoding)
  45. From, encoding = decode_header(msg.get("From"))[0]
  46. if isinstance(From, bytes):
  47. From = From.decode(encoding)
  48. print(f"Found {subject}")
  49. requests.post(
  50. "https://ntfy.unbl.ink/207-comms",
  51. data=subject.encode("utf-8"),
  52. headers={
  53. "Title": From,
  54. "Tags": "envelope",
  55. "Click": "https://box.unbl.ink/mail/?_task=mail&_mbox=INBOX"
  56. }
  57. )
  58. conn.close()
  59. conn.logout()
  60. if __name__ == "__main__":
  61. send_ntfy()