Skip to content

Instantly share code, notes, and snippets.

@brccabral
Last active August 22, 2024 00:46
Show Gist options
  • Save brccabral/838a0ef1a72bb300a8d397157a55e69e to your computer and use it in GitHub Desktop.
Save brccabral/838a0ef1a72bb300a8d397157a55e69e to your computer and use it in GitHub Desktop.
Python Email
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
class Email:
def __init__(self, from_: str, to: list[str], subject: str):
self.from_ = from_
self.to = to
self.subject = subject
self.message = MIMEMultipart()
self.body = ""
def add_text(self, text: str):
self.body += text
def send(
self, smtp_server="mail.t-mobile.com", port=25, password: str | None = None
):
result = False
self.message["From"] = self.from_
self.message["To"] = ", ".join(self.to) if isinstance(self.to, list) else self.to
self.message["Subject"] = self.subject
if self.body:
self.message.attach(MIMEText(self.body, "html"))
# Send the email
try:
server = smtplib.SMTP(smtp_server, port)
server.starttls() # Secure the connection
if password:
server.login(self.from_, password)
server.sendmail(self.from_, self.to, self.message.as_string())
result = True
except Exception:
result = False
finally:
server.quit()
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment