Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Convert email address to HTML link

I'm looking for a stand-alone python function that will take in a string and return a string with the email addresses converted to links.

Example:

>>>s = 'blah blah blah [email protected] blah blah blah'
>>>link(s)
'blah blah blah <a href="mailto:[email protected]">[email protected]</a> blah blah blah'
like image 784
Muhd Avatar asked Apr 20 '26 22:04

Muhd


2 Answers

Something like this?

import re
import xml.sax.saxutils

def anchor_from_email_address_match(match):
    address = match.group(0)
    return "<a href=%s>%s</a>" % (
        xml.sax.saxutils.quoteattr("mailto:" + address),
        xml.sax.saxutils.escape(address))

def replace_email_addresses_with_anchors(text):
    return re.sub("\w+@(?:\w|\.)+", anchor_from_email_address_match, text)

print replace_email_addresses_with_anchors(
    "An address: [email protected], and another: [email protected]")
like image 159
Croad Langshan Avatar answered Apr 23 '26 10:04

Croad Langshan


>>> def convert_emails(s):
...     words =  [ word if '@' not in word else '<a href="mailto:{0}">{0}</a>'.format(word) for word in s.split(" ") ]
...     return " ".join(words)
... 
>>> s = 'blah blah blah [email protected] blah blah blah'
>>> convert_emails(s)
'blah blah blah <a href="mailto:[email protected]">[email protected]</a> blah blah blah'
>>> 

Not super robust but works for very basic cases.

like image 34
dting Avatar answered Apr 23 '26 12:04

dting



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!