utils_send_email.py 2.0 KB

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