Skip to main content

io_msgraph/v1/rest/users/messages/
create_mime.rs

1//! Create a Microsoft Graph message from raw MIME (`POST /me/messages`
2//! or `POST /me/mailFolders/{folder}/messages`); the MIME is
3//! base64-encoded and posted as `text/plain`, as Graph requires, and the
4//! created draft message resource is returned.
5//!
6//! <https://learn.microsoft.com/en-us/graph/api/user-post-messages>
7
8use alloc::format;
9
10use base64::{Engine, engine::general_purpose::STANDARD};
11use io_http::rfc6750::bearer::HttpAuthBearer;
12use log::{debug, trace};
13use url::Url;
14
15use crate::{
16    coroutine::*,
17    msgraph_try,
18    v1::{
19        rest::users::messages::MsgraphMessage,
20        send::{MSGRAPH_API_BASE, MsgraphSend, MsgraphSendError, MsgraphSendOutput, user_path},
21    },
22};
23
24/// Creates a Microsoft Graph draft message from raw RFC 5322 MIME.
25pub struct MsgraphMessageCreateMime {
26    send: MsgraphSend<MsgraphMessage>,
27}
28
29impl MsgraphMessageCreateMime {
30    /// Creates the draft in the mailbox root, or in `folder` when given
31    /// (a folder id or a well-known name such as `drafts`).
32    pub fn new(
33        auth: &HttpAuthBearer,
34        user_id: &str,
35        folder: Option<&str>,
36        raw: &[u8],
37    ) -> Result<Self, MsgraphSendError> {
38        debug!("prepare microsoft graph message creation (mime)");
39        trace!("folder: {folder:?}");
40        trace!("raw len: {}", raw.len());
41
42        let user = user_path(user_id);
43        let path = match folder {
44            Some(folder) => format!("{user}/mailFolders/{folder}/messages"),
45            None => format!("{user}/messages"),
46        };
47        let url = Url::parse(MSGRAPH_API_BASE)?.join(&path)?;
48        let body = STANDARD.encode(raw).into_bytes();
49        let send = MsgraphSend::post_text(auth, url, body);
50
51        Ok(Self { send })
52    }
53}
54
55impl MsgraphCoroutine for MsgraphMessageCreateMime {
56    type Yield = MsgraphYield;
57    type Return = Result<MsgraphSendOutput<MsgraphMessage>, MsgraphSendError>;
58
59    fn resume(&mut self, arg: Option<&[u8]>) -> MsgraphCoroutineState<Self::Yield, Self::Return> {
60        let out = msgraph_try!(&mut self.send, arg);
61        debug!("message created (mime)");
62        trace!("out: {out:?}");
63        MsgraphCoroutineState::Complete(Ok(out))
64    }
65}