mail.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import smtplib
  2. import ssl
  3. from email.mime.text import MIMEText
  4. from email.mime.multipart import MIMEMultipart
  5. from email.mime.application import MIMEApplication
  6. import config
  7. class mail:
  8. mail_cfg2 = config.MailConfig(**{
  9. 'server': 'mail.psmanaged.com',
  10. 'port': '465',
  11. 'secure': 'ssl',
  12. 'username': 'gc@scharf-automobile.de',
  13. 'password': '+Js10TnD*km4E6',
  14. 'email': 'gc@scharf-automobile.de'
  15. })
  16. def __init__(self):
  17. self.cfg = config.config()
  18. self.mail_cfg = self.cfg.smtp
  19. self.reply_to = self.cfg.kunde.replace(' ', '-').lower() + '@global-cube.de'
  20. self.context = ssl.create_default_context()
  21. def __enter__(self):
  22. try:
  23. self.mailserver = smtplib.SMTP_SSL(self.mail_cfg.server, self.mail_cfg.port, context=self.context)
  24. self.mailserver.login(self.mail_cfg.username, self.mail_cfg.password)
  25. except smtplib.SMTPException as e:
  26. print(e)
  27. return self
  28. def __exit__(self, exc_type, exc_val, exc_tb):
  29. self.mailserver.quit()
  30. def send(self, mailto, subject, html, attachment=None):
  31. msg = self.message(mailto, subject, html, attachment)
  32. try:
  33. result = self.mailserver.sendmail(self.reply_to, mailto, msg.as_string())
  34. print(result)
  35. except smtplib.SMTPException as e:
  36. print(e)
  37. def message(self, mailto, subject, html, attachment):
  38. msg = MIMEMultipart('alternative')
  39. msg['Reply-To'] = self.reply_to
  40. msg['From'] = f'Global Cube <{self.mail_cfg.email}>'
  41. msg['To'] = mailto
  42. msg['Subject'] = subject
  43. # msg.attach(MIMEText(text, 'plain'))
  44. msg.attach(MIMEText(html, 'html'))
  45. for name, filename in attachment or []:
  46. with open(filename, "rb") as f:
  47. part = MIMEApplication(f.read(), Name=name)
  48. part['Content-Disposition'] = f'attachment; filename="{name}"'
  49. msg.attach(part)
  50. return msg
  51. if __name__ == '__main__':
  52. with mail() as m:
  53. m.send('robert.bedner@gmail.com', 'Test 123', ['C:\\GAPS\\Portal\\daten\\1_1_Taegliche_Erfolgskontrolle_1.pdf'])