-
Notifications
You must be signed in to change notification settings - Fork 0
/
mailto-opener
executable file
·85 lines (70 loc) · 2.36 KB
/
mailto-opener
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/bin/python3
"""
Open a mailto: link
Takes one argument of the form
mailto:[email protected]?subject=mysubject&body=mybody
Opens in a browser the URL
https://webmail.za3k.com/?_task=mail&_action=compose&[email protected]&_subject=mysubject&_message=mybody
To set this as your program to open mailto links, run:
sudo mailto-opener --install
"""
import pwd, grp
import os, sys
from subprocess import check_output, run
from collections import defaultdict
# Valid mailto keys are: to, subject, body, cc, bcc
# The below is for my Roundcube instance
WEBMAIL_URL="https://webmail.za3k.com/?_task=mail&_action=compose&_to={to}&_subject={subject}&_message={body}"
DEFAULT_BROWSER="xdg-open"
DESKTOP="""
[Desktop Entry]
Type=Application
Name=mailto: link opener (github.com/za3k/short-programs)
# The executable of the application, possibly with arguments.
Exec={BIN} %u
"""
def run_without_root(args):
run(
["sudo",
"-u", "#"+os.environ.get("SUDO_UID"),
"-g", "#"+os.environ.get("SUDO_GID")]+
args
)
def install():
binary = os.path.abspath(__file__)
#myname = sys.argv[0].split("/")[-1]
DESKTOP_NAME = "mailto-opener.desktop"
DESKTOP_PATH = os.path.join("/usr/local/share/applications", DESKTOP_NAME)
with open(DESKTOP_PATH, "w") as f:
f.write(DESKTOP.format(BIN=binary))
run(["desktop-file-validate", DESKTOP_PATH])
# Drop privileges for xdg-mime parts, so it updates the correct user
# This works for xdg-open "mailto:"
# Note that you may need to restart your browser, because several cache the mailto program.
run_without_root(["xdg-mime", "default", DESKTOP_NAME, "x-scheme-handler/mailto"])
def parse_mailto(url):
if url.startswith("mailto:"):
url = url.removeprefix("mailto:")
if "?" in url:
to, url = url.split("?")
d = {}
for part in url.split("&"):
k, v = part.split("=")
d[k] = v
else:
to, d = url, {}
return to, d
def make_url(to, kw):
d = defaultdict(str, kw)
d["to"] = to
return WEBMAIL_URL.format_map(d)
def visit(url):
browser = os.environ.get("BROWSER", DEFAULT_BROWSER)
os.execvp(browser, [browser, url])
if __name__ == '__main__':
if sys.argv[1] == "--install":
install()
else:
to, args = parse_mailto(sys.argv[1])
url = make_url(to, args)
visit(url)