python automatically monitors and reads the latest messages

  • 2021-09-20 21:03:53
  • OfStack

I won't talk too much, let's just look at the code ~


#zmail Library: You can use a few lines of code to collect for us 1 E-mail 
import zmail
# Enter account number and password 
server=zmail.server('13163964546@qq.com','jie110341')
# Get the latest 1 E-mail 
mail=server.get_latest()
# Read mail 
#zmail.show(mail)
# Read part of the message 
print(mail['subject'])
......
# Read attachments   Mail   Storage path   Overwrite if there is a file with the same name 
zmail.save_acctachment(mail,target_path=None,overwrite=True)

You need to download the zmail library on your computer

Supplement: Python mailbox implementation monitoring computer

I won't talk too much, let's just look at the code ~


import smtplib
import poplib
import email
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import decode_header
def send_email(account, password, email_title, send_text="", file_names=None, file_dir="."):
  msg = MIMEMultipart()
  # msg = MIMEText(HTML, 'html') --  Only text content can be sent 
  content = MIMEText(send_text, "plain", "utf-8")
  msg.attach(content)
  #  File type 
  if isinstance(file_names, list):
    for file_name in file_names:
      send_file_path = file_dir + "/" + file_name
      part = MIMEApplication(open(send_file_path, 'rb').read())
      part.add_header('Content-Disposition', 'attachment', filename=file_name)
      msg.attach(part)
  elif isinstance(file_names, str):
    send_file_path = file_dir + "/" + file_names
    part = MIMEApplication(open(send_file_path, 'rb').read())
    part.add_header('Content-Disposition', 'attachment', filename=file_names)
    msg.attach(part)
  # msg['from'],msg['to'] Sender and recipient displayed on the receiver 
  msg['from'] = " Obama @163.com"
  msg['to'] = account
  msg['subject'] = email_title
  try:
    server = smtplib.SMTP()
    server.connect('smtp.163.com')
    server.login(account, password)
    # from_addr: Sending address ; to_addrs: Receiving address ( String list )
    server.sendmail(account, msg['to'].split(), msg.as_string())
  except Exception as e:
    print(e)
#  Get the message title 
def get_email_subject(addr, password):
  #  Set the connection URL , Get pop3 Message read object of protocol 
  read = poplib.POP3('pop.163.com', timeout=3600)
  #  Enter email address and email login password 
  read.user(addr) # 163 Mailbox User Name 
  read.pass_(password) # 163 Client Authorization Password in Mailbox Settings 
  # allEmails = (totalNum, totalSize)
  #  Read mail information ( Total number of messages , Mail size )
  total_num, total_size = read.stat()
  # top(which,howmuch)
  #  Get the latest 1 E-mail ( What number of emails , How many envelopes are obtained )
  top_email = read.top(total_num, 1)
  # print("***** start *****\n The received data is : {}\n***** end *****\n".format(top_email))
  #
  # print("***** start *****\n[ Before decoding ] Initial message content obtained : {}\n***** end *****\n".format(top_email[1]))
  #  Decoding the mail information, and storing the decoded mail information into tmp
  tmp = []
  for s in top_email[1]:
    tmp.append(s.decode())
  # print("***** start *****\n[ After decoding ] The message content of is : {}\n*****  end  *****\n".format(tmp))
  #  Splice the decoded message content into a string 
  email_str = '\n'.join(tmp)
  #  Resolves a string type to Message Type 
  message = email.message_from_string(email_str)
  # print("***** start *****\n"
  #    "[ Before decoding ] The message string content of is : [ Data type ]{}\n{}\n"
  #    "--------------------------------------------\n"
  #    "[ After decoding ] The message string content of is : [ Data type ]{}\n{}\n"
  #    "***** end *****\n"
  #    .format(type(email_str), email_str, type(message), message))
  #  Get the message subject 
  subject_str = message['subject']
  # print("***** start *****\n[ Before decoding ] Message header : {}\n***** end *****\n".format(subject_str))
  subject = decode_header(subject_str)
  # print("***** start *****\n[ After decoding ] Message header : {}\n***** end *****\n".format(subject))
  content = subject[0][0]
  enc_type = subject[0][1]
  if enc_type:
    subject_decode = content.decode(enc_type)
  else:
    subject_decode = content
  return subject_decode, read, total_num

Related articles: