首页 > 解决方案 > 使用 Python 从邮件中下载附件到 dbfs

问题描述

如果我的主题与今天提到的主题匹配,我在电子邮件中有附件,我想下载这些附件。如果邮件未读,我已经编写了下载附件的代码。但是如果主题匹配并且日期是今天的日期,我想下载邮件是已读还是未读,那么它应该下载附件。

我写了下面的代码:

    def subjectQuery(subject):
m = connect(server, user, password)
m.select("Inbox")
typ, msgs = m.search(None,'(SUBJECT "' + subject + '" UNSEEN)')
msgs = msgs[0].split()
mailparser = HeaderParser()
for emailid in msgs:
  resp, data = m.fetch(emailid, "(BODY.PEEK[])")
  email_body = data[0][1]
  mail = email.message_from_bytes(email_body)
  downloaAttachmentsInEmail(m, emailid, outputdir)
  typ, msgs = m.store(emailid, '+FLAGS','\\SEEN')
  Subject = mail['subject']
  emailidD = emailid
  To = mail['To']
  mailDate = mail['Date']
  From = str(mail['From'])
  Body = str(mail['Body'])
  print("-----------------------")
  print(Subject)
  print(emailidD)
  print(To)
  print(mailDate)
  print(From)
  print(Body)
  ErrorMessage ="Attachement Downloaded successfully"
  print(ErrorMessage)
  print("-----------------------")
  print("Logging is complete for file path: "+outputfilepath)
  CustomloggingEmailAzureDB(DateofExec,CampaignId,ProcessName,Subject,To,From,Body,ProcessStartTime,SucessFailure,ErrorMessage.replace("'",""),CmdNo,NotebookName,NotebookPath,filename,mailDate)

    server = 'outlook.office365.com'
    user = dbutils.secrets.get(scope="keyvault_scope", key="email-svc-acc-global-data")
    password = dbutils.secrets.get(scope="keyvault_scope", key="email-svc-acc-global-data-psw")

    if(subject == "Quality Data"):
      if(filename == "Chat.csv"):
      outputdir = "/dbfs/FileStore/tables/EmailAttachment/Quality_Chat/"
      print(outputdir)
      outputfilepath = outputdir + filename
      print(outputfilepath)
    else:
      print("Error")

标签: pythonemail

解决方案


推荐阅读