email_sender.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on 2020/2/19 12:57 PM
  4. ---------
  5. @summary: 邮件发送
  6. ---------
  7. @author: Boris
  8. @email: boris_liu@foxmail.com
  9. """
  10. import os
  11. import smtplib
  12. from email.header import Header
  13. from email.mime.multipart import MIMEMultipart
  14. from email.mime.text import MIMEText
  15. from email.utils import formataddr
  16. from feapder.utils.log import log
  17. class EmailSender(object):
  18. SENDER = "feapder报警系统"
  19. def __init__(self, username, password, smtpserver="smtp.163.com"):
  20. self.username = username
  21. self.password = password
  22. self.smtpserver = smtpserver
  23. self.smtp_client = smtplib.SMTP_SSL(smtpserver)
  24. self.sender = EmailSender.SENDER
  25. def __enter__(self):
  26. self.login()
  27. return self
  28. def __exit__(self, exc_type, exc_val, exc_tb):
  29. self.quit()
  30. def quit(self):
  31. self.smtp_client.quit()
  32. def login(self):
  33. self.smtp_client.connect(self.smtpserver)
  34. self.smtp_client.login(self.username, self.password)
  35. def send(
  36. self,
  37. receivers: list,
  38. title: str,
  39. content: str,
  40. content_type: str = "plain",
  41. filepath: str = None,
  42. ):
  43. """
  44. Args:
  45. receivers:
  46. title:
  47. content:
  48. content_type: html / plain
  49. filepath:
  50. Returns:
  51. """
  52. # 创建一个带附件的实例
  53. message = MIMEMultipart()
  54. message["From"] = formataddr(
  55. (self.sender, self.username)
  56. ) # 括号里的对应发件人邮箱昵称、发件人邮箱账号
  57. message["To"] = formataddr((receivers[0], receivers[0])) # ",".join(receivers)
  58. message["Subject"] = Header(title, "utf-8")
  59. content = MIMEText(content, content_type, "utf-8")
  60. message.attach(content)
  61. # 构造附件
  62. if filepath:
  63. attach = MIMEText(open(filepath, "rb").read(), "base64", "utf-8")
  64. attach.add_header(
  65. "content-disposition",
  66. "attachment",
  67. filename=("utf-8", "", os.path.basename(filepath)),
  68. )
  69. message.attach(attach)
  70. msg = message.as_string()
  71. # 此处直接发送多个邮箱有问题,改成一个个发送
  72. for receiver in receivers:
  73. log.debug("发送邮件到 {}".format(receiver))
  74. self.smtp_client.sendmail(self.username, receiver, msg)
  75. log.debug("邮件发送成功!!!")
  76. return True