email_util.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # coding=utf-8
  2. import smtplib
  3. from email.mime.text import MIMEText
  4. from email.header import Header
  5. from smtplib import SMTP_SSL
  6. from email.mime.image import MIMEImage
  7. from email.mime.multipart import MIMEMultipart
  8. from email.mime.application import MIMEApplication
  9. from email.mime.base import MIMEBase
  10. from email.encoders import encode_base64
  11. import traceback
  12. import os
  13. class EmailUtil(object):
  14. host_server = 'smtp.exmail.qq.com'
  15. sender_email = 'zhangbr@elab-plus.com'
  16. pwd = '306492mnA'
  17. send_name = 'elab'
  18. receiver = ['1285211525@qq.com', '15773153135@163.com']
  19. def __init__(self):
  20. pass
  21. def send_mail(self,
  22. mail_title='elab-test',
  23. content=None,
  24. mail_excel=None
  25. ):
  26. try:
  27. smtp = SMTP_SSL(self.host_server)
  28. smtp.set_debuglevel(1)
  29. smtp.ehlo(self.host_server)
  30. smtp.login(self.sender_email, self.pwd)
  31. msg = MIMEMultipart('related')
  32. msg['Subject'] = Header(mail_title, 'utf-8')
  33. msg['From'] = self.send_name
  34. msgAlternative = MIMEMultipart('alternative')
  35. msg.attach(msgAlternative)
  36. if content:
  37. textApart = MIMEText(content)
  38. msg.attach(textApart)
  39. if mail_excel:
  40. part = MIMEBase('application', "vnd.ms-excel")
  41. with open(mail_excel, 'rb') as fp:
  42. part.set_payload(fp.read())
  43. encode_base64(part)
  44. part.add_header('Content-Disposition', f'attachment; filename="{os.path.split(mail_excel)[1]}"')
  45. msg.attach(part)
  46. for mail in self.receiver:
  47. msg['To'] = mail
  48. try:
  49. print(mail)
  50. smtp.sendmail(self.sender_email, mail, msg.as_string())
  51. except Exception as e:
  52. smtp.sendmail(self.sender_email, mail, msg.as_string())
  53. print(str(e))
  54. smtp.quit()
  55. print('Success!')
  56. except:
  57. print('Error!')
  58. traceback.print_exc()
  59. if __name__ == '__main__':
  60. send_email = EmailUtil()
  61. send_email.send_mail('elab_test', mail_excel=r'D:\elab\elab_mvp\resources\tongce1.xlsx')
  62. pass