Sending emails using Python

Thanks to the large standard library, Python is the right tool to write a portable script to send emails. The core functionality to encode an email is contained inside the “email” Python module. The conncetion to the smtp is managed by means of the “smtp” module.

from smtplib import SMTP
from smtplib import SMTP_SSL

import email
import email.mime.application
import email.mime.text

We are going to write a small class (called “smtpSender”) to take advantage of the Python object oriented programming style. The constructor of the class will be in charge of storing information about the smtp server whereas the “send” method will perform all the actions required to actually send emails. This splitting (constructor / send method) is useful when we want to send multiple email through the same smtp server.

class smtpSender:
    def __init__(self, server_addr=None, server_port=None, \
        username=None, password=None, \
        method='plain'):
...

    def send(self, from_addr, to_addr, subject='', text='', \
        attachments=[]):
    ...

An instance of this class can be created specifying the smtp server address, server port, username, password and encription method.

if __name__ == "__main__":

    # ------------------------------
    # Common settings - Example for GMAIL

    server_addr = "smtp.gmail.com"
    server_port = 587
    username = "your_email_address@gmail.com"
    password = "your_password"
    method = 'TLS'

    # ------------------------------
    # Test settings

    from_addr = "sender@gmail.com"
    to_addr = ["receiver@blabla.com"]

    subj = "Test"
    message_txt = "Hello!"

    # ------------------------------
    # Send the message

    sender = smtpSender(server_addr, server_port, \
        username, password, method)

    # Just text!
    sender.send(from_addr, to_addr, subj, message_txt)

    # With attachment!
    sender.send(from_addr, to_addr, subj, message_txt, \
        ['attachment.txt'])

Please, find the complete code in the document enclosed! Any comment is welcomed! 🙂

Leave a Reply

avatar
  Subscribe  
Notify of

Pin It on Pinterest