Following on from my Sending Text Email In Python article here is a slightly more advanced script that sends HTML formatted emails. The mechanism is fairly similar.
As with the text example you need access to an SMTP server which you will probably have if you have a web hosting account or ISP that allows you to send email.
The required SMTP details are:
- SMTP server domain
- Username
- Password
These details will need to be inserted into the appropriate places in the example Python script below.
# Import smtplib to provide email functions import smtplib # Import the email modules from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # Define email addresses to use addr_to = 'user1@example.com' addr_from = 'user2@example.com' # Define SMTP email server details smtp_server = 'mail.example.com' smtp_user = 'test@example.com' smtp_pass = '1234567889' # Construct email msg = MIMEMultipart('alternative') msg['To'] = addr_to msg['From'] = addr_from msg['Subject'] = 'Test Email From how2code' # Create the body of the message (a plain-text and HTML version). text = "This is a test message.\nText and html." html = """\ <html> <head></head> <body> <p>This is a test message from how2code.</p> <p>This is the HTML part.</p> </body> </html> """ # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') # Combine parts into message container. # According to RFC 2046, the last part of a multipart message, # in this case the HTML message, is best and preferred. msg.attach(part1) msg.attach(part2) # Send the message via an SMTP server s = smtplib.SMTP(smtp_server) s.login(smtp_user,smtp_pass) s.sendmail(addr_from, addr_to, msg.as_string()) s.quit()
This script doesn’t attempt to do any error trapping. A worthwhile enhancement would be to wrap the final four lines in a ‘try’ block to catch any errors in the sending process. These errors may be caused by invalid user details, a server error or an internet connection problem.
2 Comments
Hi Matt,
Your Syntax Highlighter plugin appears to have stripped the html tags from the html string in your code example.
Cheers
Graham.
Thanks Graham. The tags were missing from the actual post content so I’m not sure what stripped them out. I’ve seen it happen before but missed it this time!