Skip to main content

serenade_mailer/
attachment.rs

1//! Attachment and inline (CID) parts for Mime.
2
3/// How a binary part is presented in the message.
4#[derive(Clone, Copy, Debug, Eq, PartialEq)]
5pub enum ContentDisposition {
6    /// Downloadable attachment (`Content-Disposition: attachment`).
7    Attachment,
8    /// Inline part, usually referenced from HTML via `cid:` (`Content-Disposition: inline`).
9    Inline,
10}
11
12/// File or inline body part (filename + content type + raw bytes).
13#[derive(Clone, Debug, Eq, PartialEq)]
14pub struct Attachment {
15    filename: String,
16    content_type: String,
17    body: Vec<u8>,
18    disposition: ContentDisposition,
19    content_id: Option<String>,
20}
21
22impl Attachment {
23    /// Builds a downloadable attachment from raw bytes.
24    #[must_use]
25    pub fn from_bytes(
26        filename: impl Into<String>,
27        content_type: impl Into<String>,
28        body: impl Into<Vec<u8>>,
29    ) -> Self {
30        Self {
31            filename: filename.into(),
32            content_type: content_type.into(),
33            body: body.into(),
34            disposition: ContentDisposition::Attachment,
35            content_id: None,
36        }
37    }
38
39    /// Builds an inline part with a Content-ID for HTML `cid:` references.
40    ///
41    /// `content_id` should be a token without angle brackets (for example `logo@serenade`).
42    #[must_use]
43    pub fn inline_from_bytes(
44        filename: impl Into<String>,
45        content_type: impl Into<String>,
46        content_id: impl Into<String>,
47        body: impl Into<Vec<u8>>,
48    ) -> Self {
49        Self {
50            filename: filename.into(),
51            content_type: content_type.into(),
52            body: body.into(),
53            disposition: ContentDisposition::Inline,
54            content_id: Some(content_id.into()),
55        }
56    }
57
58    /// Suggested filename.
59    #[must_use]
60    pub fn filename(&self) -> &str {
61        &self.filename
62    }
63
64    /// MIME content type (for example `application/pdf`).
65    #[must_use]
66    pub fn content_type(&self) -> &str {
67        &self.content_type
68    }
69
70    /// Raw attachment bytes.
71    #[must_use]
72    pub fn body(&self) -> &[u8] {
73        &self.body
74    }
75
76    /// Attachment vs inline disposition.
77    #[must_use]
78    pub const fn disposition(&self) -> ContentDisposition {
79        self.disposition
80    }
81
82    /// Content-ID without angle brackets when this part is inline.
83    #[must_use]
84    pub fn content_id(&self) -> Option<&str> {
85        self.content_id.as_deref()
86    }
87
88    /// Whether this part is inline (CID).
89    #[must_use]
90    pub const fn is_inline(&self) -> bool {
91        matches!(self.disposition, ContentDisposition::Inline)
92    }
93}