email_util.py 2.6 KB

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