O'Reilly logo

Python Programming On Win32 by Mark Hammond, Andy Robinson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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], ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required