mail_provider.py 2.38 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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