I want to email from Gmail using Python.

Hi everyone, long time no see. Little by little, I'll start posting.

This theme

Log in to gmail with Python and send an email.

reference

~ Sending mail using Gmail with Python ~

Flow of sending an email

Create and send MIME

It's really easy.

When the above flow is disassembled, three steps are required.

  1. Compose a message using the MIMEText class
  2. Log in to gmail and send

1. Compose a message using the MIMEText class

create_msg.py


from email.mime.text import MIMEText


def create_msg(from_email, to_email):
    #The contents of the e-mail
    subject = "Today's Todo"
    message = '''
        <ul>
            <li>About MINE Text</li>
            <li>About SMTP</li>
            <li>Web technology book</li>
            <li>About MVC model</li>
        </ul>
    '''
    #Explanation 1
    msg = MIMEText(message, "html")
    msg["Subject"] = subject
    msg["To"] = to_email
    msg["From"] = from_email

    return msg

Commentary

Explanation 1

*class email.mime.text.MIMEText(_text, _subtype='plain', _charset=None, , policy=compat32) This is the argument of the MINEText class. This time, "_text" and "_subtype" are set. "_text" is set to the message you want to send this time, and since you want to display it in HTML format, "html" is passed to "_subtype".

After that, the subject, destination, and source are passed to this MIMEText class. This completes the message composition for sending.

reference

email.mine: Create email and MIME objects from scratch

2. Log in to gmail

gmail.py


    #Explanation 1
    gmail = smtplib.SMTP("smtp.gmail.com", 587)
    #For confirmation when authentication fails
    gmail.set_debuglevel(True)
    
    gmail.ehlo()
    if gmail.has_extn('STARTTLS'):
        #Switch to encrypted communication
        gmail.starttls()
    gmail.ehlo()
    #Explanation 2
    gmail.login(from_email, from_password)
    #Send email
    gmail.send_message(msg)

Commentary

Explanation 1

First, SMTP class smtplib.SMTP(host='', port=0, local_hostname=None, [timeout, ]source_address=None) Written in. SMTP Protocol Client

I'm using gmail this time, so host='smtp.gmail.com' port=587 It was made. See the Google Help below to find out where these came from. スクリーンショット 2020-03-17 11.47.29.png Google Help

Explanation 2

Then log in. You can log in with gmail.login (from_email, from_password). from_email put your email address, For from_password, enter your gmail password. There is one pitfall here.

By default, Gmail can't send mail from local Python because it reverses the source IP address and rejects the connection if the domain isn't found. For this reason, it is necessary to turn on ** "Allow access to the account from insecure apps" ** in advance from the account settings. This poses a security risk, so we recommend that you create a separate learning account.

Setting method

Go to "Security" from your Google Account (https://myaccount.google.com/) to enable access to insecure apps.

Also, the host and port number will vary depending on the provider.

Provider SMTP server name
Gmail smtp.gmail.com
Outlook.com/Hotmail.com smtp-mail.outllok.com
Yahoo Mail smtp.mail.yahoo.com
AT&T smtp.mail.att.net(port = 465)
Comcast smtp.comcast.net
Verizon smtp.verizon.net(port = 465)

Whole source code

main.py


from email.mime.text import MIMEText
import smtplib


def send_email(email):
    #Your account
    from_email="Your Gmail address"
    from_password="Password to log in to Gmail"

    #Destination
    to_email = email

    #Compose a message
    msg = create_msg(from_email, to_email)

    gmail = smtplib.SMTP("smtp.gmail.com", 587)
    #For confirmation when authentication fails
    gmail.set_debuglevel(True)
    
    gmail.ehlo()
    if gmail.has_extn('STARTTLS'):
        #Switch to encrypted communication
        gmail.starttls()
    gmail.ehlo()
    #Explanation 2
    gmail.login(from_email, from_password)
    #Send email
    gmail.send_message(msg)


def create_msg(from_email, to_email):
    #The contents of the e-mail
    subject = "Today's Todo"
    message = '''
        <ul>
            <li>About MINE Text</li>
            <li>About SMTP</li>
            <li>Web technology book</li>
            <li>About MVC model</li>
        </ul>
    '''
    #Explanation 1
    msg = MIMEText(message, "html")
    msg["Subject"] = subject
    msg["To"] = to_email
    msg["From"] = from_email

    return msg


if __name__ == '__main__':
    to_addr = 'Email address of the person you want to send'
    send_email(to_addr)

List of reference materials

Error when trying to send mail by Gmail from the program email.mine: Create email and MIME objects from scratch SMTP Protocol Client Google Help

Recommended Posts

I want to email from Gmail using Python.
I want to use jar from python
[Python] I want to manage 7DaysToDie from Discord! 1/3
I want to use ceres solver from python
[Python] I want to manage 7DaysToDie from Discord! 2/3
I want to make C ++ code from Python code!
[Python3] I want to generate harassment names from Japanese!
I want to debug with Python
I want to start a lot of processes from python
I want to send a message from Python to LINE Bot
From Python to using MeCab (and CaboCha)
I want to build a Python environment
I want to analyze logs with Python
I tried using UnityCloudBuild API from Python
I want to play with aws with python
I want to connect to PostgreSQL from various languages
I want to do Dunnett's test in Python
I want to operate DB using Django's ORM from an external application
Changes from Python 3.0 to Python 3.5
Email attachments using your gmail account in python.
I want to memoize including Python keyword arguments
I want to create a window in Python
I want to perform SageMaker inference from PHP
I want to make a game with Python
I want to visualize csv files using Vega-Lite!
[Python memo] I want to get a 2-digit hexadecimal number from a decimal number
I want to merge nested dicts in Python
I want to make fits from my head
I want to use Temporary Directory with Python2
#Unresolved I want to compile gobject-introspection with Python3
I want to solve APG4b with Python (Chapter 2)
I tried to send a registration completion email from Gmail with django.
[I want to classify images using Tensorflow] (2) Let's classify images
What I did when updating from Python 2.6 to 2.7
I want to sell Mercari by scraping python
I want to write to a file with Python
I want to display the progress in Python!
I want to make a web application using React and Python flask
I want to send Gmail with Python, but I can't because of an error
I want to get / execute variables / functions / classes of external files from Python
To automatically send an email with an attachment using the Gmail API in Python
I tried to execute Python code from .Net using Pythonnet (Hallo World edition)
I want to write in Python! (1) Code format check
I want to see the file name from DataLoader
Even beginners want to say "I fully understand Python"
I want to embed a variable in a Python string
I want to easily implement a timeout in python
I want to detect images of cats from Instagram
I want to iterate a Python generator many times
I want to generate a UUID quickly (memorandum) ~ Python ~
I want to write in Python! (2) Let's write a test
Push notifications from Python to Android using Google's API
Even in JavaScript, I want to see Python `range ()`!
MessagePack-Call Python (or Python to Ruby) methods from Ruby using RPC
I wanted to use the Python library from MATLAB
I want to randomly sample a file in Python
I want to inherit to the back with python dataclass
I want to work with a robot in python.
[Python] I want to make a nested list a tuple
I want to write in Python! (3) Utilize the mock
I want to AWS Lambda with Python on Mac!