This is a mailto: URI handler written in Python 3.4.

The first part of the script parses the URI and constructs a Message object.

The second part of the script should be modified according to your own use case. In my case, the message is written to my Mutt postponed messages directory so I can go to Mutt and press m to edit and send it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/bin/python
#
# Parses mailto: URI passed as the only argument and constructs a message.
#
# by Alexandre de Verteuil
# 2015-04-10
#
# To my knowledge, it properly handles all examples and special cases
# in http://www.ietf.org/rfc/rfc6068.txt

import sys

from urllib.parse import urlparse, parse_qs, unquote
from email.message import Message
from email.charset import Charset, QP

parsed_uri = urlparse(sys.argv[1])
query_dict = parse_qs(parsed_uri.query)

charset = Charset("utf-8")
charset.header_encoding = QP
charset.body_encoding = QP

def header_encode(s):
    if max(s.encode()) > 127:
        return charset.header_encode(s)
    else:
        return s

message = Message()

if parsed_uri.path != "":
    message['To'] = header_encode(unquote(parsed_uri.path))

if 'body' in query_dict:
    message.set_payload(query_dict['body'][0])
    del query_dict['body']
    message.set_charset(charset)

for k, v in query_dict.items():
    if k.lower() == "to" and 'to' in message:
        v = [message[k]] + v
        del message[k]
    message[k] = header_encode(",".join(v))

# The message is now usable as message.as_string() or str(message).
# Edit under this comment according to the way you want to handle it.

from tempfile import mkstemp
from os.path import expanduser

dir = expanduser("~/var/mail/brouillons/new")
fd, path = mkstemp(prefix="mailto_", dir=dir)
with open(fd, "wb") as f:
    f.write(bytes(message))

Comments

Comment Atom Feed

There are no comments yet.

Add a Comment

You can use the Markdown syntax to format your comment.