Sending mails with Python | extrovert.dev -->

Sending mails with Python

Sending mails with Python
Tuesday, December 25, 2018


   Every Pythonista will be loving to have his works to be done in python. Here in this post we will see how to send mails using python libraries. This will help you to embed the email automation functions in your project.

Using smtplib and Mail:


    Smtp stands for simple mail transfer protocol. You know that a Hyper text transfer protocol calls the data from host server , in the same way a smtp calls the data from a mail server. What is the advantage of smtplib is , It will connect to the host with the data like host , port provided by the user using connect() if not it will use the socket.getfqdn() method to detect the credentials automatically to implement success method else it will raise the corresponding Exception. 

      If you are new to the email python package read the official doc here .

Let us see an example

import smtplib
from email.message import EmailMessage
def send_mail(to_email, subject, message, server='smtp.example.cn',
              from_email='xx@example.com'):
    # import smtplib
    msg = EmailMessage()
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = ', '.join(to_email)
    msg.set_content(message)
    print(msg)
    server = smtplib.SMTP(server)
    server.set_debuglevel(1)
    server.login(from_email, 'password')  # user & password
    server.send_message(msg)
    server.quit()
    print('successfully sent the mail.')



Using Mailgun API :


     Mailgun API provides you a clean and easy solution to send mails. Ofcourse this API is restricted to just 10,000 mails per month for free. Here is a simple implementation 

def send_simple_message():
    return requests.post( "https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages", 
auth=("api", "YOUR_API_KEY"),data={"from": "Excited User ",
              "to": ["bar@example.com", "YOU@YOUR_DOMAIN_NAME"],
              "subject": "Hello",
              "text": "Testing some Mailgun awesomness!"})

To learn more go to Quickstart Guide

1 Response to Sending mails with Python

  1. your website is good and you are doing well Mr. adarsh.. 🙂

    ReplyDelete