Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse mailto urls in Python

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
like image 341
Yarin Avatar asked Jun 04 '26 19:06

Yarin


2 Answers

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
like image 124
Alexander Holmbäck Avatar answered Jun 07 '26 09:06

Alexander Holmbäck


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.

like image 23
Alien Life Form Avatar answered Jun 07 '26 10:06

Alien Life Form