Skip to content

Instantly share code, notes, and snippets.

@BaderSZ
Created January 21, 2022 18:03
Show Gist options
  • Save BaderSZ/cd5a977bd7d5fa357e464b0be29c45ec to your computer and use it in GitHub Desktop.
Save BaderSZ/cd5a977bd7d5fa357e464b0be29c45ec to your computer and use it in GitHub Desktop.
Convert a string from stdin into a thunderbird-compatible URL ASCII body.
#!/bin/env python3
"""
Convert a string from stdin into a thunderbird-compatible URL body.
Run this as follows:
thunderbird -compose "to='[email protected]',body="'<output here>'""
Public domain, Bader Zaidan, 2022
"""
import os
import sys
# mailto formatting as per RFC 1738
char_arr = ["<", ">", '"', "'", "#", "{", "}", "|", "\\", "^",
"~", "[", "]", "`", ";", "/", "?", ":", "@", "=", "&", ",", "."]
# Default vals.
char_dict = {
"%": "%25",
"\n": "%0D%0A",
"\t": "%09",
" ": "%20",
}
def checked_format(char: str):
"""Replace special character with an ASCII one."""
try:
return char_dict[char]
except KeyError:
return char
def formatsc(char: str):
"""Convert character to hex and append %."""
base_hex = format(ord(char), "x").upper()
if len(base_hex) == 1:
return "%0" + base_hex
return "%" + base_hex
def formatstring(string: str):
"""Convert input string's special characters with ASCII format"""
output = ""
for char in string:
output = output + checked_format(char)
return output
def main():
"""Fetch input from stdin and run the above defined functions"""
# create dict for ASCII characters
for char in char_arr:
char_dict[char] = formatsc(char)
# catch STDIN input
stdin_input = "".join(str(x) for x in sys.stdin.readlines())
print(formatstring(stdin_input))
sys.exit(os.EX_OK)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment