email_util.py 2.2 KB

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