email_util.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # coding=utf-8
  2. from email.mime.text import MIMEText
  3. from email.header import Header
  4. from smtplib import SMTP
  5. from email.mime.multipart import MIMEMultipart
  6. from email.mime.base import MIMEBase
  7. from email.encoders import encode_base64
  8. import traceback
  9. import os
  10. # https://blog.csdn.net/chuxu8314/article/details/100618710
  11. class EmailUtil(object):
  12. host_server = 'smtp.qq.com'
  13. sender_email = '1285211525@qq.com'
  14. pwd = 'rstydfukfpzoidgi'
  15. send_name = 'elab'
  16. receiver = ['1285211525@qq.com', 'lijm@elab-plus.com', 'xuanxc@elab-plus.com']
  17. def __init__(self):
  18. pass
  19. def send_mail(self,
  20. mail_title,
  21. content,
  22. receivers,
  23. mail_excel
  24. ):
  25. global smtp
  26. try:
  27. smtp = SMTP(self.host_server)
  28. smtp.set_debuglevel(1)
  29. smtp.ehlo(self.host_server)
  30. smtp.login(self.sender_email, self.pwd)
  31. msg = MIMEMultipart('related')
  32. msg['From'] = self.send_name
  33. msg['Subject'] = Header(mail_title, 'utf-8')
  34. msgAlternative = MIMEMultipart('alternative')
  35. msg.attach(msgAlternative)
  36. if content:
  37. textApart = MIMEText(content)
  38. msg.attach(textApart)
  39. if mail_excel:
  40. part = MIMEBase('application', "vnd.ms-excel")
  41. with open(mail_excel, 'rb') as fp:
  42. part.set_payload(fp.read())
  43. encode_base64(part)
  44. part.add_header('Content-Disposition', f'attachment; filename="{os.path.split(mail_excel)[1]}"')
  45. msg.attach(part)
  46. for receiver in receivers:
  47. msg['To'] = receiver
  48. try:
  49. smtp.sendmail(self.sender_email, receiver, msg.as_string())
  50. except Exception as e:
  51. print(str(e))
  52. smtp.sendmail(self.sender_email, receiver, msg.as_string())
  53. print('Success!')
  54. except Exception as e:
  55. print('Error:{}'.format(str(e)))
  56. traceback.print_exc()
  57. finally:
  58. smtp.quit()
  59. dir_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  60. def send_test(self):
  61. send_email = EmailUtil()
  62. send_email.send_mail('elab_test', '11', ['1285211525@qq.com'],
  63. mail_excel=r'{}/elab_mvp/resources/111.xlsx'.format(self.dir_path))
  64. if __name__ == '__main__':
  65. send_email = EmailUtil()
  66. send_email.send_test()
  67. pass