Sending Emails using Python



In this post, I will show you how to build a simple email application sender in Python. Note that this application can be automated use crontab or asyncio. I will soon write an article showing how.


Modules used

The modules that will be used are


1. smtplib - handles the sending of email messages through the SMTP protocol.

2. email - handles the email composing and structuring.





Configuration 

In order to keep the code maintainable, lets start by isolating the configuration part of the project in a file called conf.py 





In conf.py type the above while substituting the values of each with values that are relevant to your application. 


Configuration Explanation 


To initialize the class ServerConfig, you must provide two values,  self.__adminEmail, which corresponds to the email you want to send from and self.__adminPassword, the password for that account. 


By initializing the class ServerConfig, the server is also initiated over the SMTP protocol for the host gmail. I chose gmail as it is the most popular, however, you may choose any other host supported. Port 587 is primarily used between email users to submit email messages to the server. I will not go into more detail on this subject but if you're interested, wiki smtp.


Furthermore, the class initiation authenticates the connection before permanently connecting to the  server. In the serverAuthentication function, a method ehlo is executed. This method serves to identify a user to the server. The server then responds with all of the attributes it exhibits. As concerned users we are looking for an attribute called 'STARTTLS'. Once we confirm that it exists, the connection is authenticated and the permission to start the connection (by the if statement) to the server is granted. For more details on STARTTLS check this link.


Composing the Email and Sending it 


Now that we've established the connection to the server, it's time for the more tangible part, writing the email's subject and body. Make the following imports 



from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def HTML(name):
        html = """\
        <h1> """ + str(name) + """ Hello World</h1>
        <p>Hello World (again)</p>``
                <img src="cid:image1">
            </p>
        """
        msghtml = MIMEText(html, 'html')

        return msghtml

msgHTML = HTML
newMessage = MIMEMultipart()
newMessage['From'] = adminEmail
newMessage['Subject'] = 'Hello World'
newMessage.attach(msgHTML)
text = newMessage.as_string()
server.sendmail(adminEmail, ToEmail, text)

The above code is a simple application for sending composing and sending the email. First, the HTML function defines the body of the email and returns it as an instance of MIMEText. Which is then attached to the newly created email (MIMEMultipart()). After that the message is converted to string and sent using the .sendmail method of the smtplib class. 

Check out the full code on GitHub here!