✨ (mail): Marca los correos como automáticos
Por defecto, los correos llevan `Auto-Submitted: auto-generated` (RFC 3834) para no recibir avisos de ausencia; `with_auto_submitted(false)` la quita en los que escribe una persona. Añade SentEmail::links() para seguir en las pruebas los enlaces de los correos.
This commit is contained in:
parent
3c6dea9728
commit
d7caf724dd
3 changed files with 110 additions and 4 deletions
|
|
@ -5,6 +5,7 @@ use pagetop::prelude::*;
|
||||||
use crate::{Attachment, MailError, MailTemplate, Mailbox, layout, text, transport};
|
use crate::{Attachment, MailError, MailTemplate, Mailbox, layout, text, transport};
|
||||||
|
|
||||||
use lettre::Message;
|
use lettre::Message;
|
||||||
|
use lettre::message::header::{HeaderName, HeaderValue};
|
||||||
use lettre::message::{MultiPart, MultiPartBuilder, SinglePart};
|
use lettre::message::{MultiPart, MultiPartBuilder, SinglePart};
|
||||||
|
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
|
@ -30,6 +31,10 @@ use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
/// Si no se indica el remitente o la dirección de respuesta se usan los de la configuración
|
/// Si no se indica el remitente o la dirección de respuesta se usan los de la configuración
|
||||||
/// (`mail.from` y `mail.reply_to`). Las direcciones se validan al enviar.
|
/// (`mail.from` y `mail.reply_to`). Las direcciones se validan al enviar.
|
||||||
///
|
///
|
||||||
|
/// Por defecto, los correos llevan la cabecera `Auto-Submitted: auto-generated`: los envía la
|
||||||
|
/// aplicación, no una persona, así que no deben recibir respuestas automáticas (avisos de
|
||||||
|
/// ausencia...). Ver [`with_auto_submitted()`](Self::with_auto_submitted).
|
||||||
|
///
|
||||||
/// # Ejemplo
|
/// # Ejemplo
|
||||||
///
|
///
|
||||||
/// ```rust,no_run
|
/// ```rust,no_run
|
||||||
|
|
@ -74,6 +79,10 @@ pub struct Email {
|
||||||
attachments: Vec<Attachment>,
|
attachments: Vec<Attachment>,
|
||||||
#[getters(skip)]
|
#[getters(skip)]
|
||||||
langid: Option<&'static LanguageIdentifier>,
|
langid: Option<&'static LanguageIdentifier>,
|
||||||
|
/// Si lleva la cabecera `Auto-Submitted: auto-generated` (por defecto, sí).
|
||||||
|
#[default = true]
|
||||||
|
#[getters(copy)]
|
||||||
|
auto_submitted: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Email {
|
impl Email {
|
||||||
|
|
@ -231,10 +240,11 @@ impl Email {
|
||||||
}
|
}
|
||||||
|
|
||||||
let from = from.to_lettre()?;
|
let from = from.to_lettre()?;
|
||||||
let mut builder = Message::builder()
|
let mut builder = Message::builder().message_id(Some(message_id(from.email.domain())));
|
||||||
.message_id(Some(message_id(from.email.domain())))
|
if self.auto_submitted {
|
||||||
.from(from)
|
builder = builder.raw_header(auto_submitted_header());
|
||||||
.subject(self.subject.as_str());
|
}
|
||||||
|
builder = builder.from(from).subject(self.subject.as_str());
|
||||||
if let Some(reply_to) = &self.reply_to {
|
if let Some(reply_to) = &self.reply_to {
|
||||||
builder = builder.reply_to(reply_to.to_lettre()?);
|
builder = builder.reply_to(reply_to.to_lettre()?);
|
||||||
}
|
}
|
||||||
|
|
@ -369,6 +379,20 @@ impl Email {
|
||||||
self.langid = Some(language.langid());
|
self.langid = Some(language.langid());
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Indica si el correo lleva la cabecera `Auto-Submitted: auto-generated` (RFC 3834), que lo
|
||||||
|
/// marca como enviado por un programa. Por defecto la llevan todos: así los contestadores
|
||||||
|
/// automáticos que siguen el RFC (avisos de ausencia, de vacaciones...) no responden a la
|
||||||
|
/// dirección del remitente.
|
||||||
|
///
|
||||||
|
/// Quítala (`false`) en los correos que escribe una persona y que deben tratarse como suyos,
|
||||||
|
/// como los de un formulario de contacto dirigidos a una dirección de soporte: hay sistemas de
|
||||||
|
/// atención al cliente que suspenden o rechazan los correos marcados como automáticos, para no
|
||||||
|
/// abrir incidencias con ellos.
|
||||||
|
pub fn with_auto_submitted(mut self, auto_submitted: bool) -> Self {
|
||||||
|
self.auto_submitted = auto_submitted;
|
||||||
|
self
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Genera la cabecera `Message-ID`, que los filtros de correo no deseado penalizan si falta. Sólo
|
// Genera la cabecera `Message-ID`, que los filtros de correo no deseado penalizan si falta. Sólo
|
||||||
|
|
@ -384,6 +408,14 @@ fn message_id(domain: &str) -> String {
|
||||||
format!("<{nanos:x}.{count:x}.{:x}@{domain}>", std::process::id())
|
format!("<{nanos:x}.{count:x}.{:x}@{domain}>", std::process::id())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Cabecera `Auto-Submitted: auto-generated` (ver `Email::with_auto_submitted()`).
|
||||||
|
fn auto_submitted_header() -> HeaderValue {
|
||||||
|
HeaderValue::new(
|
||||||
|
HeaderName::new_from_ascii_str("Auto-Submitted"),
|
||||||
|
"auto-generated".to_owned(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// Parte de un mensaje MIME: simple o compuesta por otras partes.
|
// Parte de un mensaje MIME: simple o compuesta por otras partes.
|
||||||
enum Part {
|
enum Part {
|
||||||
Single(SinglePart),
|
Single(SinglePart),
|
||||||
|
|
|
||||||
|
|
@ -60,6 +60,41 @@ impl SentEmail {
|
||||||
.iter()
|
.iter()
|
||||||
.any(|to| to.eq_ignore_ascii_case(address.trim()))
|
.any(|to| to.eq_ignore_ascii_case(address.trim()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Devuelve las direcciones de los enlaces del HTML (atributos `href`), en el orden en que
|
||||||
|
/// aparecen y ya sin escapar, para seguirlos en las pruebas (p. ej. un enlace de un solo uso).
|
||||||
|
///
|
||||||
|
/// Incluye los del diseño común, si los tiene. Lee los atributos tal como los genera `html!`,
|
||||||
|
/// entre comillas dobles; los de un documento propio escritos de otra forma no se encuentran.
|
||||||
|
/// Sin HTML devuelve una lista vacía.
|
||||||
|
pub fn links(&self) -> Vec<String> {
|
||||||
|
const ATTR: &str = " href=\"";
|
||||||
|
let Some(html) = self.email.html() else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let mut links = Vec::new();
|
||||||
|
let mut rest = html.as_str();
|
||||||
|
// Con el espacio delante no coinciden otros atributos que acaban igual (`data-href`).
|
||||||
|
while let Some(start) = rest.find(ATTR) {
|
||||||
|
rest = &rest[start + ATTR.len()..];
|
||||||
|
let Some(end) = rest.find('"') else {
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
links.push(unescape(&rest[..end]));
|
||||||
|
rest = &rest[end..];
|
||||||
|
}
|
||||||
|
links
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deshace el escapado de un valor de atributo HTML generado con `html!`.
|
||||||
|
fn unescape(value: &str) -> String {
|
||||||
|
value
|
||||||
|
.replace(""", "\"")
|
||||||
|
.replace("<", "<")
|
||||||
|
.replace(">", ">")
|
||||||
|
.replace("'", "'")
|
||||||
|
.replace("&", "&")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Recoge todos los correos guardados, en el orden en que se enviaron.
|
/// Recoge todos los correos guardados, en el orden en que se enviaron.
|
||||||
|
|
|
||||||
|
|
@ -109,6 +109,9 @@ async fn text_email_uses_default_sender_and_reaches_every_recipient() {
|
||||||
.any(|line| line.starts_with("Message-ID: <") && line.ends_with("@example.com>")),
|
.any(|line| line.starts_with("Message-ID: <") && line.ends_with("@example.com>")),
|
||||||
"Message-ID must use the sender domain"
|
"Message-ID must use the sender domain"
|
||||||
);
|
);
|
||||||
|
// Marks the email as automatic so that out-of-office replies are not sent back.
|
||||||
|
assert!(sent.email().auto_submitted());
|
||||||
|
assert!(sent.raw().contains("Auto-Submitted: auto-generated\r\n"));
|
||||||
assert!(sent.raw().contains("Content-Type: text/plain"));
|
assert!(sent.raw().contains("Content-Type: text/plain"));
|
||||||
// Bcc recipients get the email but must not appear in its headers.
|
// Bcc recipients get the email but must not appear in its headers.
|
||||||
assert!(!sent.raw().contains("text-bcc@example.com"));
|
assert!(!sent.raw().contains("text-bcc@example.com"));
|
||||||
|
|
@ -190,6 +193,42 @@ async fn html_document_is_sent_without_layout() {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn auto_submitted_header_can_be_left_out() {
|
||||||
|
// E.g. a contact form message: some help desks suspend or reject automatic emails.
|
||||||
|
let sent = send_one(
|
||||||
|
Email::new()
|
||||||
|
.with_to("human@example.com")
|
||||||
|
.with_text("Written by a person")
|
||||||
|
.with_auto_submitted(false),
|
||||||
|
"human@example.com",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert!(!sent.raw().contains("Auto-Submitted"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn links_are_extracted_unescaped_in_order() {
|
||||||
|
let sent = send_one(
|
||||||
|
Email::new()
|
||||||
|
.with_to("links@example.com")
|
||||||
|
.with_html_document(html! {
|
||||||
|
html { body {
|
||||||
|
a href="https://example.com/a?x=1&y=2" { "First" }
|
||||||
|
// Other attributes ending in "href" are not links.
|
||||||
|
a data-href="https://example.com/no" href="https://example.com/b" { "Second" }
|
||||||
|
} }
|
||||||
|
}),
|
||||||
|
"links@example.com",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
sent.links(),
|
||||||
|
["https://example.com/a?x=1&y=2", "https://example.com/b"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// **< Attachments >********************************************************************************
|
// **< Attachments >********************************************************************************
|
||||||
|
|
||||||
#[pagetop::test]
|
#[pagetop::test]
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue