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, vec::Vec};
9
10use base64_codec::codec::Base64Codec;
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::{
21            MSGRAPH_API_BASE, MsgraphSend, MsgraphSendError, MsgraphSendOutput, path_segment,
22            user_path,
23        },
24    },
25};
26
27/// Creates a Microsoft Graph draft message from raw RFC 5322 MIME.
28pub struct MsgraphMessageCreateMime {
29    send: MsgraphSend<MsgraphMessage>,
30}
31
32impl MsgraphMessageCreateMime {
33    /// Creates the draft in the mailbox root, or in `folder` when given
34    /// (a folder id or a well-known name such as `drafts`).
35    pub fn new(
36        auth: &HttpAuthBearer,
37        user_id: &str,
38        folder: Option<&str>,
39        raw: &[u8],
40    ) -> Result<Self, MsgraphSendError> {
41        debug!("prepare microsoft graph message creation (mime)");
42        trace!("folder: {folder:?}");
43        trace!("raw len: {}", raw.len());
44
45        let user = user_path(user_id)?;
46        let path = match folder {
47            Some(folder) => format!("{user}/mailFolders/{}/messages", path_segment(folder)?),
48            None => format!("{user}/messages"),
49        };
50        let url = Url::parse(MSGRAPH_API_BASE)?.join(&path)?;
51        let mut body = Vec::new();
52        Base64Codec::default().encode_vec(raw, &mut body);
53
54        let send = MsgraphSend::post_text(auth, url, body);
55
56        Ok(Self { send })
57    }
58}
59
60impl MsgraphCoroutine for MsgraphMessageCreateMime {
61    type Yield = MsgraphYield;
62    type Return = Result<MsgraphSendOutput<MsgraphMessage>, MsgraphSendError>;
63
64    fn resume(&mut self, arg: Option<&[u8]>) -> MsgraphCoroutineState<Self::Yield, Self::Return> {
65        let out = msgraph_try!(&mut self.send, arg);
66        debug!("message created (mime)");
67        trace!("out: {out:?}");
68        MsgraphCoroutineState::Complete(Ok(out))
69    }
70}