#Mengxin log #1.Python script: the files are sent to the corresponding mailbox in batches according to the student number

Keywords: Python Operating System regex smtp

        Mengxin records his learning experience in some days.

preface:

         The teacher sent me the corrected experimental report (. pdf) at noon. As a teacher assistant, I need to return each report to the corresponding students and register my grades. There are 5 + reports and 50 + students in a semester. Using the school system to send e-mail is too cumbersome and takes a lot of time. Writing a script should be a lot easier.

        The student number will appear in the pdf file name of each report, and our school mailbox is also a unified format of student number + suffix. So I determined the preliminary idea: traverse the file name, obtain the student number, edit the email content and send it to the students with the corresponding student number. As a sprout in this regard, I got a positive reply after consulting the senior students, so I have the following contents.

Summary: Python script mail os   re   smtplib   MIMEText MIMEMultipart MIMEApplication

The following is the specific implementation process:

catalogue

Traversing files using os

Use re to get the student number in the file name

Send mail

Result

Whole Code

Reference       

Traversing files using os

import os

path = "./" + labName
files = os.listdir(path)
print(type(files),len(files))
for filename in files:

You need to use os. The os module provides a very rich method to deal with files and directories. [1]

os.listdir(path)   Returns a list of files or folder names contained in the folder specified by path.

         For example, the absolute path of my code is E:\A_scriptTools\dspMail, the absolute path where I save the file is E:\A_scriptTools\dspMail \ demo, save the file as E:\A_scriptTools\dspMail\demo\*. At this point, my path is the demo folder. The value returned by this function is a list that stores strings. Each string is the name of each file, including the suffix.

        So far, we have the name of each PDF file.

Use re to get the student number in the file name

pattern = "Lab2 Report_(.*?)_.*?"

def getSID(filename):
    information = re.match(pattern, filename)
    SID = information.group(1)
    return SID

         We need to use re. Regular expression is a special character sequence, which can help us easily check whether a string matches a pattern. [2]

re.match(pattern, string, flags=0)

        pattern is the regular expression to be matched, and string is the string to be matched. Flag flag bit, which is used to control the matching method of regular expressions, such as case sensitive, multi line matching, etc.

        For example, here I am:

          Where "11111111" is the student number, "Lab 2 Report" and "" after the student number are fixed. Then my pattern is set to

pattern = "Lab2 Report_(.*?)_.*?"

         .*? Can be treated as any string. The returned value is a group (if there is no such format, it is none). group[0] represents the complete pattern found in the string. group[i] indicates that the content of the ith (. *?) (with brackets) needs to be replaced. for instance:

          Here, group[1] is the required student number.

Send mail

        From the perspective of thinking, sending e-mail requires three parts: setting parameters (various parameters are required, including host, user name, password, sending address and receiving address, sending time, etc.), editing e-mail content (mainly including text and attachments) and sending e-mail (the process of sending e-mail needs to "log in to the mailbox" first and ensure that the process of sending e-mail is smooth) .

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

        Two packages are required:

         SMTP lib is an operation module of SMTP (Simple Mail Transfer Protocol), which plays the role of mutual communication between servers in the process of sending mail [3]. It is used to log in to the mailbox and send the edited mail.

        Three tools 3 from email.mime. * are used to edit emails (the suffixes roughly show their respective roles):

         MIMEMultipart can be said to be adhesive and frame. With this adhesive, the text and attachments can be filled up.

         MIMEText is mainly used to process text information, which is generally used to generate text.

         Mime application is what I use to process PDF files.

        Then the code is implemented as follows,

        1. Input parameters first:

mail_host = 'smtp.exmail.qq.com'
my_sender = 'XXXX'
my_pass = 'xxxx'
receiver = SID + '@mail.XXX.edu.cn'

        mail_ The login password of Tencent enterprise mailbox is not the mailbox password, but the client password. 2. You need to open "Settings - mailbox binding - security settings: enable secure login" in the web version of Tencent enterprise mailbox. If you don't do this, you can't break through the manual verification level by logging in to Tencent enterprise mailbox with SMTP lib, and you will report an error: 535, b'Error: authentication failed, system busy. 2. Tencent enterprise mailbox needs SSL authentication, so my later code will be SMTP_SSL, some mailboxes don't need SSL, just use SMTP. For details, please see the column in Reference. It is better than me.

        sender and receiver represent sending address and receiving address respectively.

        2. Next, edit the email content         

    message = MIMEMultipart()
    message['From'] = my_sender
    message['To'] = receiver
    message['Subject'] = labName + ' Report results'
    part1 = MIMEText('This is the corrected report. Please check it. Good luck.', 'plain', 'utf-8')

    part2 = MIMEApplication(open(file, 'rb').read())
    part2.add_header('Content-Disposition', 'attachment', filename=labName+'-'+SID+'.pdf')

    message.attach(part1)
    message.attach(part2)

        Create a new message. From represents the sending address, To represents the receiving address, Subject represents the title, part1 is the body, and Part2 is the corresponding PDF file. Note that the functions called by the text and PDF files have parameters To be entered. It needs To be adjusted according To the actual situation. Finally, use message.attach To load the body and attachments.

        3. Finally, send an email

    try:
        smtpObj = smtplib.SMTP_SSL(mail_host, port=465)
        smtpObj.login(my_sender, my_pass)
        smtpObj.sendmail(
            my_sender, receiver, message.as_string())
        smtpObj.quit()
        print(SID + ' success')
    except smtplib.SMTPException as e:
        print(SID+'error', e)

        As mentioned above, Tencent enterprise mailbox needs SMTP_SSL. The port number is 465. It's best to query some specific port numbers for different mailboxes first.

        login logs in to the mailbox, sendmail sends the edited email, and finally quit to exit the mailbox.

Result:

        The general process is above, and the actual effect drawing is attached:

        To sum up, they are very basic tools. Install PDF files in a folder, locate the path, and read the file name with os; Preliminarily analyze the student number position and use re to find the student number in the string; email.mime. * write an email, including the email title, recipient and sender. The body and attachments need to be created and combined together. Send e-mail with SMTP lib, log in - send - log out. Login requires an account password and is not blocked by security detection.

        (By the way) I heard that yagmail is more suitable for python?

        Thanks for reading, please give me more advice!

Whole Code

import os
import re
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

labName = ""
pattern = ""
mail_host = ''
my_sender = ''
my_pass = ''


def getSID(filename):
    information = re.match(pattern, filename)
    SID = information.group(1)
    return SID

def sendEmail(SID, file):
    receiver = SID + '@mail.XXX.edu.cn'

    ## PDF
    message = MIMEMultipart()
    message['From'] = my_sender
    message['To'] = receiver
    message['Subject'] = labName + ' Report results'
    part1 = MIMEText('This is the corrected report. Please check it. Good luck.', 'plain', 'utf-8')

    part2 = MIMEApplication(open(file, 'rb').read())
    part2.add_header('Content-Disposition', 'attachment', filename=labName+'-'+SID+'.pdf')

    message.attach(part1)
    message.attach(part2)
    try:
        smtpObj = smtplib.SMTP_SSL(mail_host, port=465)
        smtpObj.login(my_sender, my_pass)
        smtpObj.sendmail(
            my_sender, receiver, message.as_string())
        smtpObj.quit()
        print(SID + ' success')
    except smtplib.SMTPException as e:
        print(SID+'error', e)


def sendPDF(labName):
    path = "./" + labName
    files = os.listdir(path)
    print(type(files),len(files))
    for filename in files:
        SID = getSID(filename)
        print(SID)
        sendEmail(SID,path+'/'+filename)

if __name__ == "__main__":
    sendPDF(labName)

Reference       

Python OS file / directory method | rookie tutorial (runoob.com)[1] Python OS file / directory method | rookie tutorial (runoob.com) 

Python regular expression rookie tutorial (runoob.com)[2] Python regular expression rookie tutorial (runoob.com) 

In three simple steps, send email in Python - Zhihu (zhihu.com)[3] In three simple steps, send email in Python - Zhihu (zhihu.com) 

python simply sends mail / sends blog with various attachments _zqzwzd - CSDN blog _pythonsends mail with attachments[4] python simple send mail / send mail with various attachments_ zqzwzd's blog - CSDN blog_ python sends mail with attachments 

Thanks for the help of the senior students to manually @ Guoshan car   (7 messages) guo_hao_rui's blog_ Guo shanche_ CSDN blog - blogger in the field of statistical analysis in Data Science

Posted by matthewst on Sun, 10 Oct 2021 05:09:25 -0700