I tried to make it possible to automatically send an email just by double-clicking the [Python] icon

Synopsis

I decided to automate it because it is troublesome to send emails on a regular basis.

For automation, we decided to create one that meets the following requirements.

    1. I want to attach a specific file automatically
  1. I want to upload files attached to emails to Google Drive at the same time
    1. I want to go online only when sending an email and go offline immediately after sending

So I decided to make a tool in Python that meets the above requirements.

First of all, I considered whether the above three requirements were really realized.

Requirement 1: I want to attach a specific file automatically

I found out that imaplib, a package for sending emails with Python, can also attach files, so I decided to use it.

Requirement 2: I want to upload files attached to emails to Google Drive at the same time

After investigating this, I found that there is a package called PyDrive that operates Google Drive from Python, so I decided to use it. Python is too convenient. ..

Requirement 3: I want to go online only when sending an email and go offline immediately after sending

I thought about Python as a package that can easily connect / disconnect Wi-Fi, but unfortunately I couldn't find it.

However, I found that PowserShell makes it easy to operate Wi-Fi, and that PowerShell scripts can also be called easily from the Python side, so I decided to perform Wi-Fi operation with PowerShell.

Implementation results

Put the created Python script and PowerShell script in the appropriate place, put the .py shortcut on the desktop and hit it to execute automatic mail sending. For reference, the implementation results are as follows.

キャプチャ.JPG

Source

    1. Python: main part

auto_mail_tool.py


import os
import time
import email
import imaplib
import smtplib
import datetime
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from os.path import basename
from email.header import Header
from email.utils import formatdate
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication


#Connect to wifi/Disconnect
def wifi(mode):

    if mode == 'connect':  #Connect to wifi of specified SSID (SSID itself is set in PowerShell)
        os.system('powershell -Command' + ' ' + \
                  'powershell -ExecutionPolicy RemoteSigned .\\wifi_on.ps1')

        time.sleep(5)

    elif mode == 'disconnect':  #Disconnect from connected wifi

        os.system('powershell -Command' + ' ' + \
                  'powershell -ExecutionPolicy RemoteSigned .\\wifi_off.ps1')


#Upload the file you want to attach to the outgoing email to Google Drive
def up_file_on_drive():

    print('I'm uploading a file to Google Drive.')

    #Set the path and file name where the file to be uploaded is located
    tgtfolder = 'File path (not including file name)'
    tgtfile = 'The name of the file you want to upload'
    dlttgt = 'title = ' + '"' + tgtfile + '"'  #Used to get the file ID

    #Authentication process for using Google Drive API
    gauth = GoogleAuth()
    drive = GoogleDrive(gauth)

    #If a file with the same name is already stored, delete it
    file_id = drive.ListFile({'q': dlttgt}).GetList()[0]['id']
    f = drive.CreateFile({'id': file_id})
    f.Delete()

    time.sleep(3)

    #Upload file
    folder_id = '1kCwhAtoPIi2TAUK0wiAr9ecYifyve7TW'
    f = drive.CreateFile({'title': tgtfile,
                         'mimeType': 'excel/xlsx',
                         'parents': [{'kind': 'drive#fileLink', 'id': folder_id}]})
    f.SetContentFile(tgtfolder + tgtfile)
    f.Upload()

    print('The file upload is complete.')


#Send email with attachment
def send_mail_with_file():

    st = get_mail_settings()  #Get the contents of sent mail

    #Set the content of the email to be sent
    msg = MIMEMultipart()
    msg["Subject"] = st['subject']
    msg["To"] = st['to_addr']
    msg["From"] = u'%s<%s>' % (str(Header(st['send_name'].encode(st['charset']), st['charset'])), st['from_addr'])
    msg['Bcc'] = st['bcc_addr']
    msg['Date'] = formatdate()
    msg.attach(MIMEText(st['body']))

    #Attach file
    with open(st['file'], "rb") as f:
        part = MIMEApplication(f.read(), Name=basename(st['file']))
    part['attached_file'] = 'attachment; filename="%s"' % basename(st['file'])
    msg.attach(part)

    #Send email
    smtpobj = smtplib.SMTP_SSL('smtp.gmail.com', 465, timeout=10)  #Specify the port number of Gmail's SMTP server
    smtpobj.login(st['from_addr'], st['mypass'])
    smtpobj.send_message(msg=msg)
    smtpobj.close()


#Get email settings
def get_mail_settings():
    info = {
        'charset': 'iso-2022-jp',
        'send_name': u'Sender's name',
        'from_addr': 'Sender's address',
        'mypass': 'Gmail account password',
        'bcc_addr': 'Destination 1,Destination 2',
        'to_addr': 'Destination 1,Destination 2',
        'subject': 'Email subject' + get_today(),
        'body': 'the content of the email',
        'file': 'The path of the file you want to attach+file name'
    }
    return info


#Check if the email was sent
def confirm_mail_sent():

    print('I am sending an email.')

    st = get_mail_settings()  #Get the contents of sent mail

    tgtac = imaplib.IMAP4_SSL('imap.gmail.com', 993)  #gmail Incoming mail server (IMAP) host name and port number for receiving mail using SSL
    tgtac.login(st['from_addr'], st['mypass'])

    waitsec = 10  #Email transmission confirmation logic timeout time[sec]

    #Check from the latest email every second to see if the automatically sent email is received
    for i in range(waitsec, 0, -1):

        lamtitle = get_latest_mail_title(tgtac)  #Get the subject of the latest email

        time.sleep(1)  #1 loop 1 second

        if lamtitle == st['subject']:  #If the subject of the latest email is that of an automatically sent email
            print('\n Automatic mail transmission is complete.\n')
            return

    #If the confirmation time times out
    print('\n Failed to send mail automatically.\n')


#Get the subject of the latest email
def get_latest_mail_title(mail):
    mail.select('inbox')  #Mailbox selection
    data = mail.search(None, 'ALL')[1]  #Get all the data in your mailbox
    tgt = data[0].split()[-1]  #Get the latest mail order
    x = mail.fetch(tgt, 'RFC822')[1]  #Get email information (specify a standard that can be read by Gmail)
    ms = email.message_from_string(x[0][1].decode('iso-2022-jp'))  #Perspective and get

    sb = email.header.decode_header(ms.get('Subject'))
    ms_code = sb[0][1]  #Character code acquisition

    #Get only the subject of the latest email
    if ms_code != None:
        mtitle = sb[0][0].decode(ms_code)
    else:
        mtitle = sb[0][0]

    return mtitle


#Get today's date
def get_today():
    now = datetime.date.today()
    tdy = str(now.year) + '/' + str(now.month) + '/' + str(now.day)  #Display by date
    wknum = now.weekday()  #Get today's day number (0):Month... 6:Day)
    wk = get_now_weekday(wknum)  #Get today's day

    return tdy + '(' + wk + ')'


#Get today's day
def get_now_weekday(key):
    wkdict = {0: 'Month', 1: 'fire', 2: 'water', 3: 'wood', 4: 'Money', 5: 'soil', 6: 'Day'}
    return (wkdict[key])


if __name__ == '__main__':

    wifi('connect')        # 1.Connect wifi with specified SSID
    up_file_on_drive()     # 2.Upload the file you want to attach to Google Drive once
    send_mail_with_file()  # 3.Send an email with a file attached
    confirm_mail_sent()    # 4.Check if the email sent by GAS has arrived
    wifi('disconnect')     # 5.Connect wifi with specified SSID

    os.system('PAUSE')     #Stop the console

  1. PowerShell: For Wi-Fi connection / disconnection

2-1. When connecting

wifi_on.ps1


netsh wlan connect name="Wi-fi you want to connect to-Fi SSID"

2-2. At the time of disconnection

wifi_off.ps1


netsh wlan disconnect

Remarks: If you want to call .py from MATLAB

Write the following in .m using the system function.

system('Want to run.py path')

Information that was used as a reference

In particular, I was indebted to the following sites. Thank you very much.

Contents Link destination
Upload files to Google Drive with PyDrive https://note.nkmk.me/python-pydrive-download-upload-delete/ https://qiita.com/akabei/items/f25e4f79dd7c2f754f0e
PowerShell script from Python (.ps1) call https://tkstock.site/2019/10/07/python-powershell-shellscript-activate/
Connecting / disconnecting to wifi by PowerShell https://qiita.com/mindwood/items/22e0895473578c4e0c7e http://wgg.hatenablog.jp/entry/20161111/1478846489
Delete files on Google Drive https://note.nkmk.me/python-pydrive-download-upload-delete/
Get Gmail incoming email information with imaplib https://py.minitukuc.com/2017/11/07/gmailhonbun/
Hide root window when using Tkinter dialog https://stackoverflow.com/questions/1406145/how-do-i-get-rid-of-python-tkinter-root-window
Send Gmail with Python https://qiita.com/nakasuke_/items/607cf74d8841f76e59c6
Attach file when sending Gmail with Python https://time-space.kddi.com/ict-keywords/kaisetsu/20170824/2081
Set the sender's name when sending Gmail in Python https://teratail.com/questions/128993

last

We welcome your suggestions, suggestions for improvement, and suggestions for mistakes. I'm glad if you can do it.

Recommended Posts

I tried to make it possible to automatically send an email just by double-clicking the [Python] icon
I tried to make it possible to automatically send an email just by double-clicking the [GAS / Python] icon
Output the report as PDF from DB with Python and automatically attach it to an email and send it
To automatically send an email with an attachment using the Gmail API in Python
I tried to automatically send the literature of the new coronavirus to LINE with Python
[Python] Simple Japanese ⇒ I tried to make an English translation tool
I tried to make an image similarity function with Python + OpenCV
I tried sending an email with python.
Python: I tried to make a flat / flat_map just right with a generator
[Python] I tried to summarize the set type (set) in an easy-to-understand manner.
When I tried to run Python, it was skipped to the Microsoft Store
I tried to verify and analyze the acceleration of Python by Cython
[Outlook] I tried to automatically create a daily report email with Python
[Zaif] I tried to make it easy to trade virtual currencies with Python
I tried to analyze the New Year's card by myself using python
I tried to make a system to automatically acquire the program guide → register it in the calendar in one day
I tried to get an image by scraping
Send an email to Spushi's address with python
I tried using the Datetime module by Python
I tried sending an email with SendGrid + Python
I tried to rescue the data of the laptop by booting it on Ubuntu
I tried my best to make an optimization function, but it didn't work.
I tried to make the weather forecast on the official line by referring to the weather forecast bot of "Dialogue system made with python".
I tried to graph the packages installed in Python
[Introduction] I tried to implement it by myself while explaining the binary search tree.
I tried to make an automatic character dialogue generator by N floor Markov chain
I tried to make the phone ring when it was posted at the IoT post
I tried to touch the CSV file with Python
A python beginner tried to intern at an IT company [Day 3: Going to the clouds ...]
I tried to solve the soma cube with python
Continuation ・ I tried to make Slackbot after studying Python3
I tried to implement an artificial perceptron with python
[Python] I tried to graph the top 10 eyeshadow rankings
I tried to automatically generate a password with Python3
A Python beginner made a chat bot, so I tried to summarize how to make it.
I tried to solve the problem with Python Vol.1
I want to send a business start email automatically
[Introduction] I tried to implement it by myself while explaining to understand the binary tree
I tried to make an OCR application with PySimpleGUI
I made an action to automatically format python code
I tried to make it easy to change the setting of authenticated Proxy on Jupyter
I tried to summarize the string operations of Python
[Python] I tried to make an application that calculates salary according to working hours with tkinter
I tried to create a RESTful API by connecting the explosive Python framework FastAPI to MySQL.
I tried it with SymPyLive by referring to "[Ruby] Getting unique elements from an array".
I tried to make the political broadcast video like IPPON Grand Prix (OpenCV: Python version)
I tried to find the entropy of the image with python
I tried to simulate how the infection spreads with Python
I tried various methods to send Japanese mail with Python
I tried sending an email from Amazon SES with Python
Code to send an email based on the Excel email list
[Python] I tried to visualize the follow relationship of Twitter
I tried to implement the mail sending function in Python
I tried to enumerate the differences between java and python
I tried to make a stopwatch using tkinter in python
I tried to make GUI tic-tac-toe with Python and Tkinter
I tried changing the python script from 2.7.11 to 3.6.0 on windows10
A python beginner tried to intern at an IT company
I tried to divide the file into folders with Python
I tried to make a site that makes it easy to see the update information of Azure
I tried to make an image classification BOT by combining TensorFlow Lite and LINE Messaging API