✨ (mail): Añade el correo de prueba al panel

Una página del panel muestra la configuración del correo, sin las
credenciales, y envía un correo de prueba esperando el resultado,
para comprobar el transporte en producción. Exige el permiso
`mail:send_test`.
This commit is contained in:
Manuel Cillero 2026-11-07 16:17:05 +01:00
parent 9ba493c2c4
commit d1f3ede963
6 changed files with 443 additions and 6 deletions

View file

@ -172,6 +172,16 @@ extensiones declaran con la acción `DeclareMailPreviews`, y muestra cada uno co
cabeceras, HTML con el diseño común, texto plano y adjuntos, sin enviar nada. Ver el módulo cabeceras, HTML con el diseño común, texto plano y adjuntos, sin enviar nada. Ver el módulo
`preview`. `preview`.
## Correo de prueba desde el panel de administración
`pagetop-mail` añade al panel de administración de PageTop la página **Configuración > Correo
electrónico** (`config/mail`, bajo la raíz del panel). Muestra el transporte, el remitente y el
servidor configurados, nunca las credenciales, y envía un correo de prueba a la dirección que se
indique, esperando al resultado: al volver a la página se ve si se ha enviado o el error del
transporte. Sirve para comprobar la configuración en producción sin enviar correos reales a nadie
más. Exige el permiso `mail:send_test` (`MailPermission::SendTest`), que concede la extensión de
autenticación (p. ej. asignándolo a un rol con `pagetop-user`).
## Texto plano automático ## Texto plano automático
Si un correo sólo tiene HTML, al enviarlo se genera su texto plano a partir del contenido: bloques Si un correo sólo tiene HTML, al enviarlo se genera su texto plano a partir del contenido: bloques

View file

@ -0,0 +1,207 @@
//! Página del panel de administración para comprobar la configuración del correo enviando un correo
//! de prueba.
use pagetop::prelude::*;
use serde::Deserialize;
use crate::config::{self, MailTransport, SmtpSecurity};
use crate::{Email, LOCALES_MAIL, Mailbox};
// Ruta de la página, relativa a la raíz del panel.
const TEST_MAIL: &str = "config/mail";
// **< Permiso >************************************************************************************
/// Permisos propios de `pagetop-mail`.
#[derive(Clone, Copy, Debug)]
pub enum MailPermission {
/// Ver la configuración del correo (sin credenciales) y enviar correos de prueba desde el panel
/// de administración.
SendTest,
}
impl Permission for MailPermission {
fn key(&self) -> CowStr {
match self {
Self::SendTest => "mail:send_test".into(),
}
}
fn label(&self) -> Lc {
match self {
Self::SendTest => Lc::t("perm_send_test", &LOCALES_MAIL),
}
}
fn group(&self) -> &'static str {
"mail"
}
fn group_label(&self) -> Lc {
Lc::t("extension_name", &LOCALES_MAIL)
}
}
pub(crate) fn declare_permissions(registry: &mut PermissionRegistry) {
registry.register(&MailPermission::SendTest);
}
// **< Página del panel >***************************************************************************
pub(crate) fn declare_pages(bag: &mut AdminPageBag) {
bag.add(
AdminPage::new(
TEST_MAIL,
"config",
Lc::t("test_title", &LOCALES_MAIL),
&MailPermission::SendTest,
)
.with_description(Lc::t("test_description", &LOCALES_MAIL)),
);
}
pub(crate) fn configure_router(routes: Routes) -> Routes {
routes.admin_route(TEST_MAIL, web::get(test_mail_get).post(test_mail_post))
}
// Muestra la configuración del correo y el formulario para enviar un correo de prueba.
async fn test_mail_get(request: HttpRequest) -> Result<Markup, ErrorPage> {
let mut page = Page::admin(request).with_title(Lc::t("test_title", &LOCALES_MAIL));
if let Some(warning) = not_delivered_warning() {
page.push_message(MessageLevel::Warning, warning);
}
page.with_child(settings_summary())
.with_child(test_form())
.render()
.await
}
#[derive(Deserialize)]
struct TestMailForm {
to: String,
}
// Envía el correo de prueba y vuelve a la página con el resultado. Espera a la entrega, sin pasar
// por la cola, para poder informar del error del transporte.
async fn test_mail_post(
request: HttpRequest,
web::Form(form): web::Form<TestMailForm>,
) -> Result<Response, ErrorPage> {
let cx = Context::admin(request);
let to = form.to.trim().to_owned();
let back = Redirect::see_other(cx.route(admin_path(TEST_MAIL)));
if Mailbox::new(to.as_str()).validate().is_err() {
let text = Lc::t("test_invalid_address", &LOCALES_MAIL).with_arg("to", to);
return Ok(back.with_message(&cx, MessageLevel::Error, text));
}
let app = global::SETTINGS.app.name.clone();
let subject = Lc::t("test_subject", &LOCALES_MAIL).with_arg("app", app.clone());
let body = Lc::t("test_body", &LOCALES_MAIL).with_arg("app", app);
let result = Email::new()
.with_to(to.as_str())
.with_subject(subject.lookup(&cx).unwrap_or_default())
.with_html(html! { p { (body.using(&cx)) } })
.send()
.await;
Ok(match result {
Ok(()) => {
trace::info!("Test email sent to {to}");
let text = Lc::t("test_sent", &LOCALES_MAIL).with_arg("to", to);
back.with_message(&cx, MessageLevel::Info, text)
}
Err(err) => {
trace::warn!("Test email to {to} failed: {err}");
let text = Lc::t("test_failed", &LOCALES_MAIL).with_arg("error", err.to_string());
back.with_message(&cx, MessageLevel::Error, text)
}
})
}
// Aviso si el transporte configurado no entrega los correos.
fn not_delivered_warning() -> Option<Lc> {
let key = match config::SETTINGS.transport {
MailTransport::Log => "test_log_warning",
MailTransport::Memory => "test_memory_warning",
_ => return None,
};
Some(Lc::t(key, &LOCALES_MAIL))
}
// Ajustes del correo que ayudan a interpretar el resultado de la prueba, nunca las credenciales.
fn settings_summary() -> Block {
let settings = &config::SETTINGS;
let none = || Lc::t("test_not_set", &LOCALES_MAIL);
let text = |value: &Option<String>| value.clone().map_or_else(none, Lc::n);
let transport = match settings.transport {
MailTransport::Smtp => "transport_smtp",
MailTransport::Sendmail => "transport_sendmail",
MailTransport::File => "transport_file",
MailTransport::Log => "transport_log",
MailTransport::Memory => "transport_memory",
};
let mut rows = vec![
("test_transport", Lc::t(transport, &LOCALES_MAIL)),
("test_from", text(&settings.from)),
("test_reply_to", text(&settings.reply_to)),
];
if settings.redirect_to.is_some() {
rows.push(("test_redirect_to", text(&settings.redirect_to)));
}
match settings.transport {
MailTransport::Smtp => {
let smtp = &settings.smtp;
let (security, default_port) = match smtp.security {
SmtpSecurity::None => ("security_none", 25),
SmtpSecurity::Opportunistic => ("security_opportunistic", 25),
SmtpSecurity::StartTls => ("security_starttls", 587),
SmtpSecurity::Tls => ("security_tls", 465),
};
let port = smtp.port.unwrap_or(default_port).to_string();
rows.push(("test_smtp_server", Lc::n(util::join!(smtp.host, ":", port))));
rows.push(("test_smtp_security", Lc::t(security, &LOCALES_MAIL)));
}
MailTransport::Sendmail => {
rows.push(("test_sendmail_command", text(&settings.sendmail.command)));
}
MailTransport::File => {
rows.push(("test_file_dir", Lc::n(settings.file.dir.clone())));
}
MailTransport::Log | MailTransport::Memory => {}
}
let mut table = Table::new();
for (label, value) in rows {
table = table.with_row(
table::Row::new()
.with_cell(Lc::t(label, &LOCALES_MAIL))
.with_cell(value),
);
}
Block::new()
.with_title(Lc::t("test_settings", &LOCALES_MAIL))
.with_child(table)
}
fn test_form() -> Form {
Form::new()
.with_id("mail-test-form")
.with_action(admin_path(TEST_MAIL))
.with_method(form::Method::Post)
.with_child(
form::input::Field::email()
.with_name("to")
.with_label(Lc::t("test_to", &LOCALES_MAIL))
.with_autocomplete(Some(form::Autocomplete::email()))
.with_required(true)
.with_maxlength(254),
)
.with_child(
Button::submit(Lc::t("test_send", &LOCALES_MAIL))
.with_style(button::Style::Solid(Intent::Primary)),
)
}

View file

@ -170,6 +170,16 @@ Con `previews = true` en `[mail]` (sólo en desarrollo), `/mail/preview` lista l
extensiones declaran con la acción [`DeclareMailPreviews`], y muestra cada uno con datos de ejemplo: extensiones declaran con la acción [`DeclareMailPreviews`], y muestra cada uno con datos de ejemplo:
cabeceras, HTML con el diseño común, texto plano y adjuntos, sin enviar nada. Ver [`preview`]. cabeceras, HTML con el diseño común, texto plano y adjuntos, sin enviar nada. Ver [`preview`].
## Correo de prueba desde el panel de administración
`pagetop-mail` añade al panel de administración de PageTop la página **Configuración > Correo
electrónico** (`config/mail`, bajo la raíz del panel). Muestra el transporte, el remitente y el
servidor configurados, nunca las credenciales, y envía un correo de prueba a la dirección que se
indique, esperando al resultado: al volver a la página se ve si se ha enviado o el error del
transporte. Sirve para comprobar la configuración en producción sin enviar correos reales a nadie
más. Exige el permiso `mail:send_test` ([`MailPermission::SendTest`]), que concede la extensión de
autenticación (p. ej. asignándolo a un rol con `pagetop-user`).
## Texto plano automático ## Texto plano automático
Si un correo sólo tiene HTML, al enviarlo se genera su texto plano a partir del contenido: bloques Si un correo sólo tiene HTML, al enviarlo se genera su texto plano a partir del contenido: bloques
@ -273,6 +283,9 @@ pub mod outbox;
pub mod preview; pub mod preview;
pub use preview::{DeclareMailPreviews, MailPreviews}; pub use preview::{DeclareMailPreviews, MailPreviews};
mod admin;
pub use admin::MailPermission;
mod text; mod text;
mod transport; mod transport;
@ -307,9 +320,21 @@ impl Extension for Mail {
vec![&pagetop_seaorm::SeaORM, &pagetop_cron::Cron] vec![&pagetop_seaorm::SeaORM, &pagetop_cron::Cron]
} }
#[cfg(not(feature = "queue"))]
fn actions(&self) -> Vec<ActionBox> {
actions![
action::auth::DeclarePermissions::new(admin::declare_permissions),
action::admin::DeclareAdminPages::new(admin::declare_pages),
]
}
#[cfg(feature = "queue")] #[cfg(feature = "queue")]
fn actions(&self) -> Vec<ActionBox> { fn actions(&self) -> Vec<ActionBox> {
actions![pagetop_cron::DeclareCronJobs::new(queue::declare_jobs)] actions![
action::auth::DeclarePermissions::new(admin::declare_permissions),
action::admin::DeclareAdminPages::new(admin::declare_pages),
pagetop_cron::DeclareCronJobs::new(queue::declare_jobs),
]
} }
fn settings(&self) -> Option<&'static dyn LoadSettings> { fn settings(&self) -> Option<&'static dyn LoadSettings> {
@ -325,13 +350,16 @@ impl Extension for Mail {
Ok(()) Ok(())
} }
fn configure_router(&self, router: Router) -> Router { fn configure_router(&self, routes: Routes) -> Routes {
let routes = admin::configure_router(routes);
// Las vistas previas son públicas: sólo se montan con `mail.previews`, pensado para el
// desarrollo y que avisa al arrancar, y muestran los correos con datos de ejemplo.
if !config::SETTINGS.previews { if !config::SETTINGS.previews {
return router; return routes;
} }
router routes
.route(preview::PREVIEW_PATH, web::get(preview::list_get)) .public_route(preview::PREVIEW_PATH, web::get(preview::list_get))
.route( .public_route(
&util::join!(preview::PREVIEW_PATH, "/{key}"), &util::join!(preview::PREVIEW_PATH, "/{key}"),
web::get(preview::preview_get), web::get(preview::preview_get),
) )

View file

@ -20,3 +20,37 @@ preview_attachments = Attachments
preview_html = HTML preview_html = HTML
preview_text = Plain text preview_text = Plain text
preview_none = None preview_none = None
# **< Test email >**
perm_send_test = Send test emails from the administration panel
test_title = Email
test_description = Delivery settings and test email.
test_settings = Current settings
test_transport = Transport
test_from = Sender
test_reply_to = Reply to
test_redirect_to = Every email is delivered to
test_smtp_server = SMTP server
test_smtp_security = Security
test_sendmail_command = Program
test_file_dir = Directory
test_not_set = Not set
test_to = Send a test email to
test_send = Send test email
test_subject = Test email from { $app }
test_body = This email confirms that { $app } can send messages with the current settings.
test_sent = Test email sent to { $to }.
test_failed = The test email could not be sent: { $error }
test_invalid_address = "{ $to }" is not a valid email address.
test_log_warning = With the current transport emails are not sent: they are written to the logs.
test_memory_warning = With the current transport emails are not sent: they are kept in memory.
transport_smtp = SMTP
transport_sendmail = sendmail program
transport_file = .eml files
transport_log = Logs (not sent)
transport_memory = Memory (not sent)
security_none = Unencrypted
security_opportunistic = STARTTLS if the server supports it
security_starttls = STARTTLS required
security_tls = TLS from the connection

View file

@ -20,3 +20,37 @@ preview_attachments = Adjuntos
preview_html = HTML preview_html = HTML
preview_text = Texto plano preview_text = Texto plano
preview_none = Ninguno preview_none = Ninguno
# **< Correo de prueba >**
perm_send_test = Enviar correos de prueba desde el panel de administración
test_title = Correo electrónico
test_description = Configuración del envío y correo de prueba.
test_settings = Configuración actual
test_transport = Transporte
test_from = Remitente
test_reply_to = Responder a
test_redirect_to = Todos los correos se entregan a
test_smtp_server = Servidor SMTP
test_smtp_security = Seguridad
test_sendmail_command = Programa
test_file_dir = Directorio
test_not_set = Sin configurar
test_to = Enviar un correo de prueba a
test_send = Enviar correo de prueba
test_subject = Correo de prueba de { $app }
test_body = Este correo confirma que { $app } puede enviar mensajes con la configuración actual.
test_sent = Correo de prueba enviado a { $to }.
test_failed = No se pudo enviar el correo de prueba: { $error }
test_invalid_address = «{ $to }» no es una dirección de correo válida.
test_log_warning = Con el transporte actual los correos no se envían: se escriben en las trazas.
test_memory_warning = Con el transporte actual los correos no se envían: se guardan en memoria.
transport_smtp = SMTP
transport_sendmail = Programa sendmail
transport_file = Archivos .eml
transport_log = Trazas (no se envía)
transport_memory = Memoria (no se envía)
security_none = Sin cifrar
security_opportunistic = STARTTLS si el servidor lo admite
security_starttls = STARTTLS obligatorio
security_tls = TLS desde la conexión

View file

@ -0,0 +1,124 @@
// The test email page of the administration panel. `config/common.toml` keeps the emails in
// memory. Nothing in this binary manages permissions, so `grant()` plays the authentication
// extension: it grants every permission to the requests sent with the `x-grant` header.
//
// The scenarios run one after another in a single test: with the `queue` feature, starting the
// application installs the queue migrations, and starting it from parallel tests would install
// them at the same time on the same in-memory database.
use pagetop::prelude::*;
struct TestApp;
#[async_trait]
impl Extension for TestApp {
fn dependencies(&self) -> Vec<ExtensionRef> {
vec![&pagetop_mail::Mail]
}
fn actions(&self) -> Vec<ActionBox> {
actions![action::auth::CheckPermission::new(grant)]
}
}
fn grant(request: &HttpRequest, _: PermissionRef, granted: &mut bool) {
if request.headers().contains_key("x-grant") {
*granted = true;
}
}
async fn app() -> Router {
web::test::init_router(Application::prepare(&TestApp).await.test())
}
async fn send(app: &Router, request: web::test::TestRequest) -> (u16, String, String) {
let response = web::test::send_request(app, request.to_request()).await;
let status = response.status().as_u16();
let header = |name| {
response
.headers()
.get(name)
.and_then(|value| value.to_str().ok())
.unwrap_or_default()
.to_owned()
};
let (location, cookie) = (header("location"), header("set-cookie"));
let _ = web::test::read_body_text(response).await;
(status, location, cookie)
}
fn post(to: &str) -> web::test::TestRequest {
web::test::TestRequest::post()
.uri("/admin/config/mail")
.header("x-grant", "yes")
.form(format!("to={to}"))
}
#[pagetop::test]
async fn test_email_page() {
let app = app().await;
the_page_and_its_permission_are_declared();
the_page_shows_the_settings_without_credentials_and_the_form(&app).await;
without_the_permission_the_page_is_denied(&app).await;
a_test_email_is_sent_and_reported(&app).await;
an_invalid_address_sends_nothing(&app).await;
}
fn the_page_and_its_permission_are_declared() {
let page = AdminRegistry::global().page("config/mail").unwrap();
assert_eq!(page.section(), "config");
assert_eq!(page.permission().key(), "mail:send_test");
assert!(PermissionRegistry::global().has_key("mail:send_test"));
}
async fn the_page_shows_the_settings_without_credentials_and_the_form(app: &Router) {
let request = web::test::TestRequest::get()
.uri("/admin/config/mail")
.header("x-grant", "yes")
.to_request();
let response = web::test::send_request(app, request).await;
assert_eq!(response.status().as_u16(), 200);
let html = web::test::read_body_text(response).await;
assert!(
html.contains("PageTop Tests &lt;tests@example.com&gt;"),
"{html}"
);
assert!(html.contains(r#"id="mail-test-form""#), "{html}");
assert!(html.contains(r#"action="/admin/config/mail""#), "{html}");
assert!(html.contains(r#"name="to""#), "{html}");
}
async fn without_the_permission_the_page_is_denied(app: &Router) {
let get = web::test::TestRequest::get().uri("/admin/config/mail");
assert_eq!(send(app, get).await.0, 403);
let post = web::test::TestRequest::post()
.uri("/admin/config/mail")
.form("to=nobody@example.com");
assert_eq!(send(app, post).await.0, 403);
assert!(pagetop_mail::outbox::take_to("nobody@example.com").is_empty());
}
async fn a_test_email_is_sent_and_reported(app: &Router) {
let (status, location, cookie) = send(app, post("admin@example.com")).await;
assert_eq!(status, 303);
assert_eq!(location, "/admin/config/mail");
// An information message for the next page.
assert!(
cookie.starts_with("pagetop_flash=iTest%20email%20sent%20to%20admin%40example.com"),
"{cookie}"
);
let sent = pagetop_mail::outbox::take_to("admin@example.com");
assert_eq!(sent.len(), 1);
let subject = sent[0].email().subject();
assert!(subject.contains("PageTop"), "{subject}");
}
async fn an_invalid_address_sends_nothing(app: &Router) {
let (status, location, cookie) = send(app, post("not-an-address")).await;
assert_eq!(status, 303);
assert_eq!(location, "/admin/config/mail");
// An error message for the next page.
assert!(cookie.starts_with("pagetop_flash=e"), "{cookie}");
assert!(pagetop_mail::outbox::take_to("not-an-address").is_empty());
}