SoFunction
Updated on 2024-11-17

Python to batch parse emails and download attachments

The email module in python makes it easy to parse emails, so let's start with the code.

#-*- encoding: gb2312 -*-
import os
import email

def mail_to_text(mailname,datapath,index):
# Since batch emails contain attachments with the same name, pass in an index as a differentiator here.
  fp=open(mailname,"r")
  msg=email.message_from_file(fp)

  for par in ():
    if not par.is_multipart():
      name=par.get_param("name") # Get attachment name

      if name:
        h=(name)
        dh=.decode_header(h)
        fname = dh[0][0]

        data=par.get_payload(decode=True)

        try:
          f=open(fname,'wb')
        except:
          data_name=str(h).replace('/','_') # Annex data
          f=open(datapath+'\\'+str(index)+data_name,'wb')
        (data)
        ()

if __name__=='__main__':
  dir="C:\\Users\\admin\\Desktop\\srcData\\"  # Mail storage path
  Dir=unicode(dir,"utf8")
  datapath="C:\\Users\\admin\\Desktop\\destData"  # Attachment storage path
  DataPath=unicode(datapath,"utf8")
  count=0


  for filename in (dir):
    print filename
    filename=unicode(dir+filename,"utf8")  # As the mail name appears in Chinese, so unified with utf8 encoding, easy to read
    print filename
    count+=1
    mail_to_text(filename,datapath,count)

Notes:Be careful when Chinese characters appear in the email name

This is the whole content of this article.