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()
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!