Office automation: 1. Automatic document processing & batch mail processing

1. Automatic document processing

1.1 reading and writing documents

How to use python to create, read and save files on the hard disk.

1.1.1 file and file path

Two attributes of a file: path and file name.

Path: location of the file on the computer ------ D:\datawhale

File name: refers to the name of the file in this location----- "First quarter sales table"

Note: folder names and file names in Windows are not case sensitive.

On windows, path writing uses the backslash '/' as the separator between folders, while on OS X and Linux, it uses the forward slash '/' as their path separator.

  • Usually we use OS path. Join() function to create a file name string.
import os
os.path.join('Datawhale','docu')
'Datawhale\\docu'

Here are two slashes, one of which is used to escape, because it is on windows system. If this function is called on OS X or Linux, the result is' Datawhale/docu '.

1.1.2 current working directory

Using OS Getcwd() function can obtain the string of the current working path and use OS Chdir () changes it.

import os
os.getcwd()          #Get current working directory
'D:\\study\\Datawhale\\Office automation-OfficeAutomation'
# If you want to change the current working directory, you can change it directly, provided that you need to establish the corresponding working directory in advance

os.chdir('D:\\study\\Datawhale\\Office automation-OfficeAutomation\\python office automation ')          #Change current working directory
os.getcwd() 
'D:\\study\\Datawhale\\Office automation-OfficeAutomation\\python office automation '

1.1.3 path operation

1.1.3.1 absolute path and relative path

  • "Absolute path" always starts from the root folder.

  • "Relative path", relative to the current working directory of the program.

In a relative path, a single period "." Represents the abbreviation of the current directory, and the two periods "..." represent the parent folder.

Several commonly used absolute path and relative path processing functions

os.path.abspath(path): converts a relative path to an absolute path, and returns the string of the absolute path of the parameter.

os.path.isabs(path): judge whether it is an absolute path. If it is True, it returns False

os.path.abspath('.')   
#Convert current path to absolute path. 
'D:\\study\\Datawhale\\Office automation-OfficeAutomation\\python office automation '
os.path.isabs('.')        
False
os.path.isabs(os.path.abspath('.')) 
True

1.1.3.2 path operation

os.path.relpath(path,start): returns the string of the relative path from the start path to the path. If start is not provided, use the current working directory as the start path.

os.path.dirname(path): returns the directory name of the current path.

os.path.basename(path): returns the file name of the current path.

os.path.relpath('D:\\Datawhale\\python office automation ','D:\\')    
'Datawhale\\python office automation '
path = 'D:\\Datawhale\\python office automation \\First quarter sales statement.xlsx'  
os.path.dirname(path)     
'D:\\Datawhale\\python office automation '
os.path.basename(path)
'First quarter sales statement.xlsx'

If you need the directory name and basic name of a path at the same time, you can call OS path. Split(), get the tuple of two strings.

caFilePath = 'D:\\Datawhale\\python office automation \\First quarter sales statement.xlsx'
os.path.split(caFilePath) 
('D:\\Datawhale\\python office automation ', 'First quarter sales statement.xlsx')

We can also call OS path. Dirname() and OS path. Basename(), put their return values in a tuple to get the same tuple.

(os.path.dirname(caFilePath),os.path.basename(caFilePath))
('D:\\Datawhale\\python office automation ', 'First quarter sales statement.xlsx')

If we want to return a list of strings for each folder. Use OS path. split() cannot be obtained. We can use the split() string method, and according to OS path. The string in SEP is divided. os. path. Set the SEP variable to the correct folder split slash.

caFilePath.split(os.path.sep)
['D:', 'Datawhale', 'python office automation ', 'First quarter sales statement.xlsx']

1.1.3.3 path validity check

If the path provided does not exist, many Python functions will crash and report errors. os. The path module provides some functions to detect whether a given path exists and whether it is a folder or a file.

os.path.exists(path): returns True if the file or folder referred to by the path parameter exists; otherwise, returns False.

os.path.isfile(path): if the path parameter exists and is a file, it returns True; otherwise, it returns False.

os.path.isdir(path): returns True if the path parameter exists and is a folder; otherwise, returns False.

os.path.exists('C:\\Windows')
True
os.path.exists('C:\\else')
False
os.path.isfile('D:\\Datawhale\\python office automation \\First quarter sales statement.xlsx')
False
os.path.isfile('D:\\Datawhale\\python office automation ')
False
os.path.isdir('D:\\Datawhale\\python office automation \First quarter sales statement.xlsx')
False
os.path.isdir('D:\\Datawhale\\python office automation ')
False

1.1.4 document and folder operation

1.1.4.1 OS Makedirs() creates a new folder

Note: OS Makedirs () can create all the necessary intermediate folders.

import os
os.makedirs('D:\\Datawhale\\practice')  

#View the directory. It has been created. If the folder already exists, it will not be overwritten and an error will be reported

1.1.4.2 view file size and folder content

We can already handle file paths, which is the basis for operating files and folders. Next, we can collect information about specific files and folders. os. The path module provides functions to view the number of bytes of a file and the files and subfolders in a given folder.
os.path.getsize(path): returns the number of bytes of the file in the path parameter.
os. List dir (path): returns a list of file name strings, including each file in the path parameter.

os.path.getsize(r'D:\study\Datawhale\Office automation-OfficeAutomation\readme.md')
2234
os.listdir('D:\study\Datawhale\Office automation-OfficeAutomation')
['.ipynb_checkpoints',
 'python office automation ',
 'readme.md',
 'Task01 Automatic file processing&Mail batch processing.md',
 'Task02 Python And Excel.md',
 'Task03 python And word.md',
 'Task04 Python operation PDF.md',
 'Task05 Introduction and comprehensive application of reptiles.md',
 'picture',
 'Office automation: 1. Automatic document processing&Mail batch processing.ipynb']

If you want to know the total number of bytes of all files in the directory, you can use OS path. GetSize () and OS listdir()

totalSize = 0
for filename in os.listdir('D:\study\Datawhale\Office automation-OfficeAutomation'):
    totalSize = totalSize + os.path.getsize(os.path.join('D:\study\Datawhale\Office automation-OfficeAutomation',filename))
print(totalSize)
141980

1.1.6 document reading and writing process

There are three steps to read and write files:

1. Call the open() function to return a File object.

2. Call the read() or write() method of the File object.

3. Call the close() method of the File object to close the File.

1.1.6.1 open the file with the open() function

To open a File with the open () function, you pass it a string path indicating the File you want to open. This can be either an absolute path or a relative path. The open() function returns a File object.
First use TextEdit to create a text file called hello txt. Enter Hello World! As the content of the text file, save it in your users folder.

helloFile = open(r'D:\study\Datawhale\Office automation-OfficeAutomation\hello.txt',encoding = 'utf-8')
print(helloFile)
<_io.TextIOWrapper name='D:\\study\\Datawhale\\Office automation-OfficeAutomation\\hello.txt' mode='r' encoding='utf-8'>

As you can see, calling the open() function will return a File object. When you need to read or write the File, you can call the method of the File object in the helloFile variable.

1.1.6.2 reading file contents

With the File object, we can start reading from it.

read(): read the contents of the file.

readlines(): read the contents of the file by line and get a list of strings. Each string in the list is a line in the text and ends with \ n.

helloContent = helloFile.read()
helloContent
'hello world !'
sonnetFile = open(r'D:\study\Datawhale\Office automation-OfficeAutomation\hello.txt',encoding = 'utf-8')
sonnetFile.readlines()
['hello world !\n', 'hello Python. ']

1.1.6.3 write file

A file needs to be opened in write mode 'w' and add mode 'a', but not in read mode.

"Write mode": overwrite the original file and start from scratch.

"Add mode": text will be added at the end of existing files.

baconFile = open('bacon.txt','w')
baconFile.write('Hello world!\n')
# The "bacon" file name is automatically created in the current directory. The written data has not been synchronized. You need to perform the following operations to see the content
13
baconFile.close()  
#Note that the writing can be completed only after closing, and the written contents can be seen from the txt file.
baconFile = open('bacon.txt','a')
baconFile.write('Bacon is not a vegetable.')
baconFile.close() 
# A new line of data has been added to bacon Notepad
baconFile = open('bacon.txt')
content = baconFile.read()
baconFile.close()
print(content)
Hello world!
Bacon is not a vegetable.Bacon is not a vegetable.

Note that the write() method does not automatically add a newline character to the end of the string, as the print() function does. You must add this character yourself.

1.1.6.3 saving variables

1) , shelve module

With the shell module, you can save variables in Python to binary shell files. In this way, the program can recover the variable data from the hard disk.

import shelve
shelfFile = shelve.open('mydata')
cats = ['Zonphie','Pooka','Simon']
shelfFile['cats'] = cats
shelfFile.close()

Running the previous code on Windows, we will see three new files in the current working directory: mydata bak,mydata.dat and mydata dir. On OS X, only one mydata will be created DB file.

Reopen these files and take out the data. Note: the shelf value does not have to be turned on in read mode or write mode, because when turned on, it can be read and written.

shelfFile = shelve.open('mydata')
type(shelfFile)
shelve.DbfilenameShelf
shelve.DbfilenameShelf
shelve.DbfilenameShelf
shelfFile['cats']
['Zonphie', 'Pooka', 'Simon']
shelfFile.close()

Like a dictionary, the shelf value has keys() and values() methods that return a list like value of the keys and values in the shelf. However, these methods return values similar to lists, but they are not real lists, so they should be passed to the list() function to obtain the form of lists.

shelfFile = shelve.open('mydata')
list(shelfFile.keys())
['cats']
list(shelfFile.values())
[['Zonphie', 'Pooka', 'Simon']]
shelfFile.close()

2) . use pprint The pformat() function holds variables

pprint. The pformat () function returns a text string of what you want to print, which is both easy to read and syntactically correct Python code.

If there is a dictionary stored in a variable, you want to save this variable and its contents for future use. pprint. The pformat () function will provide a string that we can write to py file. This file can become our own module. If you need to use the variables stored in it, you can import it.

import  pprint
cats = [{'name':'Zophie','desc':'chubby'},{'name':'Pooka','desc':'fluffy'}]
pprint.pformat(cats)
"[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]"
fileObj = open('myCats.py','w')
fileObj.write('cats = '+pprint.pformat(cats)+'\n')
83
fileObj.close()

The module imported by the import statement itself is a Python script. If from pprint The string of pformat() is saved as a py file, which is a module that can be imported.

import myCats
myCats.cats
[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'name': 'Pooka'}]
myCats.cats[0]
{'desc': 'chubby', 'name': 'Zophie'}
myCats.cats[0]['name']
'Zophie'

1.1.7 practice

1. What happens if an existing file is opened in write mode?

A: it is written in the form of addition.

2. What is the difference between the read() and readlines() methods?

Answer: readlines,Read all lines of the whole file and save them in a list(list)Variable, each line is regarded as an element, but reading a large file will occupy more memory;

   read:Read from the current location of the file size Bytes, if no parameter size,It means that it is read to the end of the file, and its range is string object.

3. Comprehensive exercise:
1, Generate random test paper files
If you are a geography teacher with 35 students in your class, you want to take a quiz in the capitals of the United States. Unfortunately, there are some bad guys in the class. You can't be sure that students won't cheat. You want to randomly order the questions so that each test paper is unique, so that no one can copy the answers from others. Of course, doing it by hand is time-consuming and boring. Fortunately, you know some Python.

Here's what the program does:

• create 35 different test papers.

• create 50 multiple-choice questions for each test paper in random order.

• provide one correct answer and three random wrong answers for each question in random order.

• write the test paper into 35 text files.

• write answers to 35 text files.

This means that the code needs to do the following:

• keep the States and their capitals in a dictionary.

• for test text files and answer text files, call open(), write() and close().

• leverage random Shuffle () randomly adjusts the order of problems and multiple options.

1.2 organization documents

How to use programs to organize existing files on the hard disk. I wonder if you have experienced searching a folder with dozens, hundreds or even thousands of files that need to be copied, renamed, moved or compressed manually. For example, the following tasks:

• copy all pdf files (and only pdf files) in one folder and all its subfolders

• for all files in a folder, delete the leading zero in the file name. There are hundreds of files in the folder named spam001 txt, spam002.txt, spam003.txt, etc.

• compress the contents of several folders into a ZIP file (this may be a simple backup system)

All this boring task is asking for automation in Python. By programming your computer to accomplish these tasks, you turn it into a fast-working document clerk who never makes mistakes.

1.2.1 shutil module

The shutil (or shell tool) module contains functions that can copy, move, rename, and delete files in Python programs: import shutil

1.2.1.1 copy files and folders (corresponding folder names must be established)

shutil.copy(source, destination): copy the file at the path source to the folder at the path destination (both source and destination are strings), and return the absolute path string of the newly copied file.

Where destination can be:

1) . the name of a file, copy the source file as the destination of the new name

2) , a folder, copy the source file to destination

3) If this folder does not exist, copy the contents of the source target file to the destination. If the destination folder does not exist, the file will be automatically generated. (use with caution, because the source file will be copied to a file named destination without extension, which is often not what we want)

import shutil
shutil.copy(r'D:\study\Datawhale\Office automation-OfficeAutomation\python office automation \bacon.txt', 'D:\\study\\Datawhale\\Office automation-OfficeAutomation\\practice')
'D:\\study\\Datawhale\\Office automation-OfficeAutomation\\practice\\bacon.txt'
os.getcwd()
'D:\\study\\Datawhale\\Office automation-OfficeAutomation\\python office automation '
shutil.copy(r'D:\study\Datawhale\Office automation-OfficeAutomation\python office automation \capitalsquiz_answers1.txt', 'D:\\study\\Datawhale\\Office automation-OfficeAutomation\\practice\\bacon.txt')
'D:\\study\\Datawhale\\Office automation-OfficeAutomation\\practice\\bacon.txt'
shutil.copy(r'D:\study\Datawhale\Office automation-OfficeAutomation\python office automation \bacon.txt', 'D:\\study\\Datawhale\\Office automation-OfficeAutomation\\exercise')
'D:\\study\\Datawhale\\Office automation-OfficeAutomation\\exercise'

shutil.copytree(source, destination): copy the folder at the path source, including its contained folders and files, to the folder at the path destination, and return the absolute path string of the new copied folder.

Note: the folder at destination is a newly created folder. If it already exists, an error will be reported

import shutil

# Do not have the corresponding exercise folder name below. It will be created automatically.

shutil.copytree(r'D:\study\Datawhale\Office automation-OfficeAutomation','D:\\study\\Datawhale\\Office automation-OfficeAutomation\\exercise')
'D:\\study\\Datawhale\\Office automation-OfficeAutomation\\exercise'

1.2.1.2 movement and renaming of files and folders

shutil.move(source, destination): move the file / folder at the path source to the path destination, and return the string of the absolute path of the new location.

1) . if source and destination are folders and destination already exists, all contents under the source folder will be copied to the destination folder. move

2) If source is a folder and destination does not exist, all contents under the source folder will be copied to the destination folder, and the original folder name of source will be replaced with the name of destination folder. Move + rename

3) . if source and destination are files, the file at source will be moved to the location at destination and named with the file name at destination. Move + rename.

Note: if a file with the same name already exists in the destination, it will be overwritten after moving, so you should pay special attention.

import shutil
shutil.move(r'D:\study\Datawhale\Office automation-OfficeAutomation\practice','D:\\study\\Datawhale\\Office automation-OfficeAutomation\\docu')
'D:\\study\\Datawhale\\Office automation-OfficeAutomation\\docu'
shutil.move('D:\study\Datawhale\Office automation-OfficeAutomation\exercise\practice','D:\\study\\Datawhale\\Office automation-OfficeAutomation\\docueeeeee')
'D:\\study\\Datawhale\\Office automation-OfficeAutomation\\docueeeeee'
shutil.move(r'D:\study\Datawhale\Office automation-OfficeAutomation\docueeeeee\bacon.txt','D:\study\Datawhale\Office automation-OfficeAutomation\docu\egg.txt')
'D:\\study\\Datawhale\\Office automation-OfficeAutomation\\docu\\egg.txt'

1.2.1.3 permanently delete files and folders

os.unlink(path): delete the file at path.

os.rmdir(path): delete the folder at path. The folder must be empty and there are no files or folders in it.

shutil.rmtree(path): delete the folder at path, and all the files and folders it contains will be deleted.

Note: when using, you need to be very careful to avoid deleting wrong files. Generally, when running for the first time, comment out these programs and add the print() function to help check whether they are the files you want to delete.

#It is recommended to specify the folder of the operation first and view it
os.chdir('D:\study\Datawhale\Office automation-OfficeAutomation\docueeeeee')
os.getcwd()
'D:\\study\\Datawhale\\Office automation-OfficeAutomation\\docueeeeee'
import os
for filename in os.listdir():
    if filename.endswith('.dir'):
        #os.unlink(filename)
        print(filename)

1.2.1.4 safely delete with send2trash module

shutil.rmtree(path) will delete files and folders irrecoverably, which will be dangerous to use. Therefore, using a third-party send2trash module, you can send files or folders to the computer's dustbin or recycle bin instead of permanently deleting them. Some things you don't want deleted by send2trash due to program defects can be recovered from the dustbin later.

Note: when using, you need to be very careful to avoid deleting wrong files. Generally, when running for the first time, comment out these programs and add the print() function to help check whether they are the files you want to delete.

Install the module, pip install send2trash

import send2trash
send2trash.send2trash('bacon.txt')

1.2.2 traversing the directory tree

os.walk(path): pass in the path of a folder, and use OS. Net in the for loop statement The walk () function traverses the directory tree, which is similar to the range() function traversing a range of numbers. The difference is that OS Walk() returns three values in each iteration of the loop:

1) String of the current folder name.

2) , list of strings of subfolders in the current folder.

3) , list of strings of files in the current folder.

Note: the current folder refers to the folder of the current iteration of the for loop. The current working directory of the program will not be changed because of OS Change with walk ().

Create corresponding files according to the following directory tree.

import os
for folderName, subFolders,fileNames in os.walk('D:\\animals'):
    print('The current folder is ' + folderName)
    for subFolder in subFolders:
        print('Subfolder of '  + folderName+':'+subFolder)
    for filename in fileNames:
        print('File Inside '  + folderName+':'+filename)
    print('')   
The current folder is D:\animals
Subfolder of D:\animals:cats
Subfolder of D:\animals:dogs
File Inside D:\animals:Miki.txt

The current folder is D:\animals\cats
File Inside D:\animals\cats:catNames.txt
File Inside D:\animals\cats:zophie.jpg

The current folder is D:\animals\dogs
Subfolder of D:\animals\dogs:wolf

The current folder is D:\animals\dogs\wolf
File Inside D:\animals\dogs\wolf:Taidi.txt

1.2.3 compress files with zipfile module

To facilitate transmission, files are often packaged into ZIP format file. Using the functions in the zipfile module, Python programs can create and open (or unzip) zip files.

1.2.3.1 create and add to zip file

Compress the animals folder in the above section. Create an example zip and add files to it.

zipfile. Zipfile ('filename. Zip ',' W '): creates a compressed file in write mode

Write ('filename ',' compress_type = ZipFile. Zip_flattened ') method of ZipFile object: if a path is passed into the write() method, Python will compress the file indicated by the path and add it to the zip file. If you pass a string into the write () method, it represents the file name to be added. The second parameter is the "compression type" parameter, which tells the computer how to compress the file. You can always set this value to ZipFile ZIP_ Deflated (this specifies the deflate compression algorithm, which is effective for all types of data).

Note: write mode erases all the original contents of the ZIP file. If you only want to add the file to the original ZIP file, add it to zipfile Zipfile() passes in 'a' as the second parameter to open the ZIP file in add mode.

## 1 create a new Zip zip the file and add files to it
import zipfile
newZip = zipfile.ZipFile('new.zip','w')
newZip.write(r'D:\animals\Miki.txt',compress_type=zipfile.ZIP_DEFLATED)
newZip.close()
newZip = zipfile.ZipFile('new.zip','w')
newZip.write('D:\\animals\\dogs\\wolf\\Taidi.txt',compress_type=zipfile.ZIP_DEFLATED)
newZip.close()
## 2 create an example Zip file to compress all files in the animals folder.
import zipfile
import os
newZip = zipfile.ZipFile('example.zip','w')
for folderName, subFolders,fileNames in os.walk('D:\\animals'):
    for filename in fileNames:
        newZip.write(os.path.join(folderName,filename),compress_type=zipfile.ZIP_DEFLATED)
newZip.close()

1.2.3.2 read zip file

Call ZipFile The ZipFile (filename) function creates a ZipFile object (note the uppercase letters Z and F). Filename is the file name of the zip file to be read.

Two common methods in ZipFile objects:

The namelis() method returns a string list of all files and folders contained in the zip file.

getinfo() method returns a ZipInfo object about a specific file.

Two properties of ZipInfo object: file_size and compress_size indicates the original file size and the compressed file size respectively. 1.2.3.2 read zip file

import zipfile,os
exampleZip = zipfile.ZipFile('example.zip')
exampleZip.namelist()
['animals/Miki.txt',
 'animals/cats/catNames.txt',
 'animals/cats/zophie.jpg',
 'animals/dogs/wolf/Taidi.txt']
catInfo = exampleZip.getinfo('animals/Miki.txt')
catInfo.file_size
0
catInfo.compress_size
2
print('Compressed file is %s x smaller!' %(round(catInfo.file_size/catInfo.compress_size,2)))
Compressed file is 0.0 x smaller!
exampleZip.close()

1.2.3.3 extract from zip file

extractall() method of ZipFile object: extract all files and folders from the zip file and put them into the current working directory. You can also pass a folder name to extractall(), which decompresses the files to that folder instead of the current working directory. If the passed folder name does not exist, it will be created.

extract() method of ZipFile object: extract a single file from the zip file. You can also pass the second parameter to extract() to extract the file to the specified folder instead of the current working directory. If the folder specified by the second parameter does not exist, Python creates it. The return value of extract() is the absolute path of the compressed file.

import zipfile, os
exampleZip = zipfile.ZipFile('example.zip')
exampleZip.extractall('.\zip')
exampleZip.close()
exampleZip = zipfile.ZipFile('example.zip')
exampleZip.extract('animals/Miki.txt')
exampleZip.extract('animals/Miki.txt', 'D:\\animals\\folders')
exampleZip.close()

1.2.4 practice

1) Write a program to traverse a directory tree and find files with specific extensions (such as. pdf or. jpg). Wherever these files are located, copy them to a new folder.

2) It is not uncommon for some unnecessary and huge files or folders to occupy the space of the hard disk. If you're trying to free up space on your computer, it's best to delete unwanted large files. But first you have to find them. Write a program to traverse a directory tree and find particularly large files or folders, for example, files over 100MB (recall that to get the size of the file, you can use os.path.getsize()) of the os module). Print the absolute path of these files to the screen.

3) Write a program to find all files with specified prefix in a folder, such as spam001 txt,spam002. Txt, etc., and locate the missing number (for example, spam001.txt and spam003.txt exist, but spam002.txt does not exist). Let the program rename all subsequent documents and eliminate missing numbers. As an additional challenge, write another program to leave some numbers in some continuously numbered documents in order to add new documents.

2 send Email automatically

Using Python to realize automatic mail sending can let you get rid of cumbersome repetitive business and save a lot of time.

Python has two built-in libraries: SMTP lib and email, which can realize the mail function. SMTP lib library is responsible for sending mail, and email library is responsible for constructing mail format and content.

Mail sending needs to comply with the SMTP protocol. Python has built-in support for SMTP. It can send plain text mail, HTML mail and mail with attachments.

#1. Import relevant libraries and methods first
import smtplib  #Import library
from smtplib import SMTP_SSL  #Encrypt the email content to prevent it from being intercepted halfway
from email.mime.text import  MIMEText   #Construct the body of the message
from email.mime.image import MIMEImage  #Picture of construction mail
from email.mime.multipart import MIMEMultipart   #Put all parts of the mail together, the main body of the mail
from email.header import Header   #Header, title, recipient of the message
#2. Set mailbox domain name, sender's mailbox, mailbox authorization code and recipient's mailbox
host_server = 'smtp.163.com' #sina mailbox smtp The server                 #Address of smtp server
sender_163 = 'pythonauto_emai@163.com'                   #sender_163 is the sender's mailbox
pwd = 'DYEPOGLZDZYLOMRI'                    #pwd is the authorization code 'DYEPOGLZDZYLOMRI' of the mailbox
#You can also register your own email address and email authorization code'DYEPOGLZDZYLOMRI' The acquisition method can be referred to#http://help.163.com/14/0923/22/A6S1FMJD00754KNP.html
receiver = 'xxxxx@126.com'  
#3 build MIMEMultipart object to represent the mail itself, and you can add text, pictures, attachments, etc
msg = MIMEMultipart()    #Mail body
#4. Set the content of email header
mail_title = 'python Office automation mail'   # Mail title
msg["Subject"] = Header(mail_title,'utf-8')  #Load body
msg["From"] = sender_163           #Sender
msg["To"] = Header("Test mailbox",'utf-8') #title
#5 add body text
mail_content = "Hello, this is using python Test of logging in to mailbox 126 to send mail"   #Body content of the message
message_text = MIMEText(mail_content,'plain','utf-8')   #Construct text, parameter 1: text content, parameter 2: text format, parameter 3: coding method
msg.attach(message_text)    # Add a text object to the MIMEMultipart object
#6 add picture
image_data = open('D:\study\Datawhale\Office automation-OfficeAutomation\picture\Jay Chou.jpg','rb')   # Binary read picture
message_image = MIMEImage(image_data.read())  # Sets the binary data obtained by reading
image_data.close()       # Close the file you just opened
msg.attach(message_image)  # Add picture files to email messages
# 7 add attachments (excel form)
atta = MIMEText(open(r'D:\study\Datawhale\Office automation-OfficeAutomation\python office automation \Jay Chou.xlsx', 'rb').read(), 'base64', 'utf-8')   # Construction attachment
atta["Content-Disposition"] = 'attachment; filename="Jay Chou.xlsx"'  # Set attachment information
msg.attach(atta)       ## Add an attachment to the email message
#8 send mail
smtp = SMTP_SSL(host_server)       #Create SMTP object with SSL login
smtp.login(sender_163,pwd)         ## Log in to the mailbox and pass parameter 1: email address, parameter 2: mailbox authorization code
smtp.sendmail(sender_163,receiver,msg.as_string()) # Send e-mail, delivery parameters 1: sender's e-mail address, parameter 2: recipient's e-mail address, parameter 3: change the e-mail content format to str
print("Mail sent successfully")
smtp.quit         # Close SMTP object
Mail sent successfully

<bound method SMTP.quit of <smtplib.SMTP_SSL object at 0x0000023545F5C850>>

For the answers to the exercise questions, please refer to the big man: https://www.wolai.com/q2VieJLU2Yob7LLZoMLxgd

Keywords: Python Windows list

Added by DSM on Sat, 29 Jan 2022 15:50:43 +0200