The previous two articles in this series discussed connecting to the two major types of email servers and downloading messages. The task yet to be discussed is the actual sending of a message and how to represent an email message logically. In the first part of this article, we will discuss how to create the local data structure to represent an email message. The second part deals with actually connecting to an SMTP server and sending the message.
The first step in sending an email message is to instantiate an “SMTP” object with the IP address and port of the remote SMTP server where the client should connect. If these arguments aren’t supplied, you will have to call the “connect” method after instantiation to connect to the server. Once you’ve created the SMTP object, normally all you will need to use are the “sendmail” method and “quit” to close the connection.
In addition to these methods, the SMTP library also allows a client to authenticate with a username and password for servers that require authentication. Also, you can directly issue an SMTP command with the server using the “docmd” method. This is great for writing your own SMTP extensions, or for beginning to implement your own SMTP class. You can also use the SMTP “VRFY” command with the “verify” method to find out if a server has a specific address. However, remember that this functionality is often disabled on servers today for security reasons and to prevent spammers from taking advantage of it to send junk email.
The SMTP class’s “sendmail” function is the most interesting for this article. When you call this method, you must send strings with the “To:” and “From:” addresses as well as the full message represented as a string. In order to make parsing email useful, you will probably want to send the messages you’ve parsed at some point, or use a built “Message” object structure to send an email. You will need to get a string representation of your “Message” objects. This is as easy as calling the “as_string” method on the top “Message” object in the hierarchy. This returns a string encoded representation of the message ready for sending with the SMTP object. Following is an example of sending a message. Again we will assume that “emailMessage” is a Message object with data about some email.
server = SMTP(“18.104.22.168”) server.login(“username”, “password”) server.sendmail(emailMessage[‘from’], emailMessage[‘to’], emailMessage.as_string()) server.quit()
In general, sending email with Python is really very easy. You can take as much or as little control over the process as you wish. It’s certainly possible to jump in with just the built-in classes that are provided and build most applications for email. However, if you need to go deeper, many tools are provided for you to do just that, all within the great framework of the Python scripting engine.