Learning content:
1.1 reading and writing documents
We know that variables can be used to save the operation results when the program is running, but if you want to view the results after the program is closed, you need to save the data to a file. Simply put, you can interpret the file content as a string value, which may be several gigabytes in size. This section will learn how to use python to create, read, and save files on your hard disk.
1.1.1 file and file path
Two attributes of a file: "path" and "file name". The path indicates the location of the file on the computer, and the file name refers to the name of the file in that location. For example, on my computer, there is a name called Datawhale - Research on open source development theory pdf file, and its path is in D:\Datawhale. In windows, the D: \ part of the path is the "root folder" and Datawhale is the folder name. 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')
We can see that the returned is ('Datawhale\docu '), with two slashes. This is because one slash is used to escape. If you call this function on OS X or Linux, the string will be' Datawhale/docu '.
1.1.2 current working directory
Each program running on the computer has a "current working directory". Using OS Getcwd() function, which can obtain the current working path
String, and you can use OS Chdir () changes it.
import os os.getcwd() #Get current working directory
os.chdir('D:\\Datawhale\\python office automation ') #Change current working directory os.getcwd()
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:\Datawhale\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 \\python Course drawing.pptx' os.path.dirname(path) #'D:\Datawhale\python office automation '
os.path.basename(path) #'python course drawing pptx'
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 \\python Course drawing.pptx' os.path.split(caFilePath) #('D:\Datawhale\python office automation ',' python course drawing. pptx ')
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 ',' python course drawing. pptx ')
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 ',' python course drawing. pptx ']
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 file or folder.
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')
os.path.exists('C:\\else')
os.path.isfile('D:\\Datawhale\\python office automation \\python Course drawing.pptx')
os.path.isfile('D:\\Datawhale\\python office automation ')
os.path.isdir('D:\\Datawhale\\python office automation \\python Course drawing.pptx')
os.path.isdir('D:\\Datawhale\\python office automation ')
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('D:\\Datawhale\\python office automation \\python Course drawing.pptx')
os.listdir('D:\\Datawhale\\python office automation ')
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:\\Datawhale\\python office automation '): totalSize = totalSize + os.path.getsize(os.path.join('D:\\Datawhale\\python office automation ',filename)) print(totalSize)
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('D:\\Datawhale\\python office automation \\hello.txt') print(helloFile)
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
sonnetFile = open('D:\\Datawhale\\python office automation \\hello.txt') sonnetFile.readlines()
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 overwrites the original file and starts from scratch. Add mode adds text to the end of an existing file.
baconFile = open('bacon.txt','w') baconFile.write('Hello world!\n')
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()
baconFile = open('bacon.txt') content = baconFile.read() baconFile.close() print(content)
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
shelfFile['cats']
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())
list(shelfFile.values())
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)
fileObj = open('myCats.py','w') fileObj.write('cats = '+pprint.pformat(cats)+'\n')
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
myCats.cats[0]
myCats.cats[0]['name']
1.1.7 practice
1. What happens if an existing file is opened in write mode?
2. What is the difference between the read() and readlines() methods?
Comprehensive exercise:
1, Generate random test paper files
If you are a geography teacher and there are 35 students in your class, you want to conduct a survey in the capitals of the United States
quiz. Unfortunately, there are some bad guys in the class. You can't be sure that students won't cheat. You want random adjustment
The order of 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.
code:
#! python3 # randomQuizGenerator.py - Creates quizzes with questions and answers in # random order, along with the answer key. # The quiz data. Keys are states and values are their capitals. import random capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix', 'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver','Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee','Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois': 'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas': 'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine': 'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan': 'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri': 'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada': 'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton', 'New Mexico':'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh', 'North Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City', 'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence', 'South Carolina': 'Columbia', 'South Dakota': 'Pierre', 'Tennessee': 'Nashville', 'Texas': 'Austin', 'Utah': 'Salt Lake City', 'Vermont': 'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia', 'West Virginia': 'Charleston', 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'} for quizNum in range(35): # Create test papers and answer files quizFile = open('capticalsquiz%s.txt' % (quizNum + 1), 'w') answerKeyFile = open('capticalsquiz_answers%s.txt' % (quizNum + 1), 'w') # Write the title and beginning quizFile.write('Name:\n\nDate:\n\nClass:\n\n') quizFile.write(' ' * 20 + 'State Capticals Quiz (From %s)' % (quizNum + 1)) quizFile.write('\n\n') # Disrupt the capital dictionary states = list(capitals.keys()) random.shuffle(states) # Disrupt the order of states # Loop states to create 50 questions for questionNum in range(50): correctAnswer = capitals[states[questionNum]] wrongAnswers = list(capitals.values()) del wrongAnswers[wrongAnswers.index(correctAnswer)] # Delete the correct answer from the list # random. The sample () function makes this selection easy. Its first parameter is the list you want to select, and the second parameter is the number of values you want to select. wrongAnswers = random.sample(wrongAnswers, 3) answerOption = wrongAnswers + [correctAnswer] random.shuffle(answerOption) # Write problem in file quizFile.write('%s. What is the capital of %s?\n' % (questionNum + 1, states[questionNum])) for i in range(4): quizFile.write(' %s. %s\n' % ('ABCD'[i], answerOption[i])) quizFile.write('\n') # Write answers in the answers volume answerKeyFile.write('%s. %s\n' % (questionNum + 1, 'ABCD'[ answerOption.index(correctAnswer)])) quizFile.close() answerKeyFile.close()
1.2 organization documents
In the previous section, you learned how to create and write new files using Python. This section describes how to use programs to organize files that already exist on your 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. To use the functions of shutil, you first need to import shutil
1.2.1.1 copying files and folders
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('D:\\Datawhale\\python office automation \\bacon.txt', 'D:\\Datawhale\\practice')
os.getcwd()
shutil.copy('D:\\Datawhale\\python office automation \\capitalsquiz_answers1.txt', 'D:\\Datawhale\\practice\\bacon.txt')
shutil.copy('D:\\Datawhale\\python office automation \\bacon.txt', 'D:\\Datawhale\\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 shutil.copytree('D:\\Datawhale\\python office automation ','D:\\Datawhale\\practice')
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('D:\\Datawhale\\practice','D:\\Datawhale\\docu')
shutil.move('D:\\Datawhale\\practice','D:\\Datawhale\\docue')
shutil.move('D:\\Datawhale\\docue\\bacon.txt','D:\\Datawhale\\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:\\Datawhale\\docue') os.getcwd()
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.
pip install send2trash #Installing send2trash module
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 code puts OS The three elements of walk () are separated
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('Miki.txt',compress_type=zipfile.ZIP_DEFLATED) newZip.close()
newZip = zipfile.ZipFile('new.zip','w') newZip.write('D:\\animals\\dogs\\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 namelist() 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()
catInfo = exampleZip.getinfo('animals/Miki.txt')
catInfo.file_size
catInfo.compress_size
print('Compressed file is %s x smaller!' %(round(catInfo.file_size/catInfo.compress_size,2)))
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.
code:
import os,shutil for foldername,subfolders,filenames in os.walk('D:\\python\\automate_online-materials'): for filename in filenames: if filename.endswith('.pdf') or filename.endswith('.png'): print(os.path.join(foldername,filename)) shutil.copy(os.path.join(foldername,filename),'D:\\test9.1') else: continue#Continue means "continue". When a certain condition is met, the continue statement will be triggered, which will skip the following code and return directly to the beginning of the loop.
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.
code:
import os,shutil for foldername,subfolders,filenames in os.walk('D:\\python\\automate_online-materials'): for filename in filenames: if os.path.getsize(os.path.join(foldername,filename))>=500000: print(os.path.join(foldername,filename)) print(os.path.getsize(os.path.join(foldername,filename)))
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.
code:
import os,re,shutil#re provides regular expression matching operations similar to Perl. num = 1 for foldername,subfolders,filenames in os.walk('D:\\test9.2'): for filename in filenames: mo = re.compile(r'spam\d{3}.*(\.\w*)$').search(filename)#The compile function is used to compile regular expressions and generate a Pattern object. Its general form is as follows: re compile(Pattern[, flag]) if mo == None: continue else: if num < 10: temp = 'spam00'+str(num)+mo.group(1) if num>=10 and num<100: temp = 'spam0'+str(num)+mo.group(1) if num>=100: temp = 'spam'+str(num)+mo.group(1) print(temp) shutil.move(os.path.join(foldername,filename),os.path.join(foldername,temp)) num=num+1
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 = '********@163.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 163 mailbox 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('cat.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('cat.xlsx', 'rb').read(), 'base64', 'utf-8') # Construction attachment atta["Content-Disposition"] = 'attachment; filename="cat.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