I tried sending an email with python.

I tried sending an email with python.

This article is the 14th day article of SLP KBIT Advent Calendar 2020. This time I tried to send an email with Python. A sample source code can be found on the web. (Https://docs.python.org/ja/3/library/smtplib.html)

table of contents

·Development environment ・ Mechanism for automatic email transmission ・ Create a transmission program. ・ At the end

Development environment

・ Python3.9.0 ・ VS code

How e-mail is sent automatically

E-mail is sent from your smartphone or computer to your mail server. It is then sent from your mail server to the recipient's mail server. Then the email is received on the other device. I will not do it this time, but to send mail automatically, create a program that sends mail from your own mail server to the server. This time I will send gmail with python.

Enter the SMTP server address.

First, paste the sample code from https://docs.python.org/ja/3/library/smtplib.html into your editor.

import smtplib

def prompt(prompt):
    return input(prompt).strip()

fromaddr = prompt("From: ")
toaddrs  = prompt("To: ").split()
print("Enter message, end with ^D (Unix) or ^Z (Windows):")

# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
       % (fromaddr, ", ".join(toaddrs)))
while True:
    try:
        line = input()
    except EOFError:
        break
    if not line:
        break
    msg = msg + line

print("Message length is", len(msg))

server = smtplib.SMTP('localhost')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

The'localhost' on line 24 is the server address. Change this to'smtp.gmail.com'. Also, since you need to specify the port, enter "587" after the address you entered earlier. (I entered 587 because I am using TLS this time, but I entered 465 when using SSL.)

server = smtplib.SMTP('smtp.gmail.com', 587)

Enter the email addresses of yourself and the other party.

Enter your email address in "From" on the 6th line. Also, enter the other party's email address in "To" on the 7th line. If there is only one opponent, delete the s in "to addrs" on lines 7, 12, and 26. Also, change the 12th line as shown in the image below.

import smtplib

def prompt(prompt):
    return input(prompt).strip()

fromaddr = 'Enter your email address here.'
toaddr  = 'Enter the other party's email address here.'
print("Enter message, end with ^D (Unix) or ^Z (Windows):")

# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
       % (fromaddr, toaddr))
while True:
    try:
        line = input()
    except EOFError:
        break
    if not line:
        break
    msg = msg + line

print("Message length is", len(msg))

server = smtplib.SMTP('smtp.gmail.com', 587)

server.set_debuglevel(1)
server.sendmail(fromaddr, toaddr, msg)
server.quit()

Set a login password.

An app password is required when sending emails via an app or program. Two-step verification is required to set the app password, so set two-step verification first. Follow the steps below to enable the two-step process. 1 Open a google account 2 Select Security in the navigation panel (displayed on the left) 3 In [Login to google], select [Try it] in [Two-step authentication process]. 4 Follow the instructions on the screen and follow the steps to complete the procedure. Next, set the app password. 1 Open a google account 2 Select Security in the navigation panel 3 Click the app password 4 Follow the on-screen instructions to complete the procedure. Next, convert the 26th and subsequent lines to the code below.

server.ehlo()
server.starttls()
server.login('Enter your Gmail address', 'Enter password')

server.set_debuglevel(1)
server.sendmail(fromaddr, toaddr, msg)
server.quit()

Send email

Run the program and send an email by entering the body

At the end

This time I made a program to send an email. Next, I'll try to automate email. This article is https://www.youtube.com/watch?v=zdPDrtTrqqQ I created it with reference to.

Recommended Posts

I tried sending an email with python.
I tried sending an email with SendGrid + Python
I tried sending an email from Amazon SES with Python
I tried fp-growth with python
I tried scraping with Python
I tried sending an email from the Sakura server with flask-mail
I tried gRPC with Python
I tried scraping with python
I tried to implement an artificial perceptron with python
I tried web scraping with python.
I sent an SMS with Python
Easy email sending with haste python3
I tried running prolog with python 3.8.2.
[Python] Send an email with outlook
I tried SMTP communication with Python
I tried scraping Yahoo News with Python
I tried non-photorealistic rendering with Python + opencv
I tried a functional language with Python
I tried recursion with Python ② (Fibonacci sequence)
Send an email with Amazon SES + Python
#I tried something like Vlookup with Python # 2
I tried to make an image similarity function with Python + OpenCV
I tried Python> autopep8
Validate E-Mail with Python
Send email with Python
I tried Python> decorator
I tried "smoothing" the image with Python + OpenCV
I tried hundreds of millions of SQLite with python
Send an email to Spushi's address with python
I tried L-Chika with Raspberry Pi 4 (Python edition)
I tried Jacobian and partial differential with python
I tried to get CloudWatch data with Python
I tried using mecab with python2.7, ruby2.3, php7
I tried function synthesis and curry with python
I tried to output LLVM IR with Python
I tried "binarizing" the image with Python + OpenCV
I tried running faiss with python, Go, Rust
I tried to detect an object with M2Det!
I tried to automate sushi making with python
I tried playing mahjong with Python (single mahjong edition)
I tried running Deep Floor Plan with Python 3.6.10.
Send an email with Excel attached in Python
[Outlook] I tried to automatically create a daily report email with Python
I tried Learning-to-Rank with Elasticsearch!
I tried to implement Minesweeper on terminal with python
I tried to get started with blender python script_Part 01
I made blackjack with python!
I tried to touch the CSV file with Python
I tried to draw a route map with Python
Creating an egg with python
[OpenCV / Python] I tried image analysis of cells with OpenCV
I tried clustering with PyCaret
I tried to solve the soma cube with python
I tried to get started with blender python script_Part 02
I tried to automatically generate a password with Python3
I tried Python C extension
[Python] I tried using OpenPose
Mayungo's Python Learning Episode 1: I tried printing with print
I tried to solve the problem with Python Vol.1
I tried to analyze J League data with Python
I tried to make an OCR application with PySimpleGUI