tools_send_email.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # -*- coding: UTF-8 -*-
  2. import smtplib
  3. from email.mime.text import MIMEText
  4. from email.header import Header
  5. import tools_load_config
  6. config_json = tools_load_config.load_config()
  7. base_project = tools_load_config.get_base_path()
  8. PROJECT_NAME = config_json.get('PROJECT_NAME')
  9. DB_USER = config_json.get('DB_USER')
  10. DB_PASSWORD = config_json.get('DB_PASSWORD')
  11. DB_IP = config_json.get('DB_IP')
  12. DB_PORT = config_json.get('DB_PORT')
  13. MONGO_LINK = f'mongodb://{DB_USER}:{DB_PASSWORD}@{DB_IP}:{DB_PORT}/'
  14. MAIL_HOST = config_json.get('MAIL_HOST')
  15. MAIL_USER = config_json.get('MAIL_USER')
  16. MAIL_PASS = config_json.get('MAIL_PASS')
  17. MAIL_SENDER = config_json.get('MAIL_SENDER')
  18. MAIL_RECEIVERS = config_json.get('MAIL_RECEIVERS')
  19. class SendEmail(object):
  20. def __init__(self, subject='auto subject', title='auto title', text='auto text') -> None:
  21. # 第三方 SMTP 服务
  22. self.mail_host = MAIL_HOST # 设置服务器
  23. self.mail_user = MAIL_USER # 用户名
  24. self.mail_pass = MAIL_PASS # 口令
  25. self.sender = MAIL_SENDER
  26. self.receivers = [MAIL_RECEIVERS]
  27. self.subject = subject
  28. self.title = title
  29. self.text = text
  30. def send(self):
  31. message = MIMEText(self.text, 'plain', 'utf-8')
  32. message['From'] = Header(self.title, 'utf-8')
  33. message['To'] = Header("auto", 'utf-8')
  34. message['Subject'] = Header(self.subject, 'utf-8')
  35. try:
  36. smtpObj = smtplib.SMTP()
  37. smtpObj.connect(self.mail_host, 25)
  38. smtpObj.login(self.mail_user, self.mail_pass)
  39. smtpObj.sendmail(self.sender, self.receivers, message.as_string())
  40. print("邮件发送成功")
  41. except smtplib.SMTPException:
  42. print("Error: 无法发送邮件")