[bin] Add a mail-ntfy script

This commit is contained in:
2024-11-07 17:20:41 -05:00
parent 193447e2bd
commit 80ae8c208e

63
bin/.bin/mail-ntfy.py Normal file
View File

@ -0,0 +1,63 @@
import requests
import os
import imaplib
import email
from email.header import decode_header
user = "colin@unbl.ink"
password = os.environ.get("MAIL_PASS")
N = 15
def send_ntfy():
print("Checking for new email ... ")
if not password:
print("Please set your password in the MAIL_PASS environment variable")
return
conn = imaplib.IMAP4_SSL("box.unbl.ink")
conn.login(user, password)
status, messages = conn.select("INBOX")
status, unread = conn.search(None, "UnSeen")
try:
unread = unread[0].decode()
except IndexError:
print("No new messages found")
unread_list = unread.split(" ")
if unread_list == ['']:
print("No new messages found")
return
print(f"Found {len(unread_list)} unread emails")
if unread_list:
for msg_num in unread_list:
# fetch the email message by ID
res, msg = conn.fetch(msg_num, "(RFC822)")
for response in msg:
if isinstance(response, tuple):
msg = email.message_from_bytes(response[1])
subject, encoding = decode_header(msg["Subject"])[0]
if isinstance(subject, bytes):
subject = subject.decode(encoding)
From, encoding = decode_header(msg.get("From"))[0]
if isinstance(From, bytes):
From = From.decode(encoding)
print(f"Found {subject}")
requests.post(
"https://ntfy.unbl.ink/207-comms",
data=subject.encode("utf-8"),
headers={
"Title": From,
"Tags": "envelope",
"Click": "https://box.unbl.ink/mail/?_task=mail&_mbox=INBOX"
}
)
conn.close()
conn.logout()
if __name__ == "__main__":
send_ntfy()