python 通过邮件发送附件之企业QQ邮箱

def setmailinfo(self, receiveUser, cc, subject, text, text_type, *attachmentFilePaths):
  # 设置邮件的基本信息(收件人,抄送,主题,正文,附件,可变参数附件路径列表)
  self.msg['From'] = self.mailUser

  # receiveUser cc must be list,[]
  self.msg['To'] = receiveUser
  self.msg['Cc'] = cc

  self.msg['Subject'] = Header(subject, "utf-8")
  self.msg.attach(MIMEText(text, text_type))
  for attachmentFilePath in attachmentFilePaths:

  self.msg.attach(self.getattachmentfromfile(attachmentFilePath))

  # receiver 必须是列表

  receiver = [i for i in self.msg['To'].split(',')] + [k for k in self.msg['Cc'].split(',')]

  self.mailServer.sendmail(self.mailUser, receiver, self.msg.as_string())
  logger.info('Sent email to {0}, Cc {0}'.format(self.msg['To'], self.msg['Cc']))

def getattachmentfromfile(self, attachmentFilePath):
  # 通过路径添加附件
  part = MIMEBase('application', "octet-stream")
  part.set_payload(open(attachmentFilePath, "rb").read())
  encode_base64(part)

  # 指定编码格式, qq邮箱对邮件使用gbk编码,否则可能会出现文件名乱码
  part.add_header('Content-Disposition', 'attachment', filename=("gbk", "", os.path.basename(attachmentFilePath)))
  return part

posted @ 2020-05-21 09:46  进击的pythoner  阅读(238)  评论(0编辑  收藏  举报