# Sending e-mail messages with Python

> Send email from a Python script with the smtplib module, including which mail servers your hosting plan lets you use.

Source: https://helpcenter.ruachost.com/developers/programming-languages/sending-e-mail-messages-with-python/

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

## Important

- On **Shared** 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

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

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

- Official documentation for `smtplib`: [Python smtplib module](https://docs.python.org/3/library/smtplib.html)
