mail-ntfy.py 1.9 KB

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