Skip to main content

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

1//! Create a Microsoft Graph draft message (`POST /me/messages` or
2//! `POST /me/mailFolders/{id}/messages`).
3//!
4//! <https://learn.microsoft.com/en-us/graph/api/user-post-messages>
5
6use alloc::format;
7
8use io_http::rfc6750::bearer::HttpAuthBearer;
9use log::{debug, trace};
10use url::Url;
11
12use crate::{
13    coroutine::*,
14    msgraph_try,
15    v1::{
16        rest::users::messages::MsgraphMessage,
17        send::{
18            MSGRAPH_API_BASE, MsgraphSend, MsgraphSendError, MsgraphSendOutput, path_segment,
19            user_path,
20        },
21    },
22};
23
24/// Creates a Microsoft Graph draft message from JSON.
25pub struct MsgraphMessageCreate {
26    send: MsgraphSend<MsgraphMessage>,
27}
28
29impl MsgraphMessageCreate {
30    /// Creates the draft in the Drafts folder, 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        message: &MsgraphMessage,
37    ) -> Result<Self, MsgraphSendError> {
38        debug!("prepare microsoft graph message for creation");
39        trace!("folder: {folder:?}");
40        trace!("message: {message:?}");
41
42        let user = user_path(user_id)?;
43        let path = match folder {
44            Some(folder) => format!("{user}/mailFolders/{}/messages", path_segment(folder)?),
45            None => format!("{user}/messages"),
46        };
47        let url = Url::parse(MSGRAPH_API_BASE)?.join(&path)?;
48        let send = MsgraphSend::post_json(auth, url, message)?;
49
50        Ok(Self { send })
51    }
52}
53
54impl MsgraphCoroutine for MsgraphMessageCreate {
55    type Yield = MsgraphYield;
56    type Return = Result<MsgraphSendOutput<MsgraphMessage>, MsgraphSendError>;
57
58    fn resume(&mut self, arg: Option<&[u8]>) -> MsgraphCoroutineState<Self::Yield, Self::Return> {
59        let out = msgraph_try!(&mut self.send, arg);
60        debug!("message created");
61        trace!("out: {out:?}");
62        MsgraphCoroutineState::Complete(Ok(out))
63    }
64}