Sending an SMTP Message
To begin, we’ll use Python to send a simple message using the SMTP protocol. Our message will contain the minimum number of message headers, a plain ASCII message body, and no attachments.
To assist in this task, we’ll use the Python module
smtplib
. This module contains a single class,
SMTP
, that manages the connection with the
SMTP server and provides useful methods for interacting with the
server.
Sending a simple message using SMTP is so simple it’s not worth
writing a sample source file for this purpose; you can do it at the
interactive window. The SMTP class provides the
following method:
bad_addresses = sendmail(from,to,message)
-
from A string with the address of the sender.
-
to A list of strings, one for each recipient.
-
message A message as a string formatted as specified in the various RFCs.
So all you need is the message itself, a list of recipients, and your own email address.
As per RFC-822, the format of the message is simple. It consists of a list of message headers, followed by a blank line, followed by the message body. For this demonstration, you can set up a message with the following code:
>>> msg="Subject: Hi from Python\n\nHello."
Define the subject of the message as “Hi from Python” and the body as “Hello.”
Next, define a variable with your email address and SMTP host:
>>> address="MHammond@skippinet.com.au" >>> host="mail-hub"
And send the message to yourself:
>>> import smtplib >>> s=smtplib.SMTP(host) >>> s.sendmail(address, [address], ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access