[Python] Send gmail with python: Send one by one with multiple image files attached

Introduction

It is a summary when I was investigating because I wanted to send gmail with python. Just a memo.

Roughly the same as the reference below,

The photos in a specific directory are repeatedly read and sent.

Reference: https://qiita.com/numaC/items/076474934a3bb45647bd

Thank you for the reference site.

Contents

Conclusion

The conclusion is as follows. However, I think that in most cases you will get an "SMTPAuthenticationError". Please refer to it from the "Contents" section below.

sendmail.py


import os
import glob
from smtplib import SMTP
from email.mime.text import MIMEText
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart

def sendGmailAttach():
    sender, password = "[email protected]", "testtest" #Sender email address and login information to gmail
    to = '[email protected]'  #Destination email address
    sub = 'Sending test email' #Email subject
    body = 'The image is attached.'  #the content of the email
    host, port = 'smtp.gmail.com', 587

    #Email header
    msg = MIMEMultipart()
    msg['Subject'] = sub
    msg['From'] = sender
    msg['To'] = to

    #the content of the email
    body = MIMEText(body)
    msg.attach(body)

    #Additional part
    fetch_from_dir = glob.glob(os.getcwd() + "\img/*")
    fetch_from_dir_len = len(fetch_from_dir)
    len_cnt = 0
    for target_list in fetch_from_dir:
        print(target_list)

        #Attachment settings
        attach_file = {
            'name': os.path.basename(target_list),
            'path': target_list
        } #name is the attached file name. path specifies the location of the attachment
        attachment = MIMEBase('image', 'png')
        file = open(attach_file['path'], 'rb+')
        attachment.set_payload(file.read())
        file.close()
        encoders.encode_base64(attachment)
        attachment.add_header("Content-Disposition", "attachment", filename=attach_file['name'])
        msg.attach(attachment)

        #Connect to gmail(Used as an SMTP server)
        gmail=SMTP("smtp.gmail.com", 587)
        gmail.starttls() #Encrypt SMTP communication commands and authenticate server access
        gmail.login(sender, password)
        gmail.send_message(msg)
        len_cnt += 1
        print('Mail' + str(len_cnt) + '/' + str(fetch_from_dir_len) + 'Sent')


if __name__ == '__main__':
    sendGmailAttach()
    print('All emails have been sent')

Execution result


$ python sendmail.py
C:\Users\hogehoge\img\1.jpg
Email is 1/3 sent
C:\Users\hogehoge\img\2.jpg
Email 2/3 sent
C:\Users\hogehoge\img\3.jpg
Email 3/3 sent
All emails have been sent

Contents

About error at the time of transmission

You will probably get the following error when you run the program:

smtplib.SMTPAuthenticationError: (535, ‘5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials

This is resolved on the gmail side as "use app password".

The following is a reference site. Thank you very much.

Reference: https://www.gocca.work/python-mailerror/

I will write a rough procedure, but for details, see the reference site.

-Step 1: After logging in to your google account
-Step 2: Set up "2-step authentication process"
-Step 3: Generate "App Password"

About the program

I made a note as a method for the time being, so error handling etc. are not enough, so please take appropriate measures.

Recommended Posts

[Python] Send gmail with python: Send one by one with multiple image files attached
Sorting image files with Python (2)
Sorting image files with Python (3)
Sorting image files with Python
Send using Python with Gmail
Send image with python, save with php
Send email via gmail with Python 3.4.3.
HTML email with image to send with python
Combine multiple python files into one python file
[Python & Unix] Combine multiple PDF files into one.
Erase image files at once with one liner
Convert multiple proto files at once with python
Send an email with Excel attached in Python
Image processing with Python
Send email with Python
Send Gmail in Python
Extract the table of image files with OneDrive & Python
JPEG image generation by specifying quality with Python + OpenCV
Remove headings from multiple format CSV files with python
Combine multiple csv files into one csv file with python (assuming only one line of header)
Image processing with Python (Part 2)
Send Japanese email with Python3
[Python] Send an email from gmail with two-step verification set
Improve your productivity by processing huge Excel files with Python
Image editing with python OpenCV
Generate multiple HTML files at once by pouring JSON data into an HTML template with Python
Sort huge files with python
Image processing with Python (Part 1)
Tweet with image in Python
Integrate PDF files with Python
Image processing with Python (Part 3)
Reading .txt files with Python
Image processing by python (Pillow)
Decompress multiple compressed files (Python)
[Python] Easy reading of serial number image files with OpenCV
[Python] Image processing with scikit-image
Two ways to display multiple graphs in one image with matplotlib
Cut out an image with python
[Python] Using OpenCV with Python (Image Filtering)
[Python] Sort iterable by multiple conditions
Recursively unzip zip files with python
Manipulating EAGLE .brd files with Python
[Python] Using OpenCV with Python (Image transformation)
[Automation] Send Outlook email with Python
Load multiple JavaScript files with PyWebView
[Python] POST wav files with requests [POST]
Decrypt files encrypted with OpenSSL with Python 3
Image processing with Python 100 knocks # 3 Binarization
Post multiple Twitter images with python
Animate multiple still images with Python
Let's do image scraping with Python
Handle Excel CSV files with Python
Read files in parallel with Python
Find image similarity with Python + OpenCV
Multiple integrals with Python and Sympy
Image processing with Python 100 knocks # 2 Grayscale
[Python] Send an email with outlook
[Python] Creating multiple windows with Tkinter
Send multipart / form-data with python requests
Easily send emails with Gmail with Django
[Python] Create API to send Gmail