Now you can Subscribe using RSS

Submit your Email

Sunday

How to Send Emails Using Python

Vishal Shrestha
Python has some modules in the standard library that help working with emails and email servers.
In this guide we will be using the smtplib module of python. SMPTlib defines an SMTP client session object that is used to email any Internet machine with an SMTP or ESMTP listener daemon.

By the end of this guide, you'll be able to just send emails using such a simple line of code:

# Params: from_email, password, to_email, subject, email_body
mailman.sendmail('SENDER EMAIL', 'PASSWORD', 'TO EMAIL', 'SUBJECT','BODY')

In this guide, we will be sending emails using gmail's email and smtp server as example, you can use any server according to your requirement. You can checkout the video tutorial here:



There are 4 basic steps to send email with python, those are:
  1. Set up the SMTP server and log into your account.
  2. Create a MIMEMultipart object and add appropriate headers.
  3. Add message body.
  4. Send the message using the SMTP server object.
Here's the sample code:

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


def sendmail(from_email, password, to_email, subject, message):
    # setup the parameters of the message
    msg = MIMEMultipart()
    msg['From'] = from_email
    msg['To'] = to_email
    msg['Subject'] = subject

    # add in the message body
    msg.attach(MIMEText(message, 'plain'))
    try:

        # set up the SMTP server
        # host and port, you can leave port empty as 465 is the default anyway
        server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        server.ehlo()
        server.login(msg['From'], password)
        server.sendmail(msg['From'], msg['To'], msg.as_string())
        server.close()
        return True
    except Exception as e:
        print('Something went wrong: ' + str(e))
        return False

Now you can call this method wherever you like to send emails like this:

sendmail('SENDER EMAIL', 'PASSWORD', 'TO EMAIL', 'SUBJECT',
                 'BODY')


There are a lot more things that I've not covered here, but I hope this gets you started, if you have any issues sending email from python, feel free to ask about those in the comments section below.

Vishal Shrestha / Author & Founder

A developer by profession, a born Adventurer. I mainly do Android but like to get my hands dirty with web development and a little bit of Python. I would't rather go on a Trek than a party and you can find me having a few rounds with the heavy bag to let out the steam ;)

WORK

Research and Development at : Ekghanti

Mobile Technology Lead at : Vimvox Lab

For Business info : My Portfolio Site

0 comments:

Post a Comment

Coprights @ 2017 | The Code City by Vishal Shrestha Vishal Shrestha