mail-ntfy.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 = "colin@unbl.ink"
  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. conn = imaplib.IMAP4_SSL("box.unbl.ink")
  20. conn.login(user, password)
  21. status, messages = conn.select("INBOX")
  22. status, unread = conn.search(None, "UnSeen")
  23. try:
  24. unread = unread[0].decode()
  25. except IndexError:
  26. print("No new messages found")
  27. unread_list = unread.split(" ")
  28. if unread_list == ['']:
  29. print("No new messages found")
  30. return
  31. print(f"Found {len(unread_list)} unread emails")
  32. if unread_list:
  33. for msg_num in unread_list:
  34. # fetch the email message by ID
  35. res, msg = conn.fetch(msg_num, "(RFC822)")
  36. for response in msg:
  37. if isinstance(response, tuple):
  38. msg = email.message_from_bytes(response[1])
  39. subject, encoding = decode_header(msg["Subject"])[0]
  40. if isinstance(subject, bytes):
  41. subject = subject.decode(encoding)
  42. From, encoding = decode_header(msg.get("From"))[0]
  43. if isinstance(From, bytes):
  44. From = From.decode(encoding)
  45. print(f"Found {subject}")
  46. requests.post(
  47. "https://ntfy.unbl.ink/207-comms",
  48. data=subject.encode("utf-8"),
  49. headers={
  50. "Title": From,
  51. "Tags": "envelope",
  52. "Click": "https://box.unbl.ink/mail/?_task=mail&_mbox=INBOX"
  53. }
  54. )
  55. conn.close()
  56. conn.logout()
  57. if __name__ == "__main__":
  58. send_ntfy()