Python net programming

Ruochen_ 2021-02-21 11:24:10
python programming


Network programming

  • The Internet :

  • Network protocol : A set of rules

  • A network model :

    • Seven layer model - Seven layers - theory
      • The physical layer
      • Data link layer
      • The network layer
      • Transport layer
      • The session layer
      • The presentation layer
      • application layer
    • Four layer model - The practical application
      • The link layer
      • The network layer
      • Transport layer
      • Reference layer
  • Each layer has its own protocol for information exchange or collaboration

  • TCP/IP Protocol family

  • IP Address : Responsible for locating only one machine on the network

    • IP The address is divided into ABCDE class
    • It's made up of four number fields , The value of each number field is 0-255
    • 192.168.xxx.xxx: LAN ip
    • 127.0.0.1: This machine
    • IPv4, IPv6
  • port

    • Range : 0-65535
      • Well known ports :0-1023
      • Unknown port :1024-

ICP/UDP agreement

  • UDP: Non secure, non link oriented transport

    • Poor safety
    • Size limit 64kb
    • There is no order
    • Fast
  • TCP

    • Link based communication
  • SOCKET Programming

    • socket( Socket ): It's an endpoint for network communication , It can realize the process communication of different hosts , The Internet is mostly based on socket signal communication
    • adopt IP+ The communication mechanism of port locating the other side and sending message
    • It is divided into UDP and TCP
    • client Client, The party who initiated the visit
    • Server side Server, The party to be visited
  • UDP Programming

    • Server End process
      1. establish socket,socket It's an example of specific communications
      2. binding , For the creation of socket Assign fixed ports and ip Address
      3. Accept the content sent by the other party
      4. Send feedback , This step is not necessary
    • Client End process
      1. Establishing communication socket
      2. Send content to the specified server
      3. Receive feedback from the server
    • Server case v01
      '''
      Server End process
      1. establish socket,socket It's an example of specific communications
      2. binding , For the creation of socket Assign fixed ports and ip Address
      3. Accept the content sent by the other party
      4. Send feedback , This step is not necessary
      '''
      # socket Module responsible socket Programming 
      import socket
      # Functions that simulate the server 
      def serverFunc():
      # 1. establish socket
      # socket.AF_INET: Use ipv4 Protocol family 
      # socket.SOCK_DGRAM: Use UDP signal communication 
      sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
      # 2. binding ip and port
      # 127.0.0.1: This ip The address represents the machine itself 
      # 7852: Randomly assigned port number 
      # The address is a tuple type ,(ip, port)
      addr = ("127.0.0.1", 7852)
      sock.bind(addr)
      # 3. Accept the other party's message 
      # The way to wait is to die , No other possibilities 
      # recvfrom The accepted return value is a tuple, The former represents data , The latter indicates the address 
      # Parameter means buffer size 
      # rst = sock.recvfrom(500)
      data, addr = sock.recvfrom(500)
      print(data)
      print(type(data))
      # The data sent is bytes Format , You have to decode to get str Format content 
      # decode The default parameter is utf8
      text = data.decode()
      print(type(text))
      print(text)
      # Messages returned to the other party 
      rsp = "Ich hab keine Hunge"
      # The data sent needs to be encoded into bytes Format 
      # The default is utf8
      data = rsp.encode()
      sock.sendto(data, addr)
      if __name__ == '__main__':
      print("Starting server.........")
      serverFunc()
      print("Ending server...........")
      
    • Client case v02
      import socket
      '''
      Client End process
      1. Establishing communication socket
      2. Send content to the specified server
      3. Receive feedback from the server
      '''
      def clientFunc():
      sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
      text = "I love you"
      # The data sent must be bytes Format 
      data = text.encode()
      # send out 
      sock.sendto(data, ("127.0.0.1", 7852))
      data, addr = sock.recvfrom(200)
      data = data.decode()
      print(data)
      if __name__ == '__main__':
      clientFunc()
      
    • The server program should run permanently , It is usually treated with dead cycle
    • Modified server version v03
      '''
      Server End process
      1. establish socket,socket It's an example of specific communications
      2. binding , For the creation of socket Assign fixed ports and ip Address
      3. Accept the content sent by the other party
      4. Send feedback , This step is not necessary
      '''
      # socket Module responsible socket Programming 
      import socket
      # Functions that simulate the server 
      def serverFunc():
      # 1. establish socket
      # socket.AF_INET: Use ipv4 Protocol family 
      # socket.SOCK_DGRAM: Use UDP signal communication 
      sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
      # 2. binding ip and port
      # 127.0.0.1: This ip The address represents the machine itself 
      # 7852: Randomly assigned port number 
      # The address is a tuple type ,(ip, port)
      addr = ("127.0.0.1", 7852)
      sock.bind(addr)
      # 3. Accept the other party's message 
      # The way to wait is to die , No other possibilities 
      # recvfrom The accepted return value is a tuple, The former represents data , The latter indicates the address 
      # Parameter means buffer size 
      # rst = sock.recvfrom(500)
      data, addr = sock.recvfrom(500)
      print(data)
      print(type(data))
      # The data sent is bytes Format , You have to decode to get str Format content 
      # decode The default parameter is utf8
      text = data.decode()
      print(type(text))
      print(text)
      # Messages returned to the other party 
      rsp = "Ich hab keine Hunge"
      # The data sent needs to be encoded into bytes Format 
      # The default is utf8
      data = rsp.encode()
      sock.sendto(data, addr)
      if __name__ == '__main__':
      import time
      while 1:
      try:
      serverFunc()
      except Exception as e:
      print(e)
      time.sleep(1)
      
  • TCP Programming

    • Link oriented transport , That is, a link needs to be established before each transmission
    • Client and server two programs need to be written
    • Server End of the writing process
      1. establish socket Responsible for specific communications , This socket In fact, it is only responsible for accepting the request of the other party , The real communication is re established after linking socket
      2. Binding port and address
      3. Monitor access socket
      4. Visited socket, It can be understood that access establishes a link path for communication
      5. Accept the content sent by the other party , Use what you receive socket Accept content
      6. If necessary , Send feedback
      7. Turn off link access
    • Client End of the writing process
      1. Establish communication socket
      2. Link to each other , Ask to establish a path with the other party
      3. Send content to the other server
      4. Accept feedback from others
      5. Turn off link access
    • Case study v04
      import socket
      def tcp_srv():
      # 1. establish socket Responsible for specific communications , This socket In fact, it is only responsible for accepting the request of the other party , The real communication is re established after linking socket
      # You need to use two parameters 
      # AF_INET: Meaning with UDP Agreement 
      # SOCK_STREAM: It shows that the use of TCP communicate 
      sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      # 2. Binding port and address 
      # This address information is a tuple type content , The tuple is divided into two parts , The first part is the string , representative ip, The second part is ports , It's an integer , Recommendation is greater than 10000
      addr = ("127.0.0.1", 8998)
      sock.bind(addr)
      # 3. Monitor access socket
      sock.listen()
      while True:
      # 4. Visited socket, It can be understood as receiving access, that is, establishing a communication link path 
      # accept The first element of the returned tuple is assigned to skt, The second is assigned to addr
      skt, addr = sock.accept()
      # 5. Accept the content sent by the other party , Take advantage of what you receive socket Accept content 
      # 500 On behalf of buffersize
      # msg = skt.receive(500)
      msg = skt.recv(500)
      # What is received is bytes Format content 
      # expect str Format , It needs to be decoded 
      msg = msg.decode()
      rst = "Receive msg: {0} from {1}".format(msg, addr)
      print(rst)
      # 6. If necessary , Send feedback 
      skt.send(rst.encode())
      # 7. Turn off link access 
      skt.close()
      if __name__ == '__main__':
      print("Starting tcp server........")
      tcp_srv()
      print("Ending tcp server..........")
      
    • Case study v05
      import socket
      def tcp_clt():
      # 1. Establish communication socket
      sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      # 2. Link to each other , Ask to establish a path with the other party 
      addr = ("127.0.0.1", 8998)
      sock.connect(addr)
      # 3. Send content to the other server 
      msg = "I love you"
      sock.send(msg.encode())
      # 4. Accept feedback from others 
      rst = sock.recv(500)
      print(rst.decode())
      # 5. Turn off link access 
      sock.close()
      if __name__ == '__main__':
      tcp_clt()
      

FTP Programming

  • FTP(FileTransferProtoacal) File transfer protocol

  • purpose : Customize some special services for uploading and downloading files

  • The user classification : Sign in FTP The server must have an account

    • Real Account : Registered account
    • Guest Account : May temporarily authorize the behavior of a certain type of person
    • Anonymous Account : Anonymous accounts , Allow anyone to
  • FIP Workflow

    1. The client Links... On the remote host FTP The server
    2. The client enters the user name and password ( perhaps “anonymous” And email address )
    3. Client and server carry out various file transfer and information query operations
    4. Client from remote FTP The server exits , End transmission
  • FTP Document representation

    • In three paragraphs FTP Files on the server
    • HOST: The host address , Be similar to ftp.mozilla.org, With ftp start
    • DIR: Catalog , Represents the local path of the file , for example pub/android/focus/1.1-RC1
    • File: File name , for example Klar-1.1-RC1.apk
    • If you want to express it completely and accurately ftp On a file , We need to put the three parts together
    • Case study v06
      # The corresponding package needs to be imported , Mainly ftplib
      import ftplib # About FTP All the operations are in this bag 
      import os
      import socket
      # The three parts are expressed exactly in ftp A file on the server 
      # A lot of publicity ftp Server access can go wrong or not respond 
      HOST = "ftp.acc.umu.se"
      DIR = 'Public/EFLIB/'
      FILE = 'README'
      # 1. The client Links... On the remote host FTP The server 
      try:
      f = ftplib.FTP()
      # It's easy to debug by setting the debug level 
      f.set_debuglevel(2)
      # Link host address 
      f.connect(HOST)
      except Exception as e:
      print(e)
      exit()
      print("***Connected to host {0}".format(HOST))
      # 2. The client enters the user name and password ( perhaps “anonymous” And email address )
      try:
      # Log in if no user information is entered , Anonymous login is used by default 
      f.login()
      except Exception as e:
      print(e)
      exit()
      print("***Logged in as 'anonymous'")
      # 3. Client and server carry out various file transfer and information query operations 
      try:
      # Change the current directory to the specified directory 
      f.cwd(DIR)
      except Exception as e:
      print(e)
      exit()
      print("*** Changed dir to {0}".format(DIR))
      try:
      # from FTP Download files on the server 
      # The first parameter is ftp command 
      # The second parameter is the callback function 
      # This function means , perform RETR command , After downloading the file to the local , Run callback function 
      f.retrbinary('RETR {0}'.format(FILE), open(FILE, 'wb').write)
      except Exception as e:
      print(e)
      exit()
      # 4. Client from remote FTP The server exits , End transmission 
      f.quit()
      

Mail Programming

The history of email

  • origin

    • 1969 Leonard K. The professor sent to his colleagues “LO”
    • 1971 The US Department of Defense's own ARPANET (Arpanet) Communication mechanism
    • For mailing address @
    • 1987 China's first email in “Across the Great Wall we can reach every corner in the world”
  • Management procedure

    • Euroda Make email popular
    • Netscape,outlook,forxmail From behind
    • Hotmail Use your browser to send mail
  • Reference material

Email workflow

  • MUA(MailUserAgent) Email user agent

  • MTA(MailTransferAgent) Mail transfer agent

  • MDA(MailDeliveryAgent) Mail delivery agent

  • laoshi@qq.com, teacher , Beijing haidian

  • xuesheng@sina.com, Student , Jiang'an District, Shanghai

  • technological process

    1. MUA->MTA, The mail is already on the server
    2. qq MTA->........-> sina MTA, The mail is on Sina's server
    3. sina MTA-> sina MDA, The email is already in your mailbox
    4. sina MDA -> MUA(Foxmail/Outlook), Download email to local computer
  • Programming

    • send out : MUA->MTA with SMTP: SimpleMailTransferProtocal, contain MTA->MTA
    • Accept : MDA->MUA with POP3 and IMAP: PostOfficeProtocal v3 and InternetMessageAccessProtocal v4
  • preparation

    • Sign up for email ( With qq Mailbox as an example )
    • Third party mailbox needs special settings , With qq Mailbox as an example
      • Enter the setting Center
      • Get authorization code
  • Python for mail

    • SMTP The protocol is responsible for sending emails
      • Use email Module build mail

        • Plain text mail
        • Case study v07
          # Import the corresponding package 
          import smtplib
          from email.mime.text import MIMEText
          # MIMEText Three main parameters 
          # 1. Email content 
          # 2. MIME subtypes , In this case, we use plain Express text type 
          # 3. E-mail encoding format 
          msg = MIMEText("Hello, i am xxxx", "plain", "utf-8")
          # send out email Address 
          from_addr = "1441865605@qq.com"
          # The password here is the authorization code after application setting 
          from_pwd = "ajwvzqdlfigahiae" # Authorization code 
          # Recipient information 
          # At this time to use qq mailbox 
          to_addr = "1441865605@qq.com"
          # Input SMIP Server address 
          # There are different values according to different mail service providers 
          # Now basically any email service provider , If a third party is used to send and receive mail , You need to turn on the authorization option 
          # tencent qq The mailbox uses SMTP The address is smtp.qq.com
          smtp_srv = "smtp.qq.com"
          try:
          # Two parameters 
          # The first is the server address , But it must be bytes Format , So you need to code 
          # The second parameter is the server's access port 
          srv = smtplib.SMTP_SSL(smtp_srv.encode(), 465) # SMTP Protocol default port 25
          # Log in to email 
          srv.login(from_addr, from_pwd)
          # Send E-mail 
          # Three parameters 
          # 1. Sending address 
          # 2. Accept address , Must be list Format 
          # 3. send content , Send as string 
          srv.sendmail(from_addr, [to_addr], msg.as_string())
          srv.quit()
          except Exception as e:
          print(e)
          
      • HTML Send by email

        • Get ready HTML Code as content
        • Put the mail subtype Set to html
        • send out
        • Case study v08
          from email.mime.text import MIMEText
          mail_content = """
          <!DOCTYPE html>
          <html lang="en">
          <head>
          <meta charset="UTF-8">
          <title>Title</title>
          </head>
          <body>
          <h1> This is a letter HTML Format mail </h1>
          </body>
          </html>
          """
          msg = MIMEText(mail_content, "html", "utf-8")
          # Build sender address and login information 
          from_addr = "1441865605@qq.com"
          # The password here is the authorization code after application setting 
          from_pwd = "ajwvzqdlfigahiae" # Authorization code 
          # Build recipient information 
          to_addr = "971254246@qq.com"
          smtp_srv = "smtp.qq.com"
          try:
          import smtplib
          srv = smtplib.SMTP_SSL(smtp_srv.encode(), 465)
          srv.login(from_addr, from_pwd)
          srv.sendmail(from_addr, [to_addr], msg.as_string())
          srv.quit()
          except Exception as e:
          print(e)
          
      • Send email with attachments

        • You can think of an email as a combination of a text message and an attachment
        • If an email involves more than one part , Need to use MIMEMultipart Format construction
        • Add one MIMEText Text
        • Add one MIMEBase perhaps MIMEText As an attachment
        • Case study v09
          from email.mime.text import MIMEText # Build attachments using 
          from email.mime.multipart import MIMEBase, MIMEMultipart # Build basic mail usage 
          mail_mul = MIMEMultipart()
          # Build message body 
          mail_text = MIMEText("Hello, i am xxxx", "plain", "utf-8")
          # Attach the constructed email body to the email 
          mail_mul.attach(mail_text)
          # Build additional 
          # Build attachments , Need to read the attachment from local 
          # Open a local file 
          # With rb Format open 
          with open("02.html", "rb") as f:
          s = f.read()
          # Set attachment's MIME And file name 
          m = MIMEText(s, 'base64', "utf-8")
          m["Content-Type"] = "application/octet-stream"
          # We need to pay attention to 
          # 1. attachment The last semicolon is in English 
          # 2. filename You need to wrap it in quotation marks , Pay attention to staggering with the outer quotation marks 
          m["Content-Disposition"] = "attachment; filename='02.html'"
          # Add to MIMEMultipart
          mail_mul.attach(m)
          # send out email Address 
          from_addr = "1441865605@qq.com"
          # The password here is the authorization code after application setting 
          from_pwd = "ajwvzqdlfigahiae" # Authorization code 
          # Recipient information 
          # At this time to use qq mailbox 
          to_addr = "1441865605@qq.com"
          # Input SMIP Server address 
          # There are different values according to different mail service providers 
          # Now basically any email service provider , If a third party is used to send and receive mail , You need to turn on the authorization option 
          # tencent qq The mailbox uses SMTP The address is smtp.qq.com
          smtp_srv = "smtp.qq.com"
          try:
          import smtplib
          # Two parameters 
          # The first is the server address , But it must be bytes Format , So you need to code 
          # The second parameter is the server's access port 
          srv = smtplib.SMTP_SSL(smtp_srv.encode(), 465) # SMTP Protocol default port 25
          # Log in to email 
          srv.login(from_addr, from_pwd)
          # Send E-mail 
          # Three parameters 
          # 1. Sending address 
          # 2. Accept address , Must be list Format 
          # 3. send content , Send as string 
          srv.sendmail(from_addr, [to_addr], mail_mul.as_string())
          srv.quit()
          except Exception as e:
          print(e)
          
      • Add headers , CC and other information

        • mail["From"] Indicates sender information , Include name and email
        • mail["To"] Indicates the recipient information , Include name and email address
        • mail["Subject"] Represents a summary or subject information
        • Case study v10
          from email.mime.text import MIMEText
          from email.header import Header
          msg = MIMEText("Hello world", "plain", "utf-8")
          # use utf-8 The encoding is possible because the content contains non English characters 
          header_from = Header(" from A Sent out <A@qq.cn>", "utf-8")
          msg['From'] = header_from
          # Fill in the recipient information 
          header_to = Header(" Go to B<B@sina.com>", "utf-8")
          msg['To'] = header_to
          header_sub = Header(" This is the theme ", "utf-8")
          msg['Subject'] = header_sub
          # Build sender address and login information 
          from_addr = "1441865605@qq.com"
          from_pwd = "ajwvzqdlfigahiae"
          # Build recipient information 
          to_addr = "1441865605@qq.com"
          smtp_srv = "smtp.qq.com"
          try:
          import smtplib
          srv = smtplib.SMTP_SSL(smtp_srv.encode(), 465)
          srv.login(from_addr, from_pwd)
          srv.sendmail(from_addr, [to_addr], msg.as_string())
          srv.quit()
          except Exception as e:
          print(e)
          
      • Support at the same time html and text Format

        • Construct a MIMEMultipart Format mail
        • MIMEMultipartd forehead subtype Set to alternative Format
        • add to HTML and Text mail
        • Case study v11
          from email.mime.text import MIMEText
          from email.mime.multipart import MIMEMultipart
          # Construct a MIMEMultipart mail 
          msg = MIMEMultipart("alternative")
          # Construct a HTML Email content 
          html_content = """
          <!DOCTYPE html>
          <html lang="en">
          <head>
          <meta charset="UTF-8">
          <title>Title</title>
          </head>
          <body>
          <h1> This is a letter HTML Format mail </h1>
          </body>
          </html>
          """
          #
          msg_html = MIMEText(html_content, "html", "utf-8")
          msg.attach(msg_html)
          msg_text = MIMEText("just text content", "plain", "utf-8")
          msg.attach(msg_text)
          # send out email Address 
          from_addr = "1441865605@qq.com"
          from_pwd = "ajwvzqdlfigahiae"
          # Recipient information :
          # Use my qq mailbox 
          to_addr = "1441865605@qq.com"
          # Input SMTP Server address :
          # This address has a different value depending on the mail service provider , This is from a mail service provider smtp Address 
          # I use it qq E-mail , Tencent... Should be filled here qq Mailbox smtp value , namely smtp.163.com,
          # The authorization code needs to be turned on ,
          smtp_srv = "smtp.qq.com"
          try:
          import smtplib
          # The encrypted 
          #server = smtplib.SMTP_SSL(smtp_srv.encode(), 465) # SMTP The default port of the protocol is 25
          # qq The mailbox requires the use of TLS The encrypted 
          server = smtplib.SMTP(smtp_srv.encode(), 25) # SMTP The default port of the protocol is 25
          server.starttls()
          # Set debug level 
          # By setting the debug level , You can clearly see the interactive steps of sending email 
          server.set_debuglevel(1)
          # Log in to your email address 
          server.login(from_addr, from_pwd)
          server.sendmail(from_addr, [to_addr], msg.as_string())
          server.quit()
          except Exception as e:
          print(e)
          
      • Use smtplib Module send mail

    • POP3 The protocol is responsible for receiving mail
      • Essentially, MDA To MUA A process of
      • from MDA The download is a complete email structure , You need to parse to get each specific readable content
      • step :
        1. use poplib Download the original content of the email structure
          1. Prepare the corresponding content ( mailing address , password ,POP3 example )
          2. Identity Authentication
          3. Generally, you will get the whole list of mail in the mailbox first
          4. According to the corresponding serial number , Get the data stream of a letter
          5. Use the analytic function to analyze the corresponding email structure
        2. use email Analyze the specific content of the email
      • Case study v12
        # Import related packages 
        # poplib In charge of from MDA To MUA download 
        import poplib
        # The following package is responsible for the related mail structure analysis 
        from email.parser import Parser
        from email.header import decode_header
        from email.utils import parseaddr
        # Get the original content of the email 
        # This process is mainly responsible for MDA To MUA Download and use Parse Rough analysis 
        def getMsg():
        # Prepare the corresponding information 
        email = "1441865605@qq.com"
        # Email authorization code 
        pwd = "ajwvzqdlfigahiae"
        # pop3 Server address 
        pop3_srv = "pop.qq.com" # port 995
        # ssl The representative is the safe passage 
        srv = poplib.POP3_SSL(pop3_srv)
        # user representative email Address 
        srv.user(email)
        # pass_ Representative password 
        srv.pass_(pwd)
        # The following operations are used according to the specific business 
        # stat Return the number of messages and space 
        # Be careful stat Return to one tuple Format 
        msgs, counts = srv.stat()
        print("Messages: {0}, Size: {1}".format(msgs, counts))
        # list Return to the list of all mail numbers 
        # mails It's a list of all mail numbers 
        rsp, mails, octets = srv.list()
        # You can view the returned mails The list is similar to [b'1 82923', b'2 2184', ...]
        print(mails)
        # Get the latest email , Be careful , The e-mail index number is from 1 Start , The latest represents the highest index number 
        index = len(mails)
        # retr Responsible for returning the contents of a letter with a specific index number , This content is not readable 
        # lines Store each line of the original text of the message 
        rsp, lines, octets = srv.retr(index)
        # Get the original text of the entire message 
        msg_count = b'\r\n'.join(lines).decode("utf-8")
        # Parse out the whole structure of the email 
        # The parameter is the whole message after decoding 
        msg = Parser().parsestr(msg_count)
        # Close links 
        srv.quit()
        return msg
        # Detailed analysis of the email content 
        # msg The representative is the original content of the mail 
        # idnent Represents the level of mail nesting 
        def parseMsg(msg, indent=0):
        '''
        1. It's quite possible that the e-mail has a nested format
        2. There's only one mail From,To,Subject Information like that
        :param msg:
        :param indent: How many emails are there in the description email MIMEXXX Type of content , Indent accordingly when displaying
        :return:
        '''
        # Try to extract the head information 
        # It's only in the first tier that there's content ,
        # There's only one thing about this 
        if indent == 0:
        for header in ['From', "To", 'Subject']:
        # Use get Can avoid if there is no relevant keyword error possibility 
        # without keyword ”From“, We use msg["From"] Will report a mistake 
        value = msg.get(header, '')
        if value:
        # Subject You can decode the contents of , He's a string type 
        if header == 'Subject':
        value = decodeStr(value)
        # If it is From and To Field , The content is about " My mailbox <xxxxx@qq.com>“ This format 
        else:
        hdr, addr = parseaddr(value)
        name = decodeStr(hdr)
        # Finally return to the form of " My mailbox <xxx@qq.com> The format of 
        value = "{0}<{1}>".format(name, addr)
        print("{0}, {1}: {2}".format(indent, header, value))
        # The following code focuses on the email content itself 
        # In the content of the email , It could be multipart type , It could also be a normal mail type 
        # The following parsing uses recursion 
        if (msg.is_multipart()):
        # If it is multipart type , Call recursive parsing 
        # Get a base mail part of multipart mail 
        parts = msg.get_payload()
        # enumerate Functions are built-in functions 
        # The function is to put a list , Here is parts, Generate an index and parts A new list of the original contents 
        # for example enumerate(['a', 'b', 'c']) The result is : [(1,'a'), (2, 'b'), (3, 'c')]
        for n,part in enumerate(parts):
        # Multiplying a string by a number means that the string is n Double expansion 
        # such as ”aa" * 2 -> "aaaa"
        print("{0}spart: {1}".format(' '*indent, n))
        parseMsg(part, indent+1)
        else: # The base type 
        # get_content_type It's a function provided by the system , Get the content type 
        content_type = msg.get_content_type()
        # text/plain perhaps text/html It's a fixed value 
        if content_type == 'text/plain' or content_type == 'text/html':
        content = msg.get_payload(decode=True)
        charset = guessCharset(msg)
        if charset:
        content = content.decode(charset)
        print("{0}Text: {1}".format(indent, content))
        else: # It's not text content , It should be an attachment 
        print('{0}Attachment: {1}'.format(indent, content_type))
        def decodeStr(s):
        '''
        s Represents... In an email From,To,Subject Any one of
        Yes s decode , Decoding is the reverse of coding
        :param s:
        :return:
        '''
        value, charset = decode_header(s)[0]
        # charset It could be empty 
        if charset:
        # If you specify the encoding , Then decode with the specified encoding format 
        value = value.decode(charset)
        return value
        def guessCharset(msg):
        '''
        Guess the encoding format of the message
        :param msg:
        :return:
        '''
        # Call a ready-made function 
        charset = msg.get_charset()
        if charset is None:
        # Find the content type , And convert it to lowercase 
        content_type = msg.get("Content-Type", "").lower()
        pos = content_type.find("charset=")
        if pos >= 0:
        # If you include chraset, The content is like charset=xxxx
        charset = content_type[pos+8:].strip()
        return charset
        if __name__ == "__main__":
        # Get the original content of the email 
        msg = getMsg()
        print(msg)
        # Accurately parse email content 
        parseMsg(msg, 0)
        
版权声明
本文为[Ruochen_]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/02/20210221112209893N.html

  1. Python Tkinter inserts all the pictures in a directory into the docx file
  2. 解决忽略VScode中Python插件pylint报错的问题
  3. To solve the problem of ignoring the error of Python plug-in in vscode
  4. python 毫秒级时间,时间戳转换
  5. Python millisecond time, timestamp conversion
  6. python try except 出现异常时,except 中如何返回异常的信息字符串
  7. When an exception occurs in Python try except, how to return the exception information string in except
  8. 手机最强Python编程神器,在手机上运行Python
  9. The strongest Python Programming artifact on mobile phones, running Python on mobile phones
  10. 2021年Python程序员薪资待遇如何?
  11. 「python安装」Windows上安装和创建python开发环境
  12. What is the salary of Python programmers in 2021?
  13. "Python installation" to install and create a python development environment on Windows
  14. python解决组合问题
  15. Python to solve the problem of composition
  16. Python中的Lasso回归之最小角算法LARS
  17. Lars, the least angle algorithm of lasso regression in Python
  18. 利用python提取网站曲线图数据
  19. Using Python to extract website graph data
  20. Python3中urllib详细使用方法(header,代理,超时,认证,异常处理)
  21. Detailed usage of urllib in Python 3 (header, proxy, timeout, authentication, exception handling)
  22. python 第三方库paramiko
  23. python 第三方库paramiko
  24. Python third party library paramiko
  25. Python third party library paramiko
  26. 卸载 PyCharm!这才是 Python 小白的最理想的 IDE
  27. 卸载 PyCharm!这才是 Python 小白的最理想的 IDE
  28. Uninstall pycharm! This is the ideal IDE for Python Xiaobai
  29. django学习-27.admin管理后台里:对列表展示页面的数据展示进行相关优化
  30. Uninstall pycharm! This is the ideal IDE for Python Xiaobai
  31. Django learning - 27. Admin management background: optimize the data display of the list display page
  32. python day2
  33. python day2
  34. Python 内存泄漏问题排查
  35. Troubleshooting of Python memory leak
  36. Python 与 excel的简单应用
  37. Simple application of Python and excel
  38. Python 与 excel的简单应用
  39. Simple application of Python and excel
  40. 2.7万 Star!最全面的 Python 设计模式集合
  41. 27000 stars! The most comprehensive collection of Python design patterns
  42. python day3
  43. python day3
  44. Commonly used data operation functions of Python
  45. (数据科学学习手札108)Python+Dash快速web应用开发——静态部件篇(上)
  46. (learning notes of data science 108) Python + dash rapid web application development -- static components (I)
  47. (数据科学学习手札108)Python+Dash快速web应用开发——静态部件篇(上)
  48. (learning notes of data science 108) Python + dash rapid web application development -- static components (I)
  49. [Python] Matplotlib 图表的绘制和美化技巧
  50. Drawing and beautifying skills of [Python] Matplotlib chart
  51. [Python] Matplotlib 图表的绘制和美化技巧
  52. Drawing and beautifying skills of [Python] Matplotlib chart
  53. Virtual environment of Python project
  54. 翻译:《实用的Python编程》02_01_Datatypes
  55. Translation: practical Python Programming 02_ 01_ Datatypes
  56. 翻译:《实用的Python编程》02_01_Datatypes
  57. 翻译:《实用的Python编程》02_01_Datatypes
  58. Translation: practical Python Programming 02_ 01_ Datatypes
  59. Translation: practical Python Programming 02_ 01_ Datatypes
  60. Python 3 入门,看这篇就够了