use crate::{MailError, MailResult};
use lettre::message::{
header::{ContentType, HeaderName, HeaderValue},
Attachment as MimeAttachment, MultiPart, SinglePart,
};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::str::FromStr;
#[derive(Clone)]
pub struct Mailbox(pub(crate) lettre::message::Mailbox);
impl Mailbox {
pub fn parse(value: &str) -> MailResult<Self> {
header_text(value)?;
value.parse().map(Self).map_err(|_| MailError::Address)
}
pub fn new(address: &str, name: Option<String>) -> MailResult<Self> {
header_text(address)?;
if let Some(name) = &name {
header_text(name)?;
}
Ok(Self(lettre::message::Mailbox::new(
name,
address.parse().map_err(|_| MailError::Address)?,
)))
}
pub fn address(&self) -> String {
self.0.email.to_string()
}
}
impl FromStr for Mailbox {
type Err = MailError;
fn from_str(value: &str) -> MailResult<Self> {
Self::parse(value)
}
}
impl Serialize for Mailbox {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.0.to_string().serialize(serializer)
}
}
impl<'de> Deserialize<'de> for Mailbox {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Self::parse(&String::deserialize(deserializer)?).map_err(serde::de::Error::custom)
}
}
impl std::fmt::Debug for Mailbox {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Mailbox([REDACTED])")
}
}
#[derive(Clone)]
pub struct Attachment {
pub(crate) filename: String,
pub(crate) content_type: ContentType,
pub(crate) bytes: Vec<u8>,
}
impl Attachment {
pub fn new(filename: impl Into<String>, mime_type: &str, bytes: Vec<u8>) -> MailResult<Self> {
let filename = filename.into();
header_text(&filename)?;
if filename.is_empty()
|| filename.len() > 255
|| filename.contains(['/', '\\'])
|| bytes.len() > 10 * 1024 * 1024
{
return Err(MailError::Attachment);
}
header_text(mime_type)?;
let content_type = ContentType::parse(mime_type).map_err(|_| MailError::Attachment)?;
Ok(Self {
filename,
content_type,
bytes,
})
}
}
impl std::fmt::Debug for Attachment {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Attachment([REDACTED])")
}
}
#[derive(Clone, Default)]
pub struct Mail {
pub(crate) from: Option<Mailbox>,
pub(crate) to: Vec<Mailbox>,
pub(crate) cc: Vec<Mailbox>,
pub(crate) bcc: Vec<Mailbox>,
pub(crate) reply_to: Option<Mailbox>,
pub(crate) subject: String,
pub(crate) text: Option<String>,
pub(crate) html: Option<String>,
pub(crate) attachments: Vec<Attachment>,
pub(crate) headers: Vec<(String, String)>,
}
impl std::fmt::Debug for Mail {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Mail([REDACTED])")
}
}
impl Mail {
pub fn new(subject: impl Into<String>) -> Self {
Self {
subject: subject.into(),
..Self::default()
}
}
pub fn text(mut self, body: impl Into<String>) -> Self {
self.text = Some(body.into());
self
}
pub fn html(mut self, body: impl Into<String>) -> Self {
self.html = Some(body.into());
self
}
pub fn from(mut self, mailbox: Mailbox) -> Self {
self.from = Some(mailbox);
self
}
pub fn to(mut self, mailbox: Mailbox) -> Self {
self.to.push(mailbox);
self
}
pub fn cc(mut self, mailbox: Mailbox) -> Self {
self.cc.push(mailbox);
self
}
pub fn bcc(mut self, mailbox: Mailbox) -> Self {
self.bcc.push(mailbox);
self
}
pub fn reply_to(mut self, mailbox: Mailbox) -> Self {
self.reply_to = Some(mailbox);
self
}
pub fn attach(mut self, attachment: Attachment) -> Self {
self.attachments.push(attachment);
self
}
pub fn header(mut self, name: &str, value: impl Into<String>) -> MailResult<Self> {
let value = value.into();
validate_header(name, &value)?;
self.headers.push((name.into(), value));
Ok(self)
}
pub(crate) fn build(
self,
default_from: &Mailbox,
max_bytes: usize,
id: &str,
) -> MailResult<lettre::Message> {
header_text(&self.subject)?;
if self.subject.len() > 998
|| self.to.len() + self.cc.len() + self.bcc.len() == 0
|| self.to.len() + self.cc.len() + self.bcc.len() > 100
|| self.attachments.len() > 20
|| self.headers.len() > 32
|| (self.text.is_none() && self.html.is_none())
{
return Err(MailError::Message);
}
let bytes = self
.text
.as_ref()
.map_or(0, String::len)
.saturating_add(self.html.as_ref().map_or(0, String::len));
let bytes = self
.attachments
.iter()
.fold(bytes, |n, a| n.saturating_add(a.bytes.len()));
if bytes > max_bytes {
return Err(MailError::Size);
}
let mut builder = lettre::Message::builder()
.from(self.from.unwrap_or_else(|| default_from.clone()).0)
.subject(self.subject)
.message_id(Some(id.into()));
for recipient in self.to {
builder = builder.to(recipient.0);
}
for recipient in self.cc {
builder = builder.cc(recipient.0);
}
for recipient in self.bcc {
builder = builder.bcc(recipient.0);
}
if let Some(reply) = self.reply_to {
builder = builder.reply_to(reply.0);
}
for (name, value) in self.headers {
validate_header(&name, &value)?;
builder = builder.raw_header(HeaderValue::new(
HeaderName::new_from_ascii(name).map_err(|_| MailError::Header)?,
value,
));
}
let content = match (self.text, self.html) {
(Some(text), Some(html)) => MultiPart::alternative_plain_html(text, html),
(Some(text), None) => MultiPart::mixed().singlepart(SinglePart::plain(text)),
(None, Some(html)) => MultiPart::mixed().singlepart(SinglePart::html(html)),
_ => return Err(MailError::Message),
};
let content = if self.attachments.is_empty() {
content
} else {
self.attachments.into_iter().fold(
MultiPart::mixed().multipart(content),
|parts, attachment| {
parts.singlepart(
MimeAttachment::new(attachment.filename)
.body(attachment.bytes, attachment.content_type),
)
},
)
};
builder.multipart(content).map_err(|_| MailError::Message)
}
}
pub(crate) fn header_text(value: &str) -> MailResult<()> {
if value.chars().any(char::is_control) || value.len() > 4096 {
Err(MailError::Header)
} else {
Ok(())
}
}
fn validate_header(name: &str, value: &str) -> MailResult<()> {
if !name.to_ascii_lowercase().starts_with("x-")
|| name.len() > 78
|| !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
{
return Err(MailError::Header);
}
HeaderName::new_from_ascii(name.into()).map_err(|_| MailError::Header)?;
header_text(value)
}
pub trait Mailable: Send + Sync {
const NAME: &'static str;
fn render(&self) -> MailResult<Mail>;
fn to(self, address: impl AsRef<str>) -> MailResult<Envelope<Self>>
where
Self: Sized,
{
Ok(Envelope {
content: self,
recipient: Mailbox::parse(address.as_ref())?,
})
}
fn to_mailbox(self, recipient: Mailbox) -> Envelope<Self>
where
Self: Sized,
{
Envelope {
content: self,
recipient,
}
}
}
pub struct Envelope<M> {
pub(crate) content: M,
pub(crate) recipient: Mailbox,
}
impl<M> std::fmt::Debug for Envelope<M> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Envelope([REDACTED])")
}
}
pub trait QueueableMail: Mailable {}