yzc164 发表于 2018-8-10 11:20:28

Delphi使用Python来解码邮件

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 1 import email  fp = open("Test.eml", "r")#打开eml文件
  msg = email.message_from_file(fp)
  #msg = email.message_from_string(str) #也可以从字符串创建
  subject = msg.get("subject") # 取信件头里的subject, 也就是主题
  # 下面的三行代码只是为了解码象=?gbk?Q?=CF=E0=C6=AC?=这样的subject
  h = email.Header.Header(subject)
  dh = email.Header.decode_header(h)
  subject = dh
  print "subject:", subject
  print "from: ", email.utils.parseaddr(msg.get("from")) # 取from
  print "to: ", email.utils.parseaddr(msg.get("to")) # 取to
  # 循环信件中的每一个mime的数据块
  i=0
  textplain=''
  texthtml=''
  for par in msg.walk():
  if not par.is_multipart(): # 这里要判断是否是multipart,是的话,里面的数据是无用的,至于为什么可以了解mime相关知识。
  name = par.get_param("name") #如果是附件,这里就会取出附件的文件名
  print name
  if name:
  print '有附件'+name#此处略,不对附件做处理,只处理文本内容
  else:
  #不是附件,是文本内容
  #print par.get_payload(decode=True) # 解码出文本内容,直接输出来就可以了。
  content_type=par.get_content_type()
  if content_type in ['text/plain']:
  textplain=par.get_payload(decode=True)
  TextPlain.Value=textplain#这里TextPlain.Value和下面的TextHtml.Value在正常Python中是不能正确执行的,是Pytho4Delphi中的对象
  if content_type in ['text/html']:
  texthtml=par.get_payload(decode=True)
  TextHtml.Value=texthtml
  fp.close()
页: [1]
查看完整版本: Delphi使用Python来解码邮件