email_util.py 2.5 KB

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