123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- import smtplib
- import ssl
- from dataclasses import dataclass
- from email.mime.application import MIMEApplication
- from email.mime.multipart import MIMEMultipart
- from email.mime.text import MIMEText
- from email.utils import make_msgid
- from pathlib import Path
- @dataclass
- class MailConfig:
- server: str
- port: int
- secure: str
- username: str
- password: str
- email: str
- @dataclass
- class Message:
- mailto: str
- subject: str
- html: str
- attachment: list
- class SmtpMailer:
- connected = False
- def __init__(self, cfg=None):
- if cfg is None:
- cfg = default_cfg
- self.mail_cfg = cfg
- self.reply_to = "versand@global-cube.com"
- self.context = ssl.create_default_context()
- def __enter__(self):
- try:
- if self.mail_cfg.secure == "ssl":
- self.mailserver = smtplib.SMTP_SSL(self.mail_cfg.server, self.mail_cfg.port, context=self.context)
- else:
- self.mailserver = smtplib.SMTP(self.mail_cfg.server, self.mail_cfg.port)
- if self.mail_cfg.secure == "tls":
- self.context.minimum_version = ssl.TLSVersion["TLSv1_2"]
- self.mailserver.ehlo()
- self.mailserver.starttls(context=self.context)
- self.mailserver.login(self.mail_cfg.username, self.mail_cfg.password)
- self.connected = True
- except smtplib.SMTPException as e:
- print(e)
- return self
- def __exit__(self, exc_type, exc_val, exc_tb):
- if self.connected:
- self.mailserver.quit()
- def send(self, mailto, subject, html, attachment=None):
- msg = self.message(mailto, subject, html, attachment)
- msg["Message-ID"] = make_msgid(domain=self.mail_cfg.server)
- # res = {"id": msg["Message-ID"], "mailto": mailto, "status": "OK"}
- try:
- self.mailserver.sendmail(self.mail_cfg.email, mailto, msg.as_string())
- except smtplib.SMTPException as e:
- print(e)
- pass
- def message(self, mailto, subject, html, attachment):
- msg = MIMEMultipart("alternative")
- msg["From"] = self.mail_cfg.email
- msg["To"] = mailto
- msg["Subject"] = subject
- msg.attach(MIMEText(html, "html"))
- for name, filename in attachment or []:
- with open(filename, "rb") as f:
- part = MIMEApplication(f.read(), Name=name)
- part["Content-Disposition"] = f'attachment; filename="{name}"'
- msg.attach(part)
- return msg
- default_cfg = MailConfig(
- server="mail.global-cube.com",
- port=465,
- secure="ssl",
- username="versand",
- password="y6!avXX3tQvr",
- email="versand@global-cube.com",
- )
- if __name__ == "__main__":
- base_dir = str(Path(__file__).parent.parent)
- with SmtpMailer() as m:
- m.send(
- "robert.bedner@gmail.com",
- "Test 1234567",
- "kein Kommentar",
- [
- (
- "Umsatz_Bruttoertrag_Aftersales.pdf",
- base_dir + "/Portal/Publish/daten/gaps_vers_tag/Umsatz_Bruttoertrag_Aftersales_0.pdf",
- )
- ],
- )
|