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.
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.
I found out that imaplib, a package for sending emails with Python, can also attach files, so I decided to use it.
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. ..
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.
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.
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
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
Write the following in .m using the system function.
system('Want to run.py path')
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 |
We welcome your suggestions, suggestions for improvement, and suggestions for mistakes. I'm glad if you can do it.