Commit 6a715414 authored by Benjamin Krause's avatar Benjamin Krause
Browse files

Implement mail provider and useful classes.

parent c3da3290
from pydantic import BaseModel
class Mail(BaseModel):
date: str
subject: str
mail_from: str
mail_to: str
cc: str
body: str
import email
import imaplib
import smtplib
from email.message import EmailMessage
from pydantic import BaseModel
from app.mail import Mail
from app.user import User
from app.utils import subject_identifier
class MailProvider(BaseModel):
base_url: str
imap_url: str
smtp_url: str
smtp_port: int
def send_mail(self, from_user: User, to_user: User, message: EmailMessage):
try:
with smtplib.SMTP(self.smtp_url, self.smtp_port) as server:
server.ehlo()
server.starttls()
server.login(from_user.mail, from_user.password)
server.sendmail(from_user.mail, to_user.mail, message.as_string())
return True
except Exception as e:
print(e)
return False
def get_mailboxes(self, user: User):
imap = imaplib.IMAP4_SSL(self.imap_url)
imap.login(user.mail, user.password)
mailboxes = imap.list()
print(mailboxes)
def search_relevant_mails(self, user: User, mailbox: str):
if not mailbox:
print("Specified mailbox is invalid.")
return
if not user or not user.mail or not user.password:
print("Missing or invalid user data")
return
imap = imaplib.IMAP4_SSL(self.imap_url)
imap.login(user.mail, user.password)
imap.select(mailbox)
status, messages = imap.search(None, f"Subject {subject_identifier}")
if messages[0] == b"":
print(f"No messages with the subject {subject_identifier} found!")
return
messages = len(messages[0].decode("utf-8").split(" "))
mails = []
for i in range(messages, 0, -1):
res, msg = imap.fetch(str(i), "(RFC822)")
for response in msg:
if isinstance(response, tuple):
msg = email.message_from_bytes(response[1])
mails.append(
Mail(
date=msg.get("date"),
subject=msg.get("subject"),
mail_from=msg.get("from"),
mail_to=msg.get("to"),
cc=msg.get("cc"),
body=msg.get_payload(decode=True).decode(),
)
)
imap.close()
imap.logout()
return mails
from pydantic import BaseModel
class User(BaseModel):
mail: str
password: str
from datetime import datetime
subject_identifier = "#ba_subject"
def get_mail_formatted_date():
x = datetime.now()
return x.strftime("%a, %d %b %Y %H:%M:%S +0200")
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment