Sending HTML email using Python

前端 未结 10 1161
小鲜肉
小鲜肉 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:17

    for python3, improve @taltman 's answer:

    • use email.message.EmailMessage instead of email.message.Message to construct email.
    • use email.set_content func, assign subtype='html' argument. instead of low level func set_payload and add header manually.
    • use SMTP.send_message func instead of SMTP.sendmail func to send email.
    • use with block to auto close connection.
    from email.message import EmailMessage
    from smtplib import SMTP
    
    # construct email
    email = EmailMessage()
    email['Subject'] = 'foo'
    email['From'] = 'sender@test.com'
    email['To'] = 'recipient@test.com'
    email.set_content('red color text', subtype='html')
    
    # Send the message via local SMTP server.
    with smtplib.SMTP('localhost') as s:
        s.login('foo_user', 'bar_password')
        s.send_message(email)
    

提交回复
热议问题