🐛 (mail): No exige remitente con transport log

This commit is contained in:
Manuel Cillero 2026-10-19 07:44:59 +02:00
parent f2a052d66c
commit a9b1b3b2a3
3 changed files with 49 additions and 18 deletions

View file

@ -110,7 +110,8 @@ impl Email {
/// Envía el correo y espera a que se entregue (al servidor SMTP, a *sendmail*, al archivo...). /// Envía el correo y espera a que se entregue (al servidor SMTP, a *sendmail*, al archivo...).
/// ///
/// Falla si alguna dirección o el tipo MIME de algún adjunto no son válidos, si falta el /// Falla si alguna dirección o el tipo MIME de algún adjunto no son válidos, si falta el
/// remitente o los destinatarios, o si la entrega falla. /// remitente (salvo con `transport = "log"`, que sólo escribe el correo en las trazas) o los
/// destinatarios, o si la entrega falla.
pub async fn send(self) -> Result<(), MailError> { pub async fn send(self) -> Result<(), MailError> {
transport::deliver(self).await transport::deliver(self).await
} }
@ -270,9 +271,14 @@ impl Email {
self self
} }
/// Establece el asunto. /// Establece el asunto. Los caracteres de control (saltos de línea, tabuladores...) se cambian
/// por espacios: el asunto puede incluir datos de usuario, y una cabecera es una sola línea.
pub fn with_subject(mut self, subject: impl Into<String>) -> Self { pub fn with_subject(mut self, subject: impl Into<String>) -> Self {
self.subject = subject.into(); self.subject = subject
.into()
.chars()
.map(|c| if c.is_control() { ' ' } else { c })
.collect();
self self
} }

View file

@ -51,6 +51,11 @@ pub(crate) fn mailer() -> Result<&'static Mailer, MailError> {
pub(crate) async fn deliver(email: Email) -> Result<(), MailError> { pub(crate) async fn deliver(email: Email) -> Result<(), MailError> {
let mailer = mailer()?; let mailer = mailer()?;
let email = email.prepare(mailer.from.as_ref(), mailer.reply_to.as_ref()); let email = email.prepare(mailer.from.as_ref(), mailer.reply_to.as_ref());
// Escribirlo en las trazas no necesita remitente: así una aplicación sin configurar muestra sus
// correos aunque no tenga `mail.from`.
if let Transport::Log = mailer.transport {
return log_email(&email, mailer.redirect_to.as_ref());
}
let message = email.to_message()?; let message = email.to_message()?;
let envelope = match &mailer.redirect_to { let envelope = match &mailer.redirect_to {
Some(address) => Envelope::new(message.envelope().from().cloned(), vec![address.clone()]) Some(address) => Envelope::new(message.envelope().from().cloned(), vec![address.clone()])
@ -76,28 +81,46 @@ pub(crate) async fn deliver(email: Email) -> Result<(), MailError> {
.await .await
.map_err(MailError::File)?; .map_err(MailError::File)?;
} }
Transport::Log => {
let body = email
.text()
.cloned()
.or_else(|| email.html().map(|html| html.as_str().to_owned()))
.unwrap_or_default();
trace::info!(
"Email not delivered (mail.transport = \"log\")\n\
From: {}\nTo: {}\nSubject: {}\n\n{}",
email.from().map(ToString::to_string).unwrap_or_default(),
recipients(&envelope).join(", "),
email.subject(),
body
);
}
Transport::Memory => { Transport::Memory => {
outbox::push(email, recipients(&envelope), raw); outbox::push(email, recipients(&envelope), raw);
} }
Transport::Log => unreachable!("log transport is handled before building the message"),
} }
Ok(()) Ok(())
} }
// Escribe el correo en las trazas en lugar de enviarlo (`transport = "log"`). Valida las
// direcciones igual que al enviar, salvo que falte el remitente.
fn log_email(email: &Email, redirect_to: Option<&Address>) -> Result<(), MailError> {
for mailbox in email.from().into_iter().chain(email.reply_to()) {
mailbox.to_lettre()?;
}
let mut recipients = Vec::new();
for mailbox in email.to().iter().chain(email.cc()).chain(email.bcc()) {
recipients.push(mailbox.to_lettre()?.email.to_string());
}
if recipients.is_empty() {
return Err(MailError::NoRecipients);
}
if let Some(address) = redirect_to {
recipients = vec![address.to_string()];
}
let body = email
.text()
.cloned()
.or_else(|| email.html().map(|html| html.as_str().to_owned()))
.unwrap_or_default();
trace::info!(
"Email not delivered (mail.transport = \"log\")\n\
From: {}\nTo: {}\nSubject: {}\n\n{}",
email.from().map(ToString::to_string).unwrap_or_default(),
recipients.join(", "),
email.subject(),
body
);
Ok(())
}
// Completa un correo como si se fuera a enviar, para mostrar su vista previa. Si los ajustes no // Completa un correo como si se fuera a enviar, para mostrar su vista previa. Si los ajustes no
// son válidos (la aplicación no habría arrancado), se muestra sin las direcciones por defecto. // son válidos (la aplicación no habría arrancado), se muestra sin las direcciones por defecto.
pub(crate) fn prepare_preview(email: Email) -> Email { pub(crate) fn prepare_preview(email: Email) -> Email {

View file

@ -79,6 +79,8 @@ async fn control_characters_in_names_cannot_inject_headers() {
.await; .await;
assert_eq!(sent.envelope_to(), &["control@example.com".to_string()]); assert_eq!(sent.envelope_to(), &["control@example.com".to_string()]);
assert!(!sent.raw().contains("\r\nBcc:")); assert!(!sent.raw().contains("\r\nBcc:"));
// A subject is a single line: control characters become spaces.
assert_eq!(sent.email().subject(), "Hi Bcc: evil@example.com");
} }
// **< Composition >******************************************************************************** // **< Composition >********************************************************************************