The Python smtplib module offers a high-level interface to what is typically a very low-level process, offering handy dictionary returns and several convenience methods to process and send SMTP e-mail messages.  Anyone who has worked with e-mail knows it can be a beast, with effective diagnosis of issues often involving time-consuming review of cryptic logs and a cascading list of potential “gotchas” to miss or misinterpret; this tool is part one in a suite of utilities that will help to streamline the scripted sending of messages and provide a more human-readable alerts system based on scraping e-mail headers of received messages.

The mailer script itself it very simple.  Because my test host requires SMTP authentication and offers secure connections, I decided to implement a solution using both smtplib.SMTP and smtplib.SMTP_SSL.

$ python --help
usage: -s [SERVER:PORT] [-p [PASSWORD]] -f [FROM] -t [TO] [LIST]

optional arguments:
  -h, --help            show this help message and exit
  -v, --verbose         Enable verbose output
  -s SERVER, --server SERVER
                        SMTP Server or IP
  -p [{25,26,587,465}], --port [{25,26,587,465}]
  -f SOURCE, --source SOURCE
                        Source E-mail Address
  -t TO [TO ...], --to TO [TO ...]
                        Recipient List

SSL sending is detected by the port, and specifying port 465 is (currently) the only way to send using encryption using this utility.  The specification will default to 25 if a host is provided without a port.  Option -v | –verbose will display the full communication output.

$ python -s -p 465 -f -t
SMTP Sender Password > 
** Using smtplib.SMTP_SSL
** Sendmail completed : {}

Verbose Example

The SMTPMessage class can be used to directly access this functionality, it expects an argument object with each of the required attributes (like an argparse argument object or a PokeyConfig instance).

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.