Home > Backend Development > Python Tutorial > How Can I Send HTML Emails Using Python?

How Can I Send HTML Emails Using Python?

Patricia Arquette
Release: 2024-11-28 18:39:11
Original
546 people have browsed it

How Can I Send HTML Emails Using Python?

Compose and Send HTML Emails with Python

Sending text-based emails with Python is relatively straightforward. However, if you need to incorporate HTML content for more engaging email designs, here's how to achieve it:

In Python versions 2.7.14 and above, the email module provides convenient functions for creating HTML email messages with alternative plain text versions.

Consider the following code snippet:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# Define sender and recipient addresses
me = "[email protected]"
you = "[email protected]"

# Create a MIME multipart message object
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

# Define the text and HTML versions of the message
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """<html><head></head><body><p>Hi!<br>
How are you?<br>
Here is the <a href="http://www.python.org">link</a> you wanted.
</p></body></html>"""

# Create MIME text objects for both versions
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach both parts to the multipart message in order of preference
msg.attach(part1)
msg.attach(part2)

# Send the email via a local SMTP server
s = smtplib.SMTP('localhost')
s.sendmail(me, you, msg.as_string())
s.quit()
Copy after login

When using this code, be sure to replace "[email protected]" with your own email address and "[email protected]" with the recipient's email address. Additionally, you may customize the message subject and content as desired.

The above is the detailed content of How Can I Send HTML Emails Using Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template