email_utils.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #!/usr/bin/env /usr/bin/python3
  2. # -*- coding:utf-8 -*-
  3. import os
  4. import smtplib
  5. from email.header import Header
  6. from email.mime.multipart import MIMEMultipart
  7. from email.mime.text import MIMEText
  8. from typing import Union, List
  9. from dw_base.utils.file_utils import get_abs_path
  10. class EmailHandler(object):
  11. def __init__(self, smtp_server: str, smtp_port: int, username: str, password: str):
  12. self.smtp_server = smtp_server
  13. self.smtp_port = smtp_port
  14. self.username = username
  15. self.password = password
  16. def send_email(self,
  17. to: Union[List[str], str],
  18. cc: Union[List[str], str],
  19. subject: str,
  20. content: str,
  21. attachments: Union[List[str], str]):
  22. smtp = smtplib.SMTP(self.smtp_server, self.smtp_port)
  23. smtp.login(self.username, self.password)
  24. if isinstance(to, list):
  25. to = ','.join(to)
  26. if cc and isinstance(cc, list):
  27. cc = ','.join(cc)
  28. if not attachments:
  29. attachments = []
  30. elif isinstance(attachments, str):
  31. attachments = attachments.split(',')
  32. message = MIMEMultipart()
  33. message['From'] = self.username
  34. message['To'] = to
  35. if cc:
  36. message['Cc'] = cc
  37. message['Subject'] = Header(subject, 'utf-8').encode()
  38. if content:
  39. # 添加文本
  40. message.attach(MIMEText(content, 'plain', 'utf-8'))
  41. # 添加附件
  42. for file_path in attachments:
  43. self.add_attachment(message, file_path)
  44. smtp.sendmail(self.username, to, message.as_string(unixfrom=True))
  45. smtp.quit()
  46. # @staticmethod
  47. # def add_attachment(message: MIMEMultipart, file_path: str):
  48. # local_file = get_abs_path(file_path)
  49. # file_name = os.path.basename(file_path)
  50. # with open(local_file, 'r') as f:
  51. # # 第二个
  52. # mime = MIMEBase('text', 'txt', filename=file_name)
  53. # # 加上必要的头信息:
  54. # mime.add_header('Content-Disposition', 'attachment', filename=file_name)
  55. # # mime.add_header('Content-ID', '<0>')
  56. # # mime.add_header('X-Attachment-Id', '0')
  57. # # 把附件的内容读进来:
  58. # mime.set_payload(f.read())
  59. # # 用Base64编码:
  60. # encoders.encode_base64(mime)
  61. # # 添加到MIMEMultipart:
  62. # message.attach(mime)
  63. @staticmethod
  64. def add_attachment(message: MIMEMultipart, file_path: str):
  65. local_file = get_abs_path(file_path)
  66. file_name = os.path.basename(file_path)
  67. with open(local_file, 'r', encoding='utf-8') as f:
  68. mime_text = MIMEText(f.read(), 'base64', 'utf-8')
  69. mime_text["Content-Type"] = 'application/octet-stream'
  70. mime_text["Content-Disposition"] = 'attachment; filename=%s' % file_name
  71. message.attach(mime_text)
  72. if __name__ == '__main__':
  73. pass