Last active
April 25, 2020 15:57
-
-
Save holly/bb8a73b9f22cda6ab4d4e9e584691d78 to your computer and use it in GitHub Desktop.
from your imap stored mail to line notify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# vim:fileencoding=utf-8 | |
""" [NAME] script or package easy description | |
[DESCRIPTION] script or package description | |
""" | |
import os, sys, io | |
import base64 | |
import email | |
import email.header | |
import imaplib | |
import quopri | |
import urllib | |
import urllib.request | |
import json | |
LINE_NOTIFY_URL = 'https://notify-api.line.me/api/notify' | |
LINE_TOKEN = 'your_line_token' | |
LINE_NOTIFY_FORMAT = ''' | |
Subject: {0} | |
{1}''' | |
IMAP_HOST = 'your_imap_host' | |
IMAP_PORT = 993 | |
IMAP_USER = 'your_account' | |
IMAP_PASS = 'your_password' | |
IMAP_FOLDERS = [ "label_or_folder" ] | |
def notify_line(subject, body): | |
form_data = urllib.parse.urlencode({ 'message': LINE_NOTIFY_FORMAT.format(subject, body) }) | |
form_headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer {0}'.format(LINE_TOKEN) } | |
req = urllib.request.Request(LINE_NOTIFY_URL, data=form_data.encode(), headers=form_headers, method='POST') | |
try: | |
with urllib.request.urlopen(req) as res: | |
body = json.loads(res.read()) | |
status = body["status"] | |
message = body["message"] | |
except urllib.error.HTTPError as e: | |
status = e.code | |
message = e | |
return status, message | |
def parse(data): | |
msg = email.message_from_bytes(data[0][1]) | |
decoded = email.header.decode_header(msg["subject"]) | |
if decoded[0][1] is not None: | |
subject = decoded[0][0].decode(decoded[0][1]) | |
else: | |
subject = decoded[0][0] | |
if msg.is_multipart(): | |
part = msg.get_payload()[0] | |
charset = part.get_content_charset() | |
payload = part.get_payload(decode=True) | |
else: | |
charset = msg.get_content_charset() | |
payload = msg.get_payload(decode=True) | |
if charset is None: | |
charset = "UTF-8" | |
body = payload.decode(charset).strip() | |
return subject, body | |
def main(): | |
m = imaplib.IMAP4_SSL(IMAP_HOST, IMAP_PORT) | |
m.login(IMAP_USER, IMAP_PASS) | |
for folder in IMAP_FOLDERS: | |
m.select(folder) | |
typ, data = m.search(None, 'ALL') | |
for num in data[0].split(): | |
typ, data = m.fetch(num, '(RFC822)') | |
subject, body = parse(data) | |
status, message = notify_line(subject, body) | |
print("subject:{0} status:{1} message:{2}".format(subject, status, message)) | |
if status == 200: | |
m.store(num, '+FLAGS', '\\Deleted') | |
m.expunge() | |
m.close() | |
m.logout() | |
sys.exit(0) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment