Sending e-mail messages with Python
This guide explains how to send e-mail messages using Python.
Important
Section titled “Important”- On Shared, Reseller, and Managed WordPress hosting accounts, you cannot use external SMTP servers. You must use the Ruachost mail servers.
- Other hosting packages may allow some external SMTP servers.
Using Python to send e-mail
Section titled “Using Python to send e-mail”Python’s smtplib module allows you to send e-mail messages from a script. You create an instance of the SMTP class, which handles connecting to a mail server and sending messages.
Here is a sample Python script for sending e-mail from a Ruachost server:
#!/usr/bin/python3
import sysimport smtplib
from_addr = 'sender@example.com'to_addrs = ['recipient@example.com']msg = """From: sender@example.comTo: recipient@example.comSubject: This is the message subject
This is the message body."""
try: s = smtplib.SMTP('localhost') s.login('sender@example.com', 'password') s.sendmail(from_addr, to_addrs, msg) s.quit()except smtplib.SMTPException: print("Error:", sys.exc_info()[0])Explanation
Section titled “Explanation”from_addrspecifies the sender e-mail address.to_addrsis a list of recipient e-mail addresses.msgcontains the e-mail headers (From,To,Subject) and the message body.smtplib.SMTP('localhost')connects to the local mail server.login()authenticates the account.sendmail()sends the message.quit()closes the connection.
This example shows the basic functionality of smtplib.
More information
Section titled “More information”- Official documentation for
smtplib: Python smtplib module