Skip to main content

rusted_mail/api/
sessions.rs

1//! Owned IMAP/SMTP and JMAP session handles.
2
3use super::*;
4
5/// Owned IMAP/SMTP session.
6///
7/// Call [`close`](Self::close) to perform a clean IMAP logout. Dropping a live
8/// session still removes it from the engine so handles cannot leak.
9#[derive(Debug)]
10#[must_use = "dropping the session immediately closes its engine handle"]
11pub struct ImapSession {
12    pub(super) id: i64,
13    pub(super) closed: bool,
14}
15
16// Every operation forwards protocol, validation, or closed-session failures as
17// the crate's documented `Error`; repeating that text on each thin method adds
18// no method-specific information.
19#[allow(clippy::missing_errors_doc)]
20impl ImapSession {
21    /// Returns the internal session identifier used in diagnostic logs.
22    #[must_use]
23    pub fn id(&self) -> i64 {
24        self.id
25    }
26
27    /// Lists all visible mailboxes.
28    pub async fn list_mailboxes(&self) -> Result<Vec<MailboxInfo>, Error> {
29        crate::session::list_mailboxes(self.id).await
30    }
31
32    /// Lists mailboxes to which the account is subscribed.
33    pub async fn list_subscribed_mailboxes(&self) -> Result<Vec<MailboxInfo>, Error> {
34        crate::session::list_subscribed_mailboxes(self.id).await
35    }
36
37    /// Discovers common folders such as Sent, Drafts, Trash, and Archive.
38    pub async fn special_folders(&self) -> Result<SpecialFolders, Error> {
39        crate::session::discover_special_folders(self.id).await
40    }
41
42    /// Returns advertised IMAP capabilities, optionally refreshing them.
43    pub async fn capabilities(&self, refresh: bool) -> Result<ImapCapabilities, Error> {
44        crate::session::capabilities(self.id, refresh).await
45    }
46
47    /// Returns message counts and UID state for a mailbox.
48    pub async fn mailbox_stats(&self, mailbox: impl Into<String>) -> Result<MailboxStats, Error> {
49        crate::session::mailbox_stats(self.id, mailbox.into()).await
50    }
51
52    /// Selects a mailbox for subsequent stateful operations.
53    pub async fn select_mailbox(
54        &self,
55        mailbox: impl Into<String>,
56        read_only: bool,
57    ) -> Result<MailboxStatus, Error> {
58        crate::session::select_mailbox(self.id, mailbox.into(), read_only).await
59    }
60
61    /// Fetches typed message summaries.
62    pub async fn fetch(&self, options: FetchOptions) -> Result<Vec<MessageSummary>, Error> {
63        crate::session::fetch_messages(self.id, to_json(&options)?).await
64    }
65
66    /// Fetches and parses a complete message body by UID.
67    pub async fn fetch_body(&self, uid: u32, options: BodyOptions) -> Result<MessageBody, Error> {
68        crate::session::fetch_message_body(self.id, uid, to_json(&options)?).await
69    }
70
71    /// Fetches one decoded attachment by its zero-based body attachment index.
72    pub async fn fetch_attachment(
73        &self,
74        uid: u32,
75        index: usize,
76        options: BodyOptions,
77    ) -> Result<AttachmentData, Error> {
78        crate::session::fetch_attachment(self.id, uid, index, to_json(&options)?).await
79    }
80
81    /// Searches a mailbox and returns matching UIDs.
82    pub async fn search(&self, options: SearchOptions) -> Result<Vec<u32>, Error> {
83        crate::session::search_messages(self.id, to_json(&options)?).await
84    }
85
86    /// Marks a set of messages as read or unread.
87    pub async fn mark_read(&self, messages: &MessageSet, read: bool) -> Result<(), Error> {
88        crate::session::mark_read(self.id, to_json(messages)?, read).await?;
89        Ok(())
90    }
91
92    /// Adds or removes an arbitrary IMAP flag on a set of messages.
93    pub async fn set_flag(
94        &self,
95        messages: &MessageSet,
96        flag: impl Into<String>,
97        enabled: bool,
98    ) -> Result<(), Error> {
99        crate::session::flag_messages(self.id, to_json(messages)?, flag.into(), enabled).await?;
100        Ok(())
101    }
102
103    /// Moves messages to another mailbox.
104    pub async fn move_messages(
105        &self,
106        messages: &MessageSet,
107        target_mailbox: impl Into<String>,
108    ) -> Result<(), Error> {
109        crate::session::move_messages(self.id, to_json(messages)?, target_mailbox.into()).await?;
110        Ok(())
111    }
112
113    /// Copies messages to another mailbox.
114    pub async fn copy_messages(
115        &self,
116        messages: &MessageSet,
117        target_mailbox: impl Into<String>,
118    ) -> Result<CopyResult, Error> {
119        crate::session::copy_messages(self.id, to_json(messages)?, target_mailbox.into()).await
120    }
121
122    /// Moves messages to the account's discovered Archive mailbox.
123    pub async fn archive(&self, messages: &MessageSet) -> Result<(), Error> {
124        crate::session::archive_messages(self.id, to_json(messages)?).await?;
125        Ok(())
126    }
127
128    /// Moves messages to the account's discovered Spam or Junk mailbox.
129    pub async fn mark_spam(&self, messages: &MessageSet) -> Result<(), Error> {
130        crate::session::mark_spam(self.id, to_json(messages)?).await?;
131        Ok(())
132    }
133
134    /// Moves messages to the account's discovered Trash mailbox.
135    pub async fn move_to_trash(&self, messages: &MessageSet) -> Result<(), Error> {
136        crate::session::move_to_trash(self.id, to_json(messages)?).await?;
137        Ok(())
138    }
139
140    /// Marks messages as deleted and optionally expunges them immediately.
141    pub async fn delete_messages(&self, messages: &MessageSet, expunge: bool) -> Result<(), Error> {
142        crate::session::delete_messages(self.id, to_json(messages)?, expunge).await?;
143        Ok(())
144    }
145
146    /// Sends a message through the account's SMTP server.
147    pub async fn send(&self, message: Message) -> Result<SendResult, Error> {
148        crate::session::send_mail(self.id, to_json(&message)?).await
149    }
150
151    /// Sends a message and appends it to the discovered Sent mailbox.
152    pub async fn send_and_save(&self, message: Message) -> Result<SendAndSaveResult, Error> {
153        crate::session::send_and_save(self.id, to_json(&message)?).await
154    }
155
156    /// Creates a mailbox.
157    pub async fn create_mailbox(&self, mailbox: impl Into<String>) -> Result<(), Error> {
158        crate::session::create_mailbox(self.id, mailbox.into()).await?;
159        Ok(())
160    }
161
162    /// Deletes a mailbox.
163    pub async fn delete_mailbox(&self, mailbox: impl Into<String>) -> Result<(), Error> {
164        crate::session::delete_mailbox(self.id, mailbox.into()).await?;
165        Ok(())
166    }
167
168    /// Renames a mailbox.
169    pub async fn rename_mailbox(
170        &self,
171        from: impl Into<String>,
172        to: impl Into<String>,
173    ) -> Result<(), Error> {
174        crate::session::rename_mailbox(self.id, from.into(), to.into()).await?;
175        Ok(())
176    }
177
178    /// Changes a mailbox subscription.
179    pub async fn set_subscribed(
180        &self,
181        mailbox: impl Into<String>,
182        subscribed: bool,
183    ) -> Result<(), Error> {
184        crate::session::subscribe_mailbox(self.id, mailbox.into(), subscribed).await?;
185        Ok(())
186    }
187
188    /// Logs out and closes the session.
189    pub async fn close(mut self) -> Result<(), Error> {
190        crate::session::close_session(self.id).await?;
191        self.closed = true;
192        Ok(())
193    }
194}
195
196impl Drop for ImapSession {
197    fn drop(&mut self) {
198        if !self.closed {
199            crate::session::discard_session(self.id);
200        }
201    }
202}
203
204/// Owned JMAP session.
205#[derive(Debug)]
206#[must_use = "dropping the session immediately closes its engine handle"]
207pub struct JmapSession {
208    pub(super) id: i64,
209    pub(super) default_account_id: String,
210    pub(super) closed: bool,
211}
212
213#[allow(clippy::missing_errors_doc)]
214impl JmapSession {
215    /// Returns the internal session identifier used in diagnostic logs.
216    #[must_use]
217    pub fn id(&self) -> i64 {
218        self.id
219    }
220
221    /// Returns the active JMAP account identifier.
222    #[must_use]
223    pub fn default_account_id(&self) -> &str {
224        &self.default_account_id
225    }
226
227    /// Returns current server session metadata.
228    pub async fn session_info(&self) -> Result<JmapSessionInfo, Error> {
229        crate::jmap::jmap_session_info(self.id).await
230    }
231
232    /// Refreshes JMAP discovery metadata.
233    pub async fn refresh(&self) -> Result<JmapSessionInfo, Error> {
234        crate::jmap::jmap_refresh_session(self.id).await
235    }
236
237    /// Lists all JMAP mailboxes sorted by name.
238    pub async fn list_mailboxes(&self) -> Result<Vec<JmapMailbox>, Error> {
239        crate::jmap::jmap_list_mailboxes(self.id, r#"{"sortByName":true}"#.to_string()).await
240    }
241
242    /// Returns a mailbox by JMAP identifier.
243    pub async fn get_mailbox(&self, id: impl Into<String>) -> Result<JmapMailbox, Error> {
244        crate::jmap::jmap_get_mailbox(self.id, id.into()).await
245    }
246
247    /// Creates a mailbox, optionally beneath a parent mailbox.
248    pub async fn create_mailbox(
249        &self,
250        name: impl Into<String>,
251        parent_id: Option<String>,
252    ) -> Result<JmapMailbox, Error> {
253        #[derive(Serialize)]
254        #[serde(rename_all = "camelCase")]
255        struct Request {
256            name: String,
257            parent_id: Option<String>,
258            role: Option<String>,
259        }
260        crate::jmap::jmap_create_mailbox(
261            self.id,
262            to_json(&Request {
263                name: name.into(),
264                parent_id,
265                role: None,
266            })?,
267        )
268        .await
269    }
270
271    /// Renames a mailbox and returns the updated representation when supplied
272    /// by the server.
273    pub async fn rename_mailbox(
274        &self,
275        id: impl Into<String>,
276        name: impl Into<String>,
277    ) -> Result<Option<JmapMailbox>, Error> {
278        crate::jmap::jmap_rename_mailbox(self.id, id.into(), name.into()).await
279    }
280
281    /// Deletes a mailbox, optionally deleting messages that would become
282    /// mailbox-less.
283    pub async fn delete_mailbox(
284        &self,
285        id: impl Into<String>,
286        delete_emails: bool,
287    ) -> Result<(), Error> {
288        crate::jmap::jmap_delete_mailbox(self.id, id.into(), delete_emails).await?;
289        Ok(())
290    }
291
292    /// Fetches an email by JMAP identifier.
293    pub async fn get_email(&self, id: impl Into<String>) -> Result<JmapEmail, Error> {
294        crate::jmap::jmap_get_email(self.id, id.into()).await
295    }
296
297    /// Queries email identifiers using typed filters.
298    pub async fn query_emails(&self, query: JmapEmailQuery) -> Result<JmapQueryResult, Error> {
299        crate::jmap::jmap_query_emails(self.id, to_json(&query)?).await
300    }
301
302    /// Adds or removes a JMAP keyword on an email.
303    pub async fn set_email_keyword(
304        &self,
305        id: impl Into<String>,
306        keyword: impl Into<String>,
307        enabled: bool,
308    ) -> Result<Option<JmapEmail>, Error> {
309        crate::jmap::jmap_set_email_keyword(self.id, id.into(), keyword.into(), enabled).await
310    }
311
312    /// Replaces the mailbox membership of an email.
313    pub async fn set_email_mailboxes(
314        &self,
315        id: impl Into<String>,
316        mailbox_ids: impl IntoIterator<Item = String>,
317    ) -> Result<Option<JmapEmail>, Error> {
318        #[derive(Serialize)]
319        #[serde(rename_all = "camelCase")]
320        struct Request {
321            mailbox_ids: Vec<String>,
322        }
323        crate::jmap::jmap_set_email_mailboxes(
324            self.id,
325            id.into(),
326            to_json(&Request {
327                mailbox_ids: mailbox_ids.into_iter().collect(),
328            })?,
329        )
330        .await
331    }
332
333    /// Removes an email from the account.
334    pub async fn destroy_email(&self, id: impl Into<String>) -> Result<(), Error> {
335        crate::jmap::jmap_destroy_email(self.id, id.into()).await?;
336        Ok(())
337    }
338
339    /// Closes the JMAP session.
340    pub async fn close(mut self) -> Result<(), Error> {
341        crate::jmap::jmap_close_session(self.id).await?;
342        self.closed = true;
343        Ok(())
344    }
345}
346
347impl Drop for JmapSession {
348    fn drop(&mut self) {
349        if !self.closed {
350            crate::jmap::discard_jmap_session(self.id);
351        }
352    }
353}