Sending e-mail messages with Python

This guide explains how to send e-mail messages using Python.

Important

  • On Shared, Reseller, and Managed WordPress hosting accounts, you cannot use external SMTP servers. You must use the hosting.com mail servers.

  • Other hosting packages may allow some external SMTP servers.


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 hosting.com server:

#!/usr/bin/python3

import sys
import smtplib

from_addr = 'sender@example.com'
to_addrs = ['recipient@example.com']
msg = """From: sender@example.com
To: recipient@example.com
Subject: 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:

  1. from_addr specifies the sender e-mail address.

  2. to_addrs is a list of recipient e-mail addresses.

  3. msg contains the e-mail headers (From, To, Subject) and the message body.

  4. smtplib.SMTP('localhost') connects to the local mail server.

  5. login() authenticates the account.

  6. sendmail() sends the message.

  7. quit() closes the connection.

This example shows the basic functionality of smtplib.

More information

هل كانت المقالة مفيدة ؟ 0 أعضاء وجدوا هذه المقالة مفيدة (0 التصويتات)

Powered by WHMCompleteSolution