unsubscribe.py

#196
Raw
Author
winny
Created
Sept. 28, 2020, 1:49 a.m.
Expires
Never
Size
1.0 KB
Hits
467
Syntax
Python
Private
✗ No
#!/usr/bin/env python

"""
A wonky attempt to parse the list-unsubscribe header from an email and
unsubscribe.
"""

from urllib.parse import urlparse, parse_qs
import email
import re
import sys
#import webbrowser


def extract_unsubscribe_url(message):
    value = message['list-unsubscribe']
    url = re.sub(r'<([^<>]*)>', r'\1', value)
    result = urlparse(url)
    return (result, parse_qs(result.query))

MAILTO_TEMPLATE = r"""<enter-command>set $my_editor="/usr/bin/touch %s"; set $my_postpone="$postpone"\n<mail>{to}^M{subject}^M<enter-command>set $editor="$my_editor"; set $postpone="$my_postpone"\n"""

def handle_mailto(mailto):
    print(MAILTO_TEMPLATE.format(
        to=mailto[0].path,
        subject=''.join(mailto[1]['subject']),
    ))

if __name__ == '__main__':
    message = email.message_from_file(sys.stdin)
    mailto = extract_unsubscribe_url(message)
    print(mailto[0].path)
    print(''.join(mailto[1]['subject']))
#    webbrowser.open(extract_unsubscribe_url(message)[0].geturl())