how to add href link in email content when sending email through smtplib

Yuwen Yan picture Yuwen Yan · Jul 30, 2015 · Viewed 17k times · Source

I'm sending email through below code:

msg = MIMEText(u'<a href="www.google.com">abc</a>')
msg['Subject'] = 'subject'
msg['From'] = 'xxx'
msg['To'] = 'xxx'

s = smtplib.SMTP(xxx, 25)
s.sendmail(xxx, xxx, msg.as_string())

what I want to receive is

abc

what I actually received is:

<a href="www.google.com">abc</a>

Answer

Anand S Kumar picture Anand S Kumar · Jul 30, 2015

You should specify 'html' as the subtype -

msg = MIMEText(u'<a href="www.google.com">abc</a>','html')

Without specifying the subtype separately , the subtype defaults to 'plain' (plain-text). From documentations -

class email.mime.text.MIMEText(_text[, _subtype[, _charset]])

A subclass of MIMENonMultipart, the MIMEText class is used to create MIME objects of major type text. _text is the string for the payload. _subtype is the minor type and defaults to plain.

(Emphasis mine) .