| 28 | |
| 29 | |
| 30 | class DirectImap: |
| 31 | def __init__(self, account: "Account") -> None: |
| 32 | self.account = account |
| 33 | self.logid = account.get_config("displayname") or id(account) |
| 34 | self._idling = False |
| 35 | self.connect() |
| 36 | |
| 37 | def connect(self): |
| 38 | host = self.account.get_config("configured_mail_server") |
| 39 | port = 993 |
| 40 | |
| 41 | user = self.account.get_config("addr") |
| 42 | host = user.rsplit("@")[-1] |
| 43 | pw = self.account.get_config("mail_pw") |
| 44 | |
| 45 | self.conn = MailBox(host, port, ssl_context=ssl.create_default_context()) |
| 46 | self.conn.login(user, pw) |
| 47 | |
| 48 | self.select_folder("INBOX") |
| 49 | |
| 50 | def shutdown(self): |
| 51 | try: |
| 52 | self.conn.logout() |
| 53 | except (OSError, imaplib.IMAP4.abort): |
| 54 | print("Could not logout direct_imap conn") |
| 55 | |
| 56 | def create_folder(self, foldername): |
| 57 | try: |
| 58 | self.conn.folder.create(foldername) |
| 59 | except errors.MailboxFolderCreateError as e: |
| 60 | print("Can't create", foldername, "probably it already exists:", str(e)) |
| 61 | |
| 62 | def select_folder(self, foldername: str) -> tuple: |
| 63 | assert not self._idling |
| 64 | return self.conn.folder.set(foldername) |
| 65 | |
| 66 | def select_config_folder(self, config_name: str): |
| 67 | """Return info about selected folder if it is |
| 68 | configured, otherwise None. |
| 69 | """ |
| 70 | if "_" not in config_name: |
| 71 | config_name = f"configured_{config_name}_folder" |
| 72 | foldername = self.account.get_config(config_name) |
| 73 | if foldername: |
| 74 | return self.select_folder(foldername) |
| 75 | return None |
| 76 | |
| 77 | def list_folders(self) -> List[str]: |
| 78 | """return list of all existing folder names.""" |
| 79 | assert not self._idling |
| 80 | return [folder.name for folder in self.conn.folder.list()] |
| 81 | |
| 82 | def delete(self, uid_list: str, expunge=True): |
| 83 | """delete a range of messages (imap-syntax). |
| 84 | If expunge is true, perform the expunge-operation |
| 85 | to make sure the messages are really gone and not |
| 86 | just flagged as deleted. |
| 87 | """ |