✨ (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:
parent
9ba493c2c4
commit
d1f3ede963
6 changed files with 443 additions and 6 deletions
207
extensions/pagetop-mail/src/admin.rs
Normal file
207
extensions/pagetop-mail/src/admin.rs
Normal 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)),
|
||||
)
|
||||
}
|
||||
|
|
@ -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:
|
||||
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
|
||||
|
||||
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 use preview::{DeclareMailPreviews, MailPreviews};
|
||||
|
||||
mod admin;
|
||||
pub use admin::MailPermission;
|
||||
|
||||
mod text;
|
||||
|
||||
mod transport;
|
||||
|
|
@ -307,9 +320,21 @@ impl Extension for Mail {
|
|||
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")]
|
||||
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> {
|
||||
|
|
@ -325,13 +350,16 @@ impl Extension for Mail {
|
|||
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 {
|
||||
return router;
|
||||
return routes;
|
||||
}
|
||||
router
|
||||
.route(preview::PREVIEW_PATH, web::get(preview::list_get))
|
||||
.route(
|
||||
routes
|
||||
.public_route(preview::PREVIEW_PATH, web::get(preview::list_get))
|
||||
.public_route(
|
||||
&util::join!(preview::PREVIEW_PATH, "/{key}"),
|
||||
web::get(preview::preview_get),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -20,3 +20,37 @@ preview_attachments = Attachments
|
|||
preview_html = HTML
|
||||
preview_text = Plain text
|
||||
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
|
||||
|
|
|
|||
|
|
@ -20,3 +20,37 @@ preview_attachments = Adjuntos
|
|||
preview_html = HTML
|
||||
preview_text = Texto plano
|
||||
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
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue