You found this article because you want to send emails using Python script. Now a days, it’s a common task to send email through a system. In this article will learn how to send emails with simple text/HTML contents with/without attachment in Python.

Image for post

There are so many ways to send mail through python code. One is by using the **smtplib **module. One setting needs to be changed in the gmail account to receive the email from python script.

Setting up a Gmail Account

Better to create a new gmail account and use in development because there’s a chance you might accidentally expose your login details. Also, the inbox gets filled up rapidly with test emails. Below link will redirect on required page of gmail setting as shown below in picture.

Turn Allow less secure app to ON

Image for post

Implementation

Required module need to be import at the beginning of the code.

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

Configured the email attributes like subject ,receiver email, sender email, password of sender.

sender_email = 'mypython2244@gmail.com'
receiver_email = 'mypython2244@gmail.com'
password = 'XXXXXX'  ## please put your password here.

message = MIMEMultipart("alternative")
message["Subject"] = "How to send mail from a Python script"
message["From"] = sender_email
message["To"] = receiver_email

Here two variable create one holding plain text and other holding HTML code these represents two different message body. Here will learn how to configure plain text and html text in email body.

Body_text = """
Hi,
This is plain text messag and you are learing How to send mail from a Python script."""

body_html = """\
<html>
  <body>
    <p>Hi Team <br>
       <h2> Please clink on link below to create gmail account. </h2><br>
       <a href="http://www.gmail.com">Create Account</a> 

    </p>
  </body>
</html>
"""

Now the final step is to attache these two body with mail content and send to gmail account.

## Turn these into plain/html MIMEText objects
part1 = MIMEText(text, "Body_text")
part2 = MIMEText(html, "body_html")

## Add HTML/plain-text parts to MIMEMultipart message
message.attach(part1)
message.attach(part2)
## Create secure connection with server and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
    server.login(sender_email, password)
    server.sendmail(
        sender_email, receiver_email, message.as_string()
    )

#email #django #python #gmail

How to Send mail from a Python script to Gmail account
28.35 GEEK