Sending HTML email using Python

前端 未结 10 1342
小鲜肉
小鲜肉 2020-11-22 04:57

How can I send the HTML content in an email using Python? I can send simple text.

10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 05:06

    Here is a simple way to send an HTML email, just by specifying the Content-Type header as 'text/html':

    import email.message
    import smtplib
    
    msg = email.message.Message()
    msg['Subject'] = 'foo'
    msg['From'] = 'sender@test.com'
    msg['To'] = 'recipient@test.com'
    msg.add_header('Content-Type','text/html')
    msg.set_payload('Body of message')
    
    # Send the message via local SMTP server.
    s = smtplib.SMTP('localhost')
    s.starttls()
    s.login(email_login,
            email_passwd)
    s.sendmail(msg['From'], [msg['To']], msg.as_string())
    s.quit()
    

提交回复
热议问题