I'm trying to parse mailto URLs into a nice object or dictionary which includes subject, body, etc. I can't seem to find a library or class that achieves this- Do you know of any?
mailto:[email protected]?subject=mysubject&body=mybody
You can use urlparse and parse_qs to parse urls with mailto as scheme. Be aware though that according to scheme definition:
mailto:[email protected],[email protected]?subject=mysubject
is identical to
mailto:[email protected]&[email protected]&subject=mysubject
Here's an example:
from urlparse import urlparse, parse_qs
from email.message import Message
url = 'mailto:[email protected]?subject=mysubject&body=mybody&[email protected]'
msg = Message()
parsed_url = urlparse(url)
header = parse_qs(parsed_url.query)
header['to'] = header.get('to', []) + parsed_url.path.split(',')
for k,v in header.iteritems():
msg[k] = ', '.join(v)
print msg.as_string()
# Will print:
# body: mybody
# to: [email protected], [email protected]
# subject: mysubject
The core urlparse lib does less than a stellar job on mailtos, but gets you halfway there:
In [3]: from urlparse import urlparse
In [4]: urlparse("mailto:[email protected]?subject=mysubject&body=mybody")
Out[4]: ParseResult(scheme='mailto', netloc='', path='[email protected]?subject=mysubject&body=mybody', params='', query='', fragment='')
EDIT
A little research unearths this thread. Bottom line: python url parsing sucks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With