✨ (mail): Añade la extensión pagetop-mail
Envío de correo con lettre: plantillas con diseño y versión en texto, adjuntos, transporte configurable y vista previa de mensajes.
This commit is contained in:
parent
b3a7d40930
commit
ce9635f9a8
25 changed files with 3508 additions and 0 deletions
|
|
@ -11,6 +11,7 @@ members = [
|
||||||
"extensions/pagetop-bootsier",
|
"extensions/pagetop-bootsier",
|
||||||
"extensions/pagetop-htmx",
|
"extensions/pagetop-htmx",
|
||||||
"extensions/pagetop-admin",
|
"extensions/pagetop-admin",
|
||||||
|
"extensions/pagetop-mail",
|
||||||
"extensions/pagetop-seaorm",
|
"extensions/pagetop-seaorm",
|
||||||
"extensions/pagetop-user",
|
"extensions/pagetop-user",
|
||||||
]
|
]
|
||||||
|
|
@ -40,6 +41,7 @@ grass = "0.13"
|
||||||
indexmap = "2.14"
|
indexmap = "2.14"
|
||||||
indoc = "2.0"
|
indoc = "2.0"
|
||||||
itoa = "1.0"
|
itoa = "1.0"
|
||||||
|
lettre = { version = "0.11", default-features = false }
|
||||||
mime_guess = "2.0"
|
mime_guess = "2.0"
|
||||||
minify-js = "0.6"
|
minify-js = "0.6"
|
||||||
parking_lot = "0.12"
|
parking_lot = "0.12"
|
||||||
|
|
@ -75,6 +77,7 @@ pagetop-admin = { version = "0.1", path = "extensions/pagetop-admin" }
|
||||||
pagetop-aliner = { version = "0.1", path = "extensions/pagetop-aliner" }
|
pagetop-aliner = { version = "0.1", path = "extensions/pagetop-aliner" }
|
||||||
pagetop-bootsier = { version = "0.1", path = "extensions/pagetop-bootsier" }
|
pagetop-bootsier = { version = "0.1", path = "extensions/pagetop-bootsier" }
|
||||||
pagetop-htmx = { version = "0.1", path = "extensions/pagetop-htmx" }
|
pagetop-htmx = { version = "0.1", path = "extensions/pagetop-htmx" }
|
||||||
|
pagetop-mail = { version = "0.1", path = "extensions/pagetop-mail" }
|
||||||
pagetop-seaorm = { version = "0.0", path = "extensions/pagetop-seaorm" }
|
pagetop-seaorm = { version = "0.0", path = "extensions/pagetop-seaorm" }
|
||||||
pagetop-user = { version = "0.1", path = "extensions/pagetop-user" }
|
pagetop-user = { version = "0.1", path = "extensions/pagetop-user" }
|
||||||
# PageTop
|
# PageTop
|
||||||
|
|
|
||||||
|
|
@ -113,6 +113,49 @@ db_host = "localhost" # Servidor de la base de datos (mysql/postgr
|
||||||
max_pool_size = 5 # Número máximo de conexiones simultáneas.
|
max_pool_size = 5 # Número máximo de conexiones simultáneas.
|
||||||
|
|
||||||
|
|
||||||
|
# **< pagetop-mail >********************************************************************************
|
||||||
|
|
||||||
|
[mail]
|
||||||
|
transport = "log" # Entrega de los correos:
|
||||||
|
# "smtp" -> servidor SMTP ([mail.smtp]).
|
||||||
|
# "sendmail" -> programa sendmail local ([mail.sendmail]).
|
||||||
|
# "file" -> un archivo .eml por correo ([mail.file]).
|
||||||
|
# "log" -> se escriben en las trazas, sin enviarlos.
|
||||||
|
# "memory" -> se guardan en memoria (sólo pruebas).
|
||||||
|
#from = "Mi Aplicación <no-reply@example.com>"
|
||||||
|
# Remitente por defecto, con o sin nombre. Sin valor, cada
|
||||||
|
# correo debe indicar el suyo.
|
||||||
|
#reply_to = "soporte@example.com" # Dirección de respuesta por defecto.
|
||||||
|
#redirect_to = "pruebas@example.com" # Entrega todos los correos sólo a esta dirección, sin
|
||||||
|
# cambiar sus cabeceras (entornos de pruebas o preproducción).
|
||||||
|
#base_url = "https://example.com" # URL pública para los enlaces de los correos. Sin valor,
|
||||||
|
# http://{bind_address}:{bind_port} (sólo para desarrollo).
|
||||||
|
previews = false # Vistas previas de los correos en /mail/preview. Sólo en
|
||||||
|
# desarrollo: cualquiera que conozca la ruta las ve.
|
||||||
|
|
||||||
|
[mail.smtp] # Servidor SMTP (transport = "smtp").
|
||||||
|
host = "localhost" # Servidor.
|
||||||
|
#port = 587 # Puerto. Sin valor -> 465 con "tls", 587 con "starttls" y 25
|
||||||
|
# en otro caso.
|
||||||
|
security = "starttls" # Cifrado de la conexión:
|
||||||
|
# "none" -> sin cifrar (servidores de pruebas).
|
||||||
|
# "opportunistic" -> STARTTLS si el servidor lo ofrece.
|
||||||
|
# "starttls" -> STARTTLS obligatorio (puerto 587).
|
||||||
|
# "tls" -> cifrada desde el inicio (puerto 465).
|
||||||
|
#username = "no-reply@example.com" # Usuario. Sin valor, no se autentica.
|
||||||
|
#password = "secreto" # Contraseña. Mejor en config/local.toml (no se versiona).
|
||||||
|
#hello_name = "example.com" # Nombre para EHLO. Sin valor, el nombre del equipo.
|
||||||
|
timeout_secs = 60 # Espera máxima de cada orden al servidor, en segundos.
|
||||||
|
pool_max_size = 10 # Conexiones abiertas como máximo, reutilizadas entre envíos.
|
||||||
|
accept_invalid_certs = false # Acepta certificados no válidos. PELIGROSO: sólo pruebas.
|
||||||
|
|
||||||
|
[mail.sendmail] # Programa sendmail (transport = "sendmail").
|
||||||
|
#command = "/usr/sbin/sendmail" # Programa. Sin valor, "sendmail" del PATH.
|
||||||
|
|
||||||
|
[mail.file] # Archivos de correo (transport = "file").
|
||||||
|
dir = "mail" # Directorio de los archivos .eml. Se crea si no existe.
|
||||||
|
|
||||||
|
|
||||||
# **< pagetop-user >********************************************************************************
|
# **< pagetop-user >********************************************************************************
|
||||||
|
|
||||||
[user]
|
[user]
|
||||||
|
|
|
||||||
35
extensions/pagetop-mail/Cargo.toml
Normal file
35
extensions/pagetop-mail/Cargo.toml
Normal file
|
|
@ -0,0 +1,35 @@
|
||||||
|
[package]
|
||||||
|
name = "pagetop-mail"
|
||||||
|
version = "0.1.0"
|
||||||
|
|
||||||
|
description = """
|
||||||
|
Envío de correo electrónico para aplicaciones PageTop: SMTP, plantillas, HTML y adjuntos.
|
||||||
|
"""
|
||||||
|
categories = ["email", "web-programming"]
|
||||||
|
keywords = ["pagetop", "email", "smtp", "mail", "ssr"]
|
||||||
|
|
||||||
|
repository.workspace = true
|
||||||
|
homepage.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
authors.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
pagetop.workspace = true
|
||||||
|
mime_guess.workspace = true
|
||||||
|
serde.workspace = true
|
||||||
|
thiserror.workspace = true
|
||||||
|
tokio.workspace = true
|
||||||
|
|
||||||
|
[dependencies.lettre]
|
||||||
|
workspace = true
|
||||||
|
features = [
|
||||||
|
"builder",
|
||||||
|
"hostname",
|
||||||
|
"pool",
|
||||||
|
"smtp-transport",
|
||||||
|
"sendmail-transport",
|
||||||
|
"file-transport",
|
||||||
|
"tokio1-native-tls",
|
||||||
|
]
|
||||||
201
extensions/pagetop-mail/LICENSE-APACHE
Normal file
201
extensions/pagetop-mail/LICENSE-APACHE
Normal file
|
|
@ -0,0 +1,201 @@
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright 2026 Manuel Cillero
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
21
extensions/pagetop-mail/LICENSE-MIT
Normal file
21
extensions/pagetop-mail/LICENSE-MIT
Normal file
|
|
@ -0,0 +1,21 @@
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Manuel Cillero
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
228
extensions/pagetop-mail/README.md
Normal file
228
extensions/pagetop-mail/README.md
Normal file
|
|
@ -0,0 +1,228 @@
|
||||||
|
<div align="center">
|
||||||
|
|
||||||
|
<h1>PageTop Mail</h1>
|
||||||
|
|
||||||
|
<p>Envío de correo electrónico para aplicaciones <strong>PageTop</strong>.</p>
|
||||||
|
|
||||||
|
[](https://docs.rs/pagetop-mail)
|
||||||
|
[](https://crates.io/crates/pagetop-mail)
|
||||||
|
[](https://crates.io/crates/pagetop-mail)
|
||||||
|
[](https://git.cillero.es/manuelcillero/pagetop/src/branch/main/extensions/pagetop-mail#licencia)
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
Envía correos en texto plano y HTML, con archivos adjuntos e imágenes incrustadas, por SMTP, con el
|
||||||
|
programa *sendmail* o a archivos `.eml`, todo configurado en los archivos TOML de la aplicación.
|
||||||
|
Los correos pueden crearse con plantillas que traducen sus textos al idioma del destinatario, y
|
||||||
|
comparten un diseño HTML común que la aplicación puede cambiar. Para las pruebas, los correos pueden
|
||||||
|
guardarse en memoria en lugar de enviarse.
|
||||||
|
|
||||||
|
## Sobre PageTop
|
||||||
|
|
||||||
|
[PageTop](https://docs.rs/pagetop) es un entorno de desarrollo que reivindica la esencia de la web
|
||||||
|
clásica para crear soluciones web SSR (*renderizadas en el servidor*) modulares, extensibles y
|
||||||
|
configurables, basadas en HTML, CSS y JavaScript.
|
||||||
|
|
||||||
|
## Guía rápida
|
||||||
|
|
||||||
|
**Añade la dependencia** a tu `Cargo.toml`:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[dependencies]
|
||||||
|
pagetop-mail = "..."
|
||||||
|
```
|
||||||
|
|
||||||
|
**Declara la extensión** en tu aplicación o en la extensión que envíe correos:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
|
struct MyApp;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Extension for MyApp {
|
||||||
|
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||||
|
vec![&pagetop_mail::Mail]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Configura el envío** en la sección `[mail]` (todas las opciones en el módulo `config`):
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[mail]
|
||||||
|
transport = "smtp"
|
||||||
|
from = "Mi Aplicación <no-reply@example.com>"
|
||||||
|
base_url = "https://example.com"
|
||||||
|
|
||||||
|
[mail.smtp]
|
||||||
|
host = "smtp.example.com"
|
||||||
|
security = "starttls" # "none", "opportunistic", "starttls" o "tls".
|
||||||
|
username = "no-reply@example.com"
|
||||||
|
password = "secreto" # Mejor en config/local.toml, que no se versiona.
|
||||||
|
```
|
||||||
|
|
||||||
|
Sin configurar, los correos se escriben en las trazas en lugar de enviarse (`transport = "log"`),
|
||||||
|
así que una aplicación en desarrollo nunca envía correo real por error. La configuración se valida
|
||||||
|
al arrancar: un ajuste no válido detiene la aplicación con un mensaje que indica el problema.
|
||||||
|
|
||||||
|
**Envía un correo** con `Email`:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
use pagetop_mail::prelude::*;
|
||||||
|
|
||||||
|
async fn notify() -> Result<(), MailError> {
|
||||||
|
Email::new()
|
||||||
|
.with_to("Ana Pérez <ana@example.com>")
|
||||||
|
.with_subject("Tu pedido ha salido")
|
||||||
|
.with_text("Tu pedido 1234 ha salido hoy.")
|
||||||
|
.with_html(html! {
|
||||||
|
p { "Tu pedido " strong { "1234" } " ha salido hoy." }
|
||||||
|
})
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`Email::send()` espera a que el correo se entregue; `Email::send_later()` lo envía en segundo plano
|
||||||
|
y registra en las trazas los errores.
|
||||||
|
|
||||||
|
## Plantillas
|
||||||
|
|
||||||
|
Una `MailTemplate` genera el asunto, el HTML y el texto de un correo a partir de sus datos, con los
|
||||||
|
textos traducidos mediante `Lc` al idioma del contexto que recibe. Así, cada extensión define sus
|
||||||
|
correos como tipos propios, y el mismo correo se envía a cada destinatario en su idioma:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
use pagetop_mail::prelude::*;
|
||||||
|
|
||||||
|
include_locales!(LOCALES_SHOP);
|
||||||
|
|
||||||
|
struct Welcome {
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MailTemplate for Welcome {
|
||||||
|
fn subject(&self, cx: &Context) -> String {
|
||||||
|
Lc::t("welcome-subject", &LOCALES_SHOP).lookup(cx).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn html(&self, cx: &Context) -> Option<Markup> {
|
||||||
|
let greeting = Lc::t("welcome-greeting", &LOCALES_SHOP).with_arg("name", self.name.clone());
|
||||||
|
Some(html! {
|
||||||
|
p { (greeting.using(cx)) }
|
||||||
|
p {
|
||||||
|
a href=(absolute_url("/shop")) { (Lc::t("welcome-visit", &LOCALES_SHOP).using(cx)) }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn welcome(request: HttpRequest) -> Result<(), MailError> {
|
||||||
|
// El contexto de la petición: el correo sale en el idioma de quien se acaba de registrar.
|
||||||
|
let cx = Context::new(request);
|
||||||
|
Email::from_template(&Welcome { name: "Ana".to_string() }, &cx)
|
||||||
|
.with_to("ana@example.com")
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Enlaces en los correos
|
||||||
|
|
||||||
|
Los enlaces de un correo deben ser absolutos. `absolute_url()` antepone a una ruta la URL pública de
|
||||||
|
la aplicación, que se configura en `mail.base_url`. No se deduce de la petición, porque la cabecera
|
||||||
|
`Host` la elige el cliente y un atacante podría hacer que los enlaces de un correo de recuperación
|
||||||
|
de contraseña apuntaran a su propio servidor.
|
||||||
|
|
||||||
|
## Adjuntos e imágenes incrustadas
|
||||||
|
|
||||||
|
Un `Attachment` se crea con un contenido en memoria o leyendo un archivo, y su tipo MIME se deduce
|
||||||
|
del nombre. Con `Attachment::with_content_id()` se incrusta en el HTML, que lo muestra con `cid:`:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
use pagetop_mail::prelude::*;
|
||||||
|
|
||||||
|
async fn report(png: Vec<u8>) -> Result<(), MailError> {
|
||||||
|
Email::new()
|
||||||
|
.with_to("ana@example.com")
|
||||||
|
.with_subject("Informe")
|
||||||
|
.with_html(html! { img src="cid:logo" alt="Logo"; p { "Adjunto el informe." } })
|
||||||
|
.with_attachment(Attachment::new("logo.png", png).with_content_id("logo"))
|
||||||
|
.with_attachment(Attachment::from_path("informes/octubre.pdf").await?)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Diseño común del HTML
|
||||||
|
|
||||||
|
El HTML de los correos es sólo su contenido: al enviarlos se envuelve en un documento con un diseño
|
||||||
|
sobrio y neutro. La aplicación puede darle su propia imagen a **todos** los correos, incluidos los
|
||||||
|
de otras extensiones, registrando la acción `RenderMailLayout`.
|
||||||
|
|
||||||
|
## Vistas previas en el navegador
|
||||||
|
|
||||||
|
Con `previews = true` en `[mail]` (sólo en desarrollo), `/mail/preview` lista los correos que las
|
||||||
|
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.
|
||||||
|
|
||||||
|
## Texto plano automático
|
||||||
|
|
||||||
|
Si un correo sólo tiene HTML, al enviarlo se genera su texto plano a partir del contenido: bloques
|
||||||
|
separados por líneas, listas con guiones, y la dirección de cada enlace entre paréntesis.
|
||||||
|
|
||||||
|
## Transportes
|
||||||
|
|
||||||
|
Se elige en `mail.transport`:
|
||||||
|
|
||||||
|
| Valor | Uso |
|
||||||
|
|--------------|-----------------------------------------------------------------------------|
|
||||||
|
| `"smtp"` | Producción. Servidor SMTP con conexiones reutilizables y cifrado TLS. |
|
||||||
|
| `"sendmail"` | Producción, con un servidor de correo local (Postfix, Exim...). |
|
||||||
|
| `"file"` | Desarrollo. Guarda cada correo como `.eml` para abrirlo con un cliente. |
|
||||||
|
| `"log"` | Por defecto. Escribe los correos en las trazas, sin enviarlos. |
|
||||||
|
| `"memory"` | Pruebas. Guarda los correos en memoria para comprobarlos con `outbox`. |
|
||||||
|
|
||||||
|
En entornos de pruebas con datos reales, `mail.redirect_to` entrega todos los correos a una sola
|
||||||
|
dirección, sin cambiar sus cabeceras.
|
||||||
|
|
||||||
|
Para probar el envío SMTP en desarrollo sin enviar correo real, un servidor como
|
||||||
|
[Mailpit](https://mailpit.axllent.org) recoge los correos y los muestra en el navegador:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[mail]
|
||||||
|
transport = "smtp"
|
||||||
|
|
||||||
|
[mail.smtp]
|
||||||
|
host = "localhost"
|
||||||
|
port = 1025
|
||||||
|
security = "none"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Créditos
|
||||||
|
|
||||||
|
Este *crate* se apoya en [lettre](https://lettre.rs), la biblioteca de correo de referencia en Rust,
|
||||||
|
distribuida bajo licencia [MIT](https://github.com/lettre/lettre/blob/master/LICENSE).
|
||||||
|
|
||||||
|
## Advertencia
|
||||||
|
|
||||||
|
**PageTop** es un proyecto personal para aprender [Rust](https://www.rust-lang.org/es) y conocer su
|
||||||
|
ecosistema. Su API está sujeta a cambios frecuentes. No se recomienda su uso en producción, al menos
|
||||||
|
hasta que se libere la versión **1.0.0**.
|
||||||
|
|
||||||
|
## Licencia
|
||||||
|
|
||||||
|
El código está disponible bajo una doble licencia:
|
||||||
|
|
||||||
|
* **Licencia MIT**
|
||||||
|
([LICENSE-MIT](LICENSE-MIT) o también https://opensource.org/licenses/MIT)
|
||||||
|
|
||||||
|
* **Licencia Apache, Versión 2.0**
|
||||||
|
([LICENSE-APACHE](LICENSE-APACHE) o también https://www.apache.org/licenses/LICENSE-2.0)
|
||||||
|
|
||||||
|
Puedes elegir la licencia que prefieras. Este enfoque de doble licencia es el estándar de facto en
|
||||||
|
el ecosistema Rust.
|
||||||
8
extensions/pagetop-mail/config/common.toml
Normal file
8
extensions/pagetop-mail/config/common.toml
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
# Configuración para las pruebas de este crate: guarda los correos en memoria en lugar de enviarlos
|
||||||
|
# y ofrece las vistas previas.
|
||||||
|
|
||||||
|
[mail]
|
||||||
|
transport = "memory"
|
||||||
|
from = "PageTop Tests <tests@example.com>"
|
||||||
|
base_url = "https://example.com/"
|
||||||
|
previews = true
|
||||||
141
extensions/pagetop-mail/src/attachment.rs
Normal file
141
extensions/pagetop-mail/src/attachment.rs
Normal file
|
|
@ -0,0 +1,141 @@
|
||||||
|
//! Archivos adjuntos e imágenes incrustadas ([`Attachment`]).
|
||||||
|
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
|
use crate::MailError;
|
||||||
|
|
||||||
|
use lettre::message::SinglePart;
|
||||||
|
use lettre::message::header::ContentType;
|
||||||
|
|
||||||
|
use std::fmt;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
/// Archivo adjunto a un correo, o recurso incrustado en su HTML.
|
||||||
|
///
|
||||||
|
/// Un adjunto tiene un nombre de archivo, un contenido y un tipo MIME. Si no se indica el tipo, se
|
||||||
|
/// deduce de la extensión del nombre (`informe.pdf` -> `application/pdf`) y, si no se reconoce, se
|
||||||
|
/// usa `application/octet-stream`.
|
||||||
|
///
|
||||||
|
/// Con [`with_content_id()`](Self::with_content_id) el adjunto pasa a ser un recurso **incrustado**
|
||||||
|
/// (*inline*), típicamente una imagen que el HTML del correo muestra con `src="cid:..."`. Sólo se
|
||||||
|
/// incrustan si el correo tiene HTML; si no, se envían como adjuntos normales.
|
||||||
|
///
|
||||||
|
/// El contenido se comparte al clonar el adjunto, sin copiarlo.
|
||||||
|
///
|
||||||
|
/// # Ejemplos
|
||||||
|
///
|
||||||
|
/// ```rust,no_run
|
||||||
|
/// # use pagetop::prelude::*;
|
||||||
|
/// # use pagetop_mail::prelude::*;
|
||||||
|
/// # async fn example(pdf: Vec<u8>, png: Vec<u8>) -> Result<(), MailError> {
|
||||||
|
/// // Un PDF generado por la aplicación.
|
||||||
|
/// let report = Attachment::new("informe.pdf", pdf);
|
||||||
|
///
|
||||||
|
/// // Un archivo del disco, con el nombre del archivo.
|
||||||
|
/// let terms = Attachment::from_path("docs/condiciones.pdf").await?;
|
||||||
|
///
|
||||||
|
/// // Un logotipo que el HTML muestra con <img src="cid:logo">.
|
||||||
|
/// let logo = Attachment::new("logo.png", png).with_content_id("logo");
|
||||||
|
/// # Ok(())
|
||||||
|
/// # }
|
||||||
|
/// ```
|
||||||
|
#[derive(Clone, Getters)]
|
||||||
|
pub struct Attachment {
|
||||||
|
/// Nombre del archivo, tal como lo verá el destinatario.
|
||||||
|
filename: String,
|
||||||
|
/// Tipo MIME del contenido.
|
||||||
|
content_type: String,
|
||||||
|
/// Identificador del recurso incrustado, si lo es.
|
||||||
|
content_id: Option<String>,
|
||||||
|
#[getters(skip)]
|
||||||
|
body: Arc<[u8]>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Attachment {
|
||||||
|
/// Crea un adjunto con el nombre de archivo y el contenido dados.
|
||||||
|
pub fn new(filename: impl Into<String>, body: impl Into<Vec<u8>>) -> Self {
|
||||||
|
let filename = filename.into();
|
||||||
|
let content_type = mime_guess::from_path(&filename)
|
||||||
|
.first_or_octet_stream()
|
||||||
|
.essence_str()
|
||||||
|
.to_owned();
|
||||||
|
Attachment {
|
||||||
|
filename,
|
||||||
|
content_type,
|
||||||
|
content_id: None,
|
||||||
|
body: Arc::from(body.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Crea un adjunto leyendo un archivo del disco. El nombre del adjunto es el del archivo.
|
||||||
|
///
|
||||||
|
/// Falla con [`MailError::ReadAttachment`] si no se puede leer el archivo.
|
||||||
|
pub async fn from_path(path: impl AsRef<Path>) -> Result<Self, MailError> {
|
||||||
|
let path = path.as_ref();
|
||||||
|
let body = tokio::fs::read(path)
|
||||||
|
.await
|
||||||
|
.map_err(|source| MailError::ReadAttachment {
|
||||||
|
path: path.to_path_buf(),
|
||||||
|
source,
|
||||||
|
})?;
|
||||||
|
let filename = path
|
||||||
|
.file_name()
|
||||||
|
.map(|name| name.to_string_lossy().into_owned())
|
||||||
|
.unwrap_or_default();
|
||||||
|
Ok(Attachment::new(filename, body))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Contenido del adjunto.
|
||||||
|
pub fn body(&self) -> &[u8] {
|
||||||
|
&self.body
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Indica si es un recurso incrustado en el HTML del correo.
|
||||||
|
pub fn is_inline(&self) -> bool {
|
||||||
|
self.content_id.is_some()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convierte el adjunto en una parte del mensaje. Los recursos incrustados sólo se incrustan si
|
||||||
|
// `inline` es `true` (el correo tiene HTML).
|
||||||
|
pub(crate) fn to_part(&self, inline: bool) -> Result<SinglePart, MailError> {
|
||||||
|
let content_type = ContentType::parse(&self.content_type)
|
||||||
|
.map_err(|_| MailError::InvalidContentType(self.content_type.clone()))?;
|
||||||
|
let attachment = match self.content_id() {
|
||||||
|
Some(id) if inline => lettre::message::Attachment::new_inline(id.clone()),
|
||||||
|
_ => lettre::message::Attachment::new(self.filename.clone()),
|
||||||
|
};
|
||||||
|
Ok(attachment.body(self.body.to_vec(), content_type))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Muestra el tamaño del contenido en lugar de sus bytes.
|
||||||
|
impl fmt::Debug for Attachment {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.debug_struct("Attachment")
|
||||||
|
.field("filename", &self.filename)
|
||||||
|
.field("content_type", &self.content_type)
|
||||||
|
.field("content_id", &self.content_id)
|
||||||
|
.field("body_len", &self.body.len())
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[builder_impl]
|
||||||
|
impl Attachment {
|
||||||
|
// **< Attachment BUILDER >*********************************************************************
|
||||||
|
|
||||||
|
/// Cambia el tipo MIME deducido del nombre del archivo (p. ej. `"text/csv; charset=utf-8"`).
|
||||||
|
/// Si no es válido, el envío falla con [`MailError::InvalidContentType`].
|
||||||
|
pub fn with_content_type(mut self, content_type: impl Into<String>) -> Self {
|
||||||
|
self.content_type = content_type.into();
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Incrusta el adjunto en el HTML del correo con el identificador dado, que el HTML usa como
|
||||||
|
/// `cid:<identificador>` (p. ej. `img src="cid:logo"`).
|
||||||
|
pub fn with_content_id(mut self, content_id: impl Into<String>) -> Self {
|
||||||
|
self.content_id = Some(content_id.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
171
extensions/pagetop-mail/src/config.rs
Normal file
171
extensions/pagetop-mail/src/config.rs
Normal file
|
|
@ -0,0 +1,171 @@
|
||||||
|
//! Ajustes de configuración de `pagetop-mail`.
|
||||||
|
//!
|
||||||
|
//! Ejemplo:
|
||||||
|
//!
|
||||||
|
//! ```toml
|
||||||
|
//! [mail]
|
||||||
|
//! transport = "smtp"
|
||||||
|
//! from = "Mi Aplicación <no-reply@example.com>"
|
||||||
|
//! base_url = "https://example.com"
|
||||||
|
//!
|
||||||
|
//! [mail.smtp]
|
||||||
|
//! host = "smtp.example.com"
|
||||||
|
//! security = "starttls"
|
||||||
|
//! username = "no-reply@example.com"
|
||||||
|
//! password = "secreto"
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! Uso:
|
||||||
|
//!
|
||||||
|
//! ```rust,no_run
|
||||||
|
//! use pagetop_mail::config;
|
||||||
|
//!
|
||||||
|
//! assert_eq!(config::SETTINGS.smtp.host, "smtp.example.com");
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! Todas las opciones, con su valor por defecto, se documentan en [`MailSettings`] y sus
|
||||||
|
//! subsecciones ([`SmtpSettings`], [`SendmailSettings`] y [`FileSettings`]).
|
||||||
|
//!
|
||||||
|
//! Consulta [`pagetop::config`] para ver cómo PageTop lee los archivos de configuración y aplica
|
||||||
|
//! los valores a los ajustes.
|
||||||
|
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
/// Ajustes de la sección `[mail]`, cargados al arrancar la aplicación.
|
||||||
|
pub static SETTINGS: LazySettings<MailSettings> = LazySettings::new();
|
||||||
|
|
||||||
|
/// Sección **`[mail]`** de la configuración.
|
||||||
|
#[settings(section = "mail")]
|
||||||
|
pub struct MailSettings {
|
||||||
|
/// Cómo se entregan los correos. Por defecto se escriben en las trazas sin enviarlos
|
||||||
|
/// ([`MailTransport::Log`]), para que una aplicación sin configurar no envíe correo real.
|
||||||
|
pub transport: MailTransport,
|
||||||
|
/// Remitente por defecto, para los correos que no indican uno propio. Admite la dirección sola
|
||||||
|
/// (`"no-reply@example.com"`) o con nombre (`"Mi Aplicación <no-reply@example.com>"`). Sin
|
||||||
|
/// valor, cada correo debe indicar su remitente.
|
||||||
|
pub from: Option<String>,
|
||||||
|
/// Dirección de respuesta por defecto, para los correos que no indican una propia.
|
||||||
|
pub reply_to: Option<String>,
|
||||||
|
/// Si se indica, todos los correos se entregan **sólo** a esta dirección en lugar de a sus
|
||||||
|
/// destinatarios, que se conservan en las cabeceras (`To`, `Cc`). Pensado para entornos de
|
||||||
|
/// pruebas o preproducción con datos reales.
|
||||||
|
pub redirect_to: Option<String>,
|
||||||
|
/// URL pública de la aplicación (p. ej. `"https://example.com"`), para construir los enlaces
|
||||||
|
/// absolutos de los correos con [`absolute_url()`](crate::absolute_url). Debe empezar por
|
||||||
|
/// `http://` o `https://`, o la aplicación no arranca. Sin valor, se usa la dirección y el
|
||||||
|
/// puerto de escucha del servidor (`http://localhost:8080`), que sólo sirve en desarrollo.
|
||||||
|
pub base_url: Option<String>,
|
||||||
|
/// Ofrece en `/mail/preview` las vistas previas de los correos que declaran las extensiones
|
||||||
|
/// (ver [`preview`](crate::preview)). Sólo para desarrollo: muestra las plantillas a cualquiera
|
||||||
|
/// que conozca la ruta.
|
||||||
|
#[default = false]
|
||||||
|
pub previews: bool,
|
||||||
|
|
||||||
|
/// Servidor SMTP, en la subsección `[mail.smtp]`.
|
||||||
|
pub smtp: SmtpSettings,
|
||||||
|
|
||||||
|
/// Programa *sendmail*, en la subsección `[mail.sendmail]`.
|
||||||
|
pub sendmail: SendmailSettings,
|
||||||
|
|
||||||
|
/// Archivos de correo, en la subsección `[mail.file]`.
|
||||||
|
pub file: FileSettings,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Forma de entregar los correos. Usado en [`MailSettings::transport`].
|
||||||
|
#[derive(AutoDefault, Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum MailTransport {
|
||||||
|
/// Envía los correos a un servidor SMTP (ver [`SmtpSettings`]).
|
||||||
|
Smtp,
|
||||||
|
/// Entrega los correos al programa *sendmail* local (ver [`SendmailSettings`]).
|
||||||
|
Sendmail,
|
||||||
|
/// Guarda cada correo como un archivo `.eml` en un directorio (ver [`FileSettings`]). Útil en
|
||||||
|
/// desarrollo para abrirlos con un cliente de correo.
|
||||||
|
File,
|
||||||
|
/// No envía nada: escribe en las trazas el remitente, los destinatarios, el asunto y el texto
|
||||||
|
/// de cada correo. Es el valor por defecto. No debe usarse en producción, porque los textos
|
||||||
|
/// pueden incluir enlaces con *tokens* de un solo uso.
|
||||||
|
#[default]
|
||||||
|
Log,
|
||||||
|
/// No envía nada: guarda los correos en memoria para que las pruebas los consulten con
|
||||||
|
/// [`outbox`](crate::outbox).
|
||||||
|
Memory,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Subsección **`[mail.smtp]`** de la configuración.
|
||||||
|
#[settings]
|
||||||
|
pub struct SmtpSettings {
|
||||||
|
/// Servidor SMTP.
|
||||||
|
#[default = "localhost"]
|
||||||
|
pub host: String,
|
||||||
|
/// Puerto del servidor. Sin valor, el habitual según la seguridad: 465 con
|
||||||
|
/// [`SmtpSecurity::Tls`], 587 con [`SmtpSecurity::StartTls`] y 25 en los demás casos.
|
||||||
|
pub port: Option<u16>,
|
||||||
|
/// Cifrado de la conexión.
|
||||||
|
#[default(SmtpSecurity::StartTls)]
|
||||||
|
pub security: SmtpSecurity,
|
||||||
|
/// Usuario para autenticarse en el servidor. Sin valor, no se autentica.
|
||||||
|
pub username: Option<String>,
|
||||||
|
/// Contraseña del usuario. Conviene guardarla en `config/local.toml`, que no se versiona.
|
||||||
|
pub password: Option<String>,
|
||||||
|
/// Nombre con el que se presenta la aplicación al servidor (`EHLO`). Sin valor, el nombre del
|
||||||
|
/// equipo.
|
||||||
|
pub hello_name: Option<String>,
|
||||||
|
/// Segundos de espera máxima de cada orden al servidor.
|
||||||
|
#[default = 60]
|
||||||
|
pub timeout_secs: u64,
|
||||||
|
/// Número máximo de conexiones abiertas con el servidor, que se reutilizan entre envíos.
|
||||||
|
#[default = 10]
|
||||||
|
pub pool_max_size: u32,
|
||||||
|
/// Acepta certificados no válidos (caducados, autofirmados o de otro servidor). **Peligroso**:
|
||||||
|
/// sólo para servidores de pruebas, nunca en producción.
|
||||||
|
#[default = false]
|
||||||
|
pub accept_invalid_certs: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cifrado de la conexión SMTP. Usado en [`SmtpSettings::security`].
|
||||||
|
#[derive(AutoDefault, Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum SmtpSecurity {
|
||||||
|
/// Sin cifrado. Sólo para servidores locales o de pruebas (p. ej. Mailpit o MailHog).
|
||||||
|
None,
|
||||||
|
/// Cifra con `STARTTLS` si el servidor lo ofrece y, si no, envía sin cifrar.
|
||||||
|
Opportunistic,
|
||||||
|
/// Exige `STARTTLS`: empieza sin cifrar y cifra antes de autenticarse. Es el valor por
|
||||||
|
/// defecto (puerto 587).
|
||||||
|
#[default]
|
||||||
|
StartTls,
|
||||||
|
/// Conexión cifrada desde el principio, también llamada SMTPS (puerto 465).
|
||||||
|
Tls,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Subsección **`[mail.sendmail]`** de la configuración.
|
||||||
|
#[settings]
|
||||||
|
pub struct SendmailSettings {
|
||||||
|
/// Programa que recibe los correos. Sin valor, `sendmail` del `PATH`.
|
||||||
|
pub command: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Subsección **`[mail.file]`** de la configuración.
|
||||||
|
#[settings]
|
||||||
|
pub struct FileSettings {
|
||||||
|
/// Directorio donde se guardan los correos. Se crea al arrancar si no existe.
|
||||||
|
#[default = "mail"]
|
||||||
|
pub dir: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::{MailSettings, config};
|
||||||
|
|
||||||
|
// `reference.toml` documents every option; with unknown keys rejected, loading it proves that
|
||||||
|
// it only documents keys that exist, with values of the right type.
|
||||||
|
const REFERENCE: &str = include_str!("../../../config/reference.toml");
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reference_toml_documents_only_existing_keys() {
|
||||||
|
config::load_from_str::<MailSettings>(REFERENCE).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
345
extensions/pagetop-mail/src/email.rs
Normal file
345
extensions/pagetop-mail/src/email.rs
Normal file
|
|
@ -0,0 +1,345 @@
|
||||||
|
//! Correos electrónicos ([`Email`]).
|
||||||
|
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
|
use crate::{Attachment, MailError, MailTemplate, Mailbox, layout, text, transport};
|
||||||
|
|
||||||
|
use lettre::Message;
|
||||||
|
use lettre::message::{MultiPart, MultiPartBuilder, SinglePart};
|
||||||
|
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
/// Correo electrónico listo para enviar.
|
||||||
|
///
|
||||||
|
/// Se compone con los métodos `with_*()` y se envía con [`send()`](Self::send), que espera a que
|
||||||
|
/// el servidor lo acepte, o con [`send_later()`](Self::send_later), que lo envía en segundo plano.
|
||||||
|
/// También puede crearse a partir de una plantilla con [`from_template()`](Self::from_template).
|
||||||
|
///
|
||||||
|
/// Un correo puede tener texto plano, HTML o ambos (los clientes de correo muestran el que
|
||||||
|
/// prefieran), además de archivos adjuntos y de imágenes incrustadas en el HTML (ver
|
||||||
|
/// [`Attachment`]). El HTML de [`with_html()`](Self::with_html) es sólo el contenido: al enviarlo
|
||||||
|
/// se envuelve en el diseño común de los correos (ver
|
||||||
|
/// [`RenderMailLayout`](crate::RenderMailLayout)).
|
||||||
|
///
|
||||||
|
/// Si sólo tiene HTML, al enviarlo se genera el texto plano a partir de él, porque los filtros de
|
||||||
|
/// correo no deseado penalizan los correos sin texto. Escríbelo con
|
||||||
|
/// [`with_text()`](Self::with_text) sólo si el generado no queda bien.
|
||||||
|
///
|
||||||
|
/// 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.
|
||||||
|
///
|
||||||
|
/// # Ejemplo
|
||||||
|
///
|
||||||
|
/// ```rust,no_run
|
||||||
|
/// use pagetop::prelude::*;
|
||||||
|
/// use pagetop_mail::prelude::*;
|
||||||
|
///
|
||||||
|
/// async fn send_report(pdf: Vec<u8>) -> Result<(), MailError> {
|
||||||
|
/// Email::new()
|
||||||
|
/// .with_to("Ana Pérez <ana@example.com>")
|
||||||
|
/// .with_cc("contabilidad@example.com")
|
||||||
|
/// .with_subject("Informe mensual")
|
||||||
|
/// .with_text("Adjunto el informe del mes.")
|
||||||
|
/// .with_html(html! {
|
||||||
|
/// p { "Adjunto el " strong { "informe" } " del mes." }
|
||||||
|
/// })
|
||||||
|
/// .with_attachment(Attachment::new("informe.pdf", pdf))
|
||||||
|
/// .send()
|
||||||
|
/// .await
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
#[derive(AutoDefault, Clone, Debug, Getters)]
|
||||||
|
pub struct Email {
|
||||||
|
/// Remitente, si se ha indicado.
|
||||||
|
from: Option<Mailbox>,
|
||||||
|
/// Dirección de respuesta, si se ha indicado.
|
||||||
|
reply_to: Option<Mailbox>,
|
||||||
|
/// Destinatarios principales.
|
||||||
|
to: Vec<Mailbox>,
|
||||||
|
/// Destinatarios en copia.
|
||||||
|
cc: Vec<Mailbox>,
|
||||||
|
/// Destinatarios en copia oculta.
|
||||||
|
bcc: Vec<Mailbox>,
|
||||||
|
/// Asunto.
|
||||||
|
subject: String,
|
||||||
|
/// Texto plano, si lo tiene.
|
||||||
|
text: Option<String>,
|
||||||
|
/// HTML, si lo tiene: el contenido mientras se compone y el documento completo una vez
|
||||||
|
/// enviado.
|
||||||
|
html: Option<Markup>,
|
||||||
|
#[getters(skip)]
|
||||||
|
html_is_document: bool,
|
||||||
|
/// Archivos adjuntos e imágenes incrustadas.
|
||||||
|
attachments: Vec<Attachment>,
|
||||||
|
#[getters(skip)]
|
||||||
|
langid: Option<&'static LanguageIdentifier>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Email {
|
||||||
|
/// Crea un correo vacío.
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Email::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Crea un correo con el asunto, el HTML y el texto de una plantilla, generados en el idioma
|
||||||
|
/// del contexto, que también es el del diseño común del HTML.
|
||||||
|
///
|
||||||
|
/// El contexto puede ser el de la petición en curso, si el destinatario es quien la hace (p.
|
||||||
|
/// ej. al registrarse), o uno creado para el destinatario con
|
||||||
|
/// `Context::default().with_langid(...)`.
|
||||||
|
pub fn from_template(template: &impl MailTemplate, cx: &Context) -> Self {
|
||||||
|
let mut email = Email::new()
|
||||||
|
.with_subject(template.subject(cx))
|
||||||
|
.with_langid(cx);
|
||||||
|
if let Some(html) = template.html(cx) {
|
||||||
|
email.alter_html(html);
|
||||||
|
}
|
||||||
|
if let Some(text) = template.text(cx) {
|
||||||
|
email.alter_text(text);
|
||||||
|
}
|
||||||
|
email
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Idioma del correo: el indicado con [`with_langid()`](Self::with_langid) o, si no, el idioma
|
||||||
|
/// por defecto de la aplicación.
|
||||||
|
pub fn langid(&self) -> &'static LanguageIdentifier {
|
||||||
|
self.langid.unwrap_or_else(Locale::default_langid)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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
|
||||||
|
/// remitente o los destinatarios, o si la entrega falla.
|
||||||
|
pub async fn send(self) -> Result<(), MailError> {
|
||||||
|
transport::deliver(self).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Envía el correo en segundo plano, sin esperar al resultado. Si falla, se registra el error
|
||||||
|
/// en las trazas.
|
||||||
|
///
|
||||||
|
/// La respuesta de la petición no espera al servidor de correo, y su tiempo no revela si el
|
||||||
|
/// correo se ha enviado (p. ej., si existe la cuenta para la que se pide recuperar la
|
||||||
|
/// contraseña). A cambio, los correos pendientes se pierden si la aplicación se detiene antes
|
||||||
|
/// de enviarlos, y no se reintentan si fallan.
|
||||||
|
pub fn send_later(self) {
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let subject = self.subject.clone();
|
||||||
|
if let Err(err) = self.send().await {
|
||||||
|
let mut message = err.to_string();
|
||||||
|
let mut source = std::error::Error::source(&err);
|
||||||
|
while let Some(cause) = source {
|
||||||
|
message.push_str(": ");
|
||||||
|
message.push_str(&cause.to_string());
|
||||||
|
source = cause.source();
|
||||||
|
}
|
||||||
|
trace::error!("Cannot send email \"{subject}\": {message}");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Completa el correo antes de enviarlo: remitente y dirección de respuesta por defecto, el
|
||||||
|
// texto plano a partir del HTML si no tiene, y el documento HTML con el diseño común. El texto
|
||||||
|
// se genera antes del diseño para que no incluya su pie.
|
||||||
|
pub(crate) fn prepare(mut self, from: Option<&Mailbox>, reply_to: Option<&Mailbox>) -> Self {
|
||||||
|
if self.from.is_none() {
|
||||||
|
self.from = from.cloned();
|
||||||
|
}
|
||||||
|
if self.reply_to.is_none() {
|
||||||
|
self.reply_to = reply_to.cloned();
|
||||||
|
}
|
||||||
|
if self.text.is_none()
|
||||||
|
&& let Some(html) = &self.html
|
||||||
|
{
|
||||||
|
self.text = Some(text::html_to_text(html.as_str()));
|
||||||
|
}
|
||||||
|
if !self.html_is_document
|
||||||
|
&& let Some(content) = self.html.take()
|
||||||
|
{
|
||||||
|
let cx = Context::default().with_langid(&Locale::Resolved(self.langid()));
|
||||||
|
self.html = Some(layout::render(&cx, &self, &content));
|
||||||
|
self.html_is_document = true;
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compone el mensaje MIME:
|
||||||
|
//
|
||||||
|
// - texto y HTML -> multipart/alternative (el texto primero, el preferido al final).
|
||||||
|
// - HTML con imágenes incrustadas -> multipart/related con el HTML y las imágenes.
|
||||||
|
// - con adjuntos -> multipart/mixed con el cuerpo y los adjuntos.
|
||||||
|
pub(crate) fn to_message(&self) -> Result<Message, MailError> {
|
||||||
|
let from = self.from.as_ref().ok_or(MailError::MissingFrom)?;
|
||||||
|
if self.to.is_empty() && self.cc.is_empty() && self.bcc.is_empty() {
|
||||||
|
return Err(MailError::NoRecipients);
|
||||||
|
}
|
||||||
|
|
||||||
|
let from = from.to_lettre()?;
|
||||||
|
let mut builder = Message::builder()
|
||||||
|
.message_id(Some(message_id(from.email.domain())))
|
||||||
|
.from(from)
|
||||||
|
.subject(self.subject.as_str());
|
||||||
|
if let Some(reply_to) = &self.reply_to {
|
||||||
|
builder = builder.reply_to(reply_to.to_lettre()?);
|
||||||
|
}
|
||||||
|
for mailbox in &self.to {
|
||||||
|
builder = builder.to(mailbox.to_lettre()?);
|
||||||
|
}
|
||||||
|
for mailbox in &self.cc {
|
||||||
|
builder = builder.cc(mailbox.to_lettre()?);
|
||||||
|
}
|
||||||
|
for mailbox in &self.bcc {
|
||||||
|
builder = builder.bcc(mailbox.to_lettre()?);
|
||||||
|
}
|
||||||
|
|
||||||
|
let has_html = self.html.is_some();
|
||||||
|
let html = match &self.html {
|
||||||
|
Some(html) => {
|
||||||
|
let part = SinglePart::html(html.as_str().to_owned());
|
||||||
|
let mut inline = self.attachments.iter().filter(|a| a.is_inline()).peekable();
|
||||||
|
if inline.peek().is_some() {
|
||||||
|
let images = inline
|
||||||
|
.map(|attachment| attachment.to_part(true).map(Part::Single))
|
||||||
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
|
Some(multipart(MultiPart::related(), Part::Single(part), images))
|
||||||
|
} else {
|
||||||
|
Some(Part::Single(part))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
let text = self
|
||||||
|
.text
|
||||||
|
.as_ref()
|
||||||
|
.map(|t| Part::Single(SinglePart::plain(t.clone())));
|
||||||
|
let mut body = match (text, html) {
|
||||||
|
(Some(text), Some(html)) => multipart(MultiPart::alternative(), text, vec![html]),
|
||||||
|
(Some(part), None) | (None, Some(part)) => part,
|
||||||
|
(None, None) => Part::Single(SinglePart::plain(String::new())),
|
||||||
|
};
|
||||||
|
|
||||||
|
let attached = self
|
||||||
|
.attachments
|
||||||
|
.iter()
|
||||||
|
.filter(|a| !(has_html && a.is_inline()))
|
||||||
|
.map(|attachment| attachment.to_part(false).map(Part::Single))
|
||||||
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
|
if !attached.is_empty() {
|
||||||
|
body = multipart(MultiPart::mixed(), body, attached);
|
||||||
|
}
|
||||||
|
|
||||||
|
match body {
|
||||||
|
Part::Single(part) => builder.singlepart(part),
|
||||||
|
Part::Multi(multi) => builder.multipart(multi),
|
||||||
|
}
|
||||||
|
.map_err(MailError::Build)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[builder_impl]
|
||||||
|
impl Email {
|
||||||
|
// **< Email BUILDER >**************************************************************************
|
||||||
|
|
||||||
|
/// Establece el remitente, en lugar del de la configuración (`mail.from`).
|
||||||
|
pub fn with_from(mut self, from: impl Into<Mailbox>) -> Self {
|
||||||
|
self.from = Some(from.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Establece la dirección de respuesta, en lugar de la de la configuración (`mail.reply_to`).
|
||||||
|
pub fn with_reply_to(mut self, reply_to: impl Into<Mailbox>) -> Self {
|
||||||
|
self.reply_to = Some(reply_to.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Añade un destinatario principal (`To`).
|
||||||
|
pub fn with_to(mut self, to: impl Into<Mailbox>) -> Self {
|
||||||
|
self.to.push(to.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Añade un destinatario en copia (`Cc`).
|
||||||
|
pub fn with_cc(mut self, cc: impl Into<Mailbox>) -> Self {
|
||||||
|
self.cc.push(cc.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Añade un destinatario en copia oculta (`Bcc`), que no ven los demás destinatarios.
|
||||||
|
pub fn with_bcc(mut self, bcc: impl Into<Mailbox>) -> Self {
|
||||||
|
self.bcc.push(bcc.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Establece el asunto.
|
||||||
|
pub fn with_subject(mut self, subject: impl Into<String>) -> Self {
|
||||||
|
self.subject = subject.into();
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Establece el texto plano.
|
||||||
|
pub fn with_text(mut self, text: impl Into<String>) -> Self {
|
||||||
|
self.text = Some(text.into());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Establece el contenido HTML, que al enviarse se envuelve en el diseño común de los correos.
|
||||||
|
pub fn with_html(mut self, content: Markup) -> Self {
|
||||||
|
self.html = Some(content);
|
||||||
|
self.html_is_document = false;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Establece el documento HTML completo, que se envía tal cual, sin el diseño común. Útil si el
|
||||||
|
/// HTML se genera con otra herramienta.
|
||||||
|
pub fn with_html_document(mut self, document: Markup) -> Self {
|
||||||
|
self.html = Some(document);
|
||||||
|
self.html_is_document = true;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Añade un archivo adjunto o una imagen incrustada.
|
||||||
|
pub fn with_attachment(mut self, attachment: Attachment) -> Self {
|
||||||
|
self.attachments.push(attachment);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Establece el idioma del correo, que usa el diseño común del HTML.
|
||||||
|
pub fn with_langid(mut self, language: &impl LangId) -> Self {
|
||||||
|
self.langid = Some(language.langid());
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Genera la cabecera `Message-ID`, que los filtros de correo no deseado penalizan si falta. Sólo
|
||||||
|
// tiene que ser única: la hora, un contador y el proceso lo garantizan sin depender del azar. El
|
||||||
|
// dominio es el del remitente y no el nombre del equipo, que en un contenedor suele ser aleatorio y
|
||||||
|
// también penalizan algunos filtros.
|
||||||
|
fn message_id(domain: &str) -> String {
|
||||||
|
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||||
|
let nanos = SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map_or(0, |elapsed| elapsed.as_nanos());
|
||||||
|
let count = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||||
|
format!("<{nanos:x}.{count:x}.{:x}@{domain}>", std::process::id())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parte de un mensaje MIME: simple o compuesta por otras partes.
|
||||||
|
enum Part {
|
||||||
|
Single(SinglePart),
|
||||||
|
Multi(MultiPart),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compone una parte del tipo dado con `first` y el resto de partes, en ese orden.
|
||||||
|
fn multipart(kind: MultiPartBuilder, first: Part, rest: Vec<Part>) -> Part {
|
||||||
|
let mut multi = match first {
|
||||||
|
Part::Single(part) => kind.singlepart(part),
|
||||||
|
Part::Multi(multi) => kind.multipart(multi),
|
||||||
|
};
|
||||||
|
for part in rest {
|
||||||
|
multi = match part {
|
||||||
|
Part::Single(part) => multi.singlepart(part),
|
||||||
|
Part::Multi(part) => multi.multipart(part),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
Part::Multi(multi)
|
||||||
|
}
|
||||||
68
extensions/pagetop-mail/src/error.rs
Normal file
68
extensions/pagetop-mail/src/error.rs
Normal file
|
|
@ -0,0 +1,68 @@
|
||||||
|
//! Errores de `pagetop-mail`.
|
||||||
|
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
/// Errores al configurar el envío de correo o al componer y enviar un correo.
|
||||||
|
#[derive(Debug, thiserror::Error)]
|
||||||
|
pub enum MailError {
|
||||||
|
/// Una dirección de correo no es válida.
|
||||||
|
#[error("invalid email address \"{address}\"")]
|
||||||
|
InvalidAddress {
|
||||||
|
/// Dirección tal como se indicó.
|
||||||
|
address: String,
|
||||||
|
/// Motivo del error.
|
||||||
|
#[source]
|
||||||
|
source: lettre::address::AddressError,
|
||||||
|
},
|
||||||
|
/// Un ajuste de la sección `[mail]` no es válido.
|
||||||
|
#[error("invalid mail setting \"{key}\"")]
|
||||||
|
InvalidSetting {
|
||||||
|
/// Clave del ajuste, p. ej. `"mail.from"`.
|
||||||
|
key: &'static str,
|
||||||
|
/// Motivo del error.
|
||||||
|
#[source]
|
||||||
|
source: Box<MailError>,
|
||||||
|
},
|
||||||
|
/// Una URL no es absoluta (no empieza por `http://` ni `https://`).
|
||||||
|
#[error("invalid URL \"{0}\": it must start with http:// or https://")]
|
||||||
|
InvalidUrl(String),
|
||||||
|
/// El correo no indica remitente y no hay uno por defecto (`mail.from`).
|
||||||
|
#[error("email has no sender: set mail.from or use Email::with_from()")]
|
||||||
|
MissingFrom,
|
||||||
|
/// El correo no tiene ningún destinatario (`To`, `Cc` ni `Bcc`).
|
||||||
|
#[error("email has no recipients")]
|
||||||
|
NoRecipients,
|
||||||
|
/// El tipo de contenido de un adjunto no es un tipo MIME válido.
|
||||||
|
#[error("invalid content type \"{0}\" for attachment")]
|
||||||
|
InvalidContentType(String),
|
||||||
|
/// No se puede leer el archivo de un adjunto.
|
||||||
|
#[error("cannot read attachment \"{path}\"")]
|
||||||
|
ReadAttachment {
|
||||||
|
/// Ruta del archivo.
|
||||||
|
path: PathBuf,
|
||||||
|
/// Error devuelto al leerlo.
|
||||||
|
#[source]
|
||||||
|
source: std::io::Error,
|
||||||
|
},
|
||||||
|
/// No se puede crear el directorio de los archivos de correo (`mail.file.dir`).
|
||||||
|
#[error("cannot create mail directory \"{path}\"")]
|
||||||
|
CreateDir {
|
||||||
|
/// Ruta del directorio.
|
||||||
|
path: PathBuf,
|
||||||
|
/// Error devuelto al crearlo.
|
||||||
|
#[source]
|
||||||
|
source: std::io::Error,
|
||||||
|
},
|
||||||
|
/// No se puede componer el mensaje.
|
||||||
|
#[error("cannot build email message")]
|
||||||
|
Build(#[source] lettre::error::Error),
|
||||||
|
/// Error de conexión, de cifrado o de entrega con el servidor SMTP.
|
||||||
|
#[error("SMTP error")]
|
||||||
|
Smtp(#[source] lettre::transport::smtp::Error),
|
||||||
|
/// Error al entregar el correo al programa *sendmail*.
|
||||||
|
#[error("sendmail error")]
|
||||||
|
Sendmail(#[source] lettre::transport::sendmail::Error),
|
||||||
|
/// Error al guardar el correo como archivo.
|
||||||
|
#[error("cannot write email file")]
|
||||||
|
File(#[source] lettre::transport::file::Error),
|
||||||
|
}
|
||||||
151
extensions/pagetop-mail/src/layout.rs
Normal file
151
extensions/pagetop-mail/src/layout.rs
Normal file
|
|
@ -0,0 +1,151 @@
|
||||||
|
//! Diseño común del HTML de los correos y acción [`RenderMailLayout`] para cambiarlo.
|
||||||
|
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
|
use crate::{Email, LOCALES_MAIL};
|
||||||
|
|
||||||
|
use std::ops::ControlFlow;
|
||||||
|
|
||||||
|
/// Tipo de función que genera el documento HTML completo de un correo.
|
||||||
|
///
|
||||||
|
/// Recibe:
|
||||||
|
///
|
||||||
|
/// - `cx`: contexto con el idioma del correo, para traducir los textos del diseño.
|
||||||
|
/// - `email`: el correo, p. ej. para usar su asunto como título del documento.
|
||||||
|
/// - `content`: el contenido HTML del correo, que el diseño debe incluir sin modificar.
|
||||||
|
pub type FnRenderMailLayout = fn(cx: &Context, email: &Email, content: &Markup) -> Markup;
|
||||||
|
|
||||||
|
/// Acción para cambiar el diseño común del HTML de los correos.
|
||||||
|
///
|
||||||
|
/// Todos los correos con contenido HTML ([`Email::with_html()`] o una
|
||||||
|
/// [`MailTemplate`](crate::MailTemplate)) se envuelven al enviarlos en un documento HTML completo:
|
||||||
|
/// cabecera, estilos y pie. El diseño por defecto es sobrio y neutro: un recuadro blanco de hasta
|
||||||
|
/// 600 píxeles de ancho sobre fondo gris, con el nombre de la aplicación al pie.
|
||||||
|
///
|
||||||
|
/// Una aplicación (o una extensión) registra esta acción para dar a **todos** los correos su propia
|
||||||
|
/// imagen, incluidos los que envían otras extensiones como `pagetop-user`. Si hay varias, se aplica
|
||||||
|
/// sólo la de menor peso.
|
||||||
|
///
|
||||||
|
/// Los clientes de correo ignoran las hojas de estilo externas y muchos ignoran también los estilos
|
||||||
|
/// del `<head>`: lo seguro es escribir los estilos en línea (`style="..."`) y maquetar con tablas.
|
||||||
|
///
|
||||||
|
/// # Ejemplo
|
||||||
|
///
|
||||||
|
/// ```rust,no_run
|
||||||
|
/// use pagetop::prelude::*;
|
||||||
|
/// use pagetop_mail::prelude::*;
|
||||||
|
///
|
||||||
|
/// fn my_layout(cx: &Context, email: &Email, content: &Markup) -> Markup {
|
||||||
|
/// html! {
|
||||||
|
/// (DOCTYPE)
|
||||||
|
/// html lang=(cx.langid().to_string()) {
|
||||||
|
/// head {
|
||||||
|
/// meta charset="utf-8";
|
||||||
|
/// title { (email.subject()) }
|
||||||
|
/// }
|
||||||
|
/// body style="font-family: Georgia, serif;" {
|
||||||
|
/// img src="https://example.com/logo.png" alt="Example" width="120";
|
||||||
|
/// (content)
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// struct MyApp;
|
||||||
|
///
|
||||||
|
/// #[async_trait]
|
||||||
|
/// impl Extension for MyApp {
|
||||||
|
/// fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||||
|
/// vec![&pagetop_mail::Mail]
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// fn actions(&self) -> Vec<ActionBox> {
|
||||||
|
/// actions![RenderMailLayout::new(my_layout)]
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// [`Email::with_html()`]: crate::Email::with_html
|
||||||
|
pub struct RenderMailLayout {
|
||||||
|
f: FnRenderMailLayout,
|
||||||
|
weight: Weight,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActionDispatcher for RenderMailLayout {
|
||||||
|
fn weight(&self) -> Weight {
|
||||||
|
self.weight
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RenderMailLayout {
|
||||||
|
/// Registra una función que genera el documento HTML de los correos.
|
||||||
|
pub fn new(f: FnRenderMailLayout) -> Self {
|
||||||
|
RenderMailLayout { f, weight: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opcional. Si varias extensiones registran esta acción, se aplica la de menor peso. Se pueden
|
||||||
|
/// usar valores negativos.
|
||||||
|
pub fn with_weight(mut self, value: Weight) -> Self {
|
||||||
|
self.weight = value;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Genera el documento HTML del correo con la acción de menor peso o, sin ninguna, con el diseño por
|
||||||
|
// defecto.
|
||||||
|
pub(crate) fn render(cx: &Context, email: &Email, content: &Markup) -> Markup {
|
||||||
|
let mut document = None;
|
||||||
|
try_dispatch_actions(|action: &RenderMailLayout| {
|
||||||
|
document = Some((action.f)(cx, email, content));
|
||||||
|
ControlFlow::Break(())
|
||||||
|
});
|
||||||
|
document.unwrap_or_else(|| default_layout(cx, email, content))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Estilos en línea del diseño por defecto.
|
||||||
|
const PAGE_STYLE: &str = "margin: 0; padding: 0; background-color: #f4f4f5;";
|
||||||
|
const CARD_STYLE: &str = "max-width: 600px; background-color: #ffffff; border-radius: 6px;";
|
||||||
|
const CONTENT_STYLE: &str = concat!(
|
||||||
|
"font-family: -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; ",
|
||||||
|
"padding: 32px; font-size: 16px; line-height: 1.5; color: #1f2937;"
|
||||||
|
);
|
||||||
|
const FOOTER_STYLE: &str = concat!(
|
||||||
|
"font-family: -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; ",
|
||||||
|
"margin: 16px 0 0; font-size: 12px; color: #6b7280;"
|
||||||
|
);
|
||||||
|
|
||||||
|
fn default_layout(cx: &Context, email: &Email, content: &Markup) -> Markup {
|
||||||
|
html! {
|
||||||
|
(DOCTYPE)
|
||||||
|
html lang=(cx.langid().to_string()) {
|
||||||
|
head {
|
||||||
|
meta charset="utf-8";
|
||||||
|
meta name="viewport" content="width=device-width, initial-scale=1";
|
||||||
|
meta name="color-scheme" content="light";
|
||||||
|
title { (email.subject()) }
|
||||||
|
}
|
||||||
|
body style=(PAGE_STYLE) {
|
||||||
|
table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0"
|
||||||
|
style=(PAGE_STYLE)
|
||||||
|
{
|
||||||
|
tr {
|
||||||
|
td align="center" style="padding: 24px 12px;" {
|
||||||
|
table role="presentation" width="100%" cellpadding="0" cellspacing="0"
|
||||||
|
border="0" style=(CARD_STYLE)
|
||||||
|
{
|
||||||
|
tr {
|
||||||
|
td style=(CONTENT_STYLE) { (content) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
p style=(FOOTER_STYLE) {
|
||||||
|
(Lc::t("mail_footer", &LOCALES_MAIL)
|
||||||
|
.with_arg("app", &global::SETTINGS.app.name)
|
||||||
|
.using(cx))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
339
extensions/pagetop-mail/src/lib.rs
Normal file
339
extensions/pagetop-mail/src/lib.rs
Normal file
|
|
@ -0,0 +1,339 @@
|
||||||
|
/*!
|
||||||
|
<div align="center">
|
||||||
|
|
||||||
|
<h1>PageTop Mail</h1>
|
||||||
|
|
||||||
|
<p>Envío de correo electrónico para aplicaciones <strong>PageTop</strong>.</p>
|
||||||
|
|
||||||
|
[](https://docs.rs/pagetop-mail)
|
||||||
|
[](https://crates.io/crates/pagetop-mail)
|
||||||
|
[](https://crates.io/crates/pagetop-mail)
|
||||||
|
[](https://git.cillero.es/manuelcillero/pagetop/src/branch/main/extensions/pagetop-mail#licencia)
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
Envía correos en texto plano y HTML, con archivos adjuntos e imágenes incrustadas, por SMTP, con el
|
||||||
|
programa *sendmail* o a archivos `.eml`, todo configurado en los archivos TOML de la aplicación.
|
||||||
|
Los correos pueden crearse con plantillas que traducen sus textos al idioma del destinatario, y
|
||||||
|
comparten un diseño HTML común que la aplicación puede cambiar. Para las pruebas, los correos pueden
|
||||||
|
guardarse en memoria en lugar de enviarse.
|
||||||
|
|
||||||
|
## Sobre PageTop
|
||||||
|
|
||||||
|
[PageTop](https://docs.rs/pagetop) es un entorno de desarrollo que reivindica la esencia de la web
|
||||||
|
clásica para crear soluciones web SSR (*renderizadas en el servidor*) modulares, extensibles y
|
||||||
|
configurables, basadas en HTML, CSS y JavaScript.
|
||||||
|
|
||||||
|
## Guía rápida
|
||||||
|
|
||||||
|
**Añade la dependencia** a tu `Cargo.toml`:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[dependencies]
|
||||||
|
pagetop-mail = "..."
|
||||||
|
```
|
||||||
|
|
||||||
|
**Declara la extensión** en tu aplicación o en la extensión que envíe correos:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
|
struct MyApp;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Extension for MyApp {
|
||||||
|
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||||
|
vec![&pagetop_mail::Mail]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Configura el envío** en la sección `[mail]` (todas las opciones en [`config`]):
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[mail]
|
||||||
|
transport = "smtp"
|
||||||
|
from = "Mi Aplicación <no-reply@example.com>"
|
||||||
|
base_url = "https://example.com"
|
||||||
|
|
||||||
|
[mail.smtp]
|
||||||
|
host = "smtp.example.com"
|
||||||
|
security = "starttls" # "none", "opportunistic", "starttls" o "tls".
|
||||||
|
username = "no-reply@example.com"
|
||||||
|
password = "secreto" # Mejor en config/local.toml, que no se versiona.
|
||||||
|
```
|
||||||
|
|
||||||
|
Sin configurar, los correos se escriben en las trazas en lugar de enviarse (`transport = "log"`),
|
||||||
|
así que una aplicación en desarrollo nunca envía correo real por error. La configuración se valida
|
||||||
|
al arrancar: un ajuste no válido detiene la aplicación con un mensaje que indica el problema.
|
||||||
|
|
||||||
|
**Envía un correo** con [`Email`]:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
use pagetop_mail::prelude::*;
|
||||||
|
|
||||||
|
async fn notify() -> Result<(), MailError> {
|
||||||
|
Email::new()
|
||||||
|
.with_to("Ana Pérez <ana@example.com>")
|
||||||
|
.with_subject("Tu pedido ha salido")
|
||||||
|
.with_text("Tu pedido 1234 ha salido hoy.")
|
||||||
|
.with_html(html! {
|
||||||
|
p { "Tu pedido " strong { "1234" } " ha salido hoy." }
|
||||||
|
})
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
[`Email::send()`] espera a que el correo se entregue; [`Email::send_later()`] lo envía en segundo
|
||||||
|
plano y registra en las trazas los errores.
|
||||||
|
|
||||||
|
## Plantillas
|
||||||
|
|
||||||
|
Una [`MailTemplate`] genera el asunto, el HTML y el texto de un correo a partir de sus datos, con
|
||||||
|
los textos traducidos mediante [`Lc`] al idioma del contexto que recibe. Así, cada extensión
|
||||||
|
define sus correos como tipos propios, y el mismo correo se envía a cada destinatario en su idioma:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
# use pagetop::prelude::*;
|
||||||
|
# use pagetop_mail::prelude::*;
|
||||||
|
# include_locales!(LOCALES_SHOP);
|
||||||
|
struct Welcome {
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MailTemplate for Welcome {
|
||||||
|
fn subject(&self, cx: &Context) -> String {
|
||||||
|
Lc::t("welcome-subject", &LOCALES_SHOP).lookup(cx).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn html(&self, cx: &Context) -> Option<Markup> {
|
||||||
|
let greeting = Lc::t("welcome-greeting", &LOCALES_SHOP).with_arg("name", self.name.clone());
|
||||||
|
Some(html! {
|
||||||
|
p { (greeting.using(cx)) }
|
||||||
|
p {
|
||||||
|
a href=(absolute_url("/shop")) { (Lc::t("welcome-visit", &LOCALES_SHOP).using(cx)) }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn welcome(request: HttpRequest) -> Result<(), MailError> {
|
||||||
|
// El contexto de la petición: el correo sale en el idioma de quien se acaba de registrar.
|
||||||
|
let cx = Context::new(request);
|
||||||
|
Email::from_template(&Welcome { name: "Ana".to_string() }, &cx)
|
||||||
|
.with_to("ana@example.com")
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Enlaces en los correos
|
||||||
|
|
||||||
|
Los enlaces de un correo deben ser absolutos. [`absolute_url()`] antepone a una ruta la URL pública
|
||||||
|
de la aplicación, que se configura en `mail.base_url`. No se deduce de la petición, porque la
|
||||||
|
cabecera `Host` la elige el cliente y un atacante podría hacer que los enlaces de un correo de
|
||||||
|
recuperación de contraseña apuntaran a su propio servidor.
|
||||||
|
|
||||||
|
## Adjuntos e imágenes incrustadas
|
||||||
|
|
||||||
|
Un [`Attachment`] se crea con un contenido en memoria o leyendo un archivo, y su tipo MIME se deduce
|
||||||
|
del nombre. Con [`Attachment::with_content_id()`] se incrusta en el HTML, que lo muestra con
|
||||||
|
`cid:`:
|
||||||
|
|
||||||
|
```rust,no_run
|
||||||
|
# use pagetop::prelude::*;
|
||||||
|
# use pagetop_mail::prelude::*;
|
||||||
|
# async fn example(png: Vec<u8>) -> Result<(), MailError> {
|
||||||
|
Email::new()
|
||||||
|
.with_to("ana@example.com")
|
||||||
|
.with_subject("Informe")
|
||||||
|
.with_html(html! { img src="cid:logo" alt="Logo"; p { "Adjunto el informe." } })
|
||||||
|
.with_attachment(Attachment::new("logo.png", png).with_content_id("logo"))
|
||||||
|
.with_attachment(Attachment::from_path("informes/octubre.pdf").await?)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
# }
|
||||||
|
```
|
||||||
|
|
||||||
|
## Diseño común del HTML
|
||||||
|
|
||||||
|
El HTML de los correos es sólo su contenido: al enviarlos se envuelve en un documento con un diseño
|
||||||
|
sobrio y neutro. La aplicación puede darle su propia imagen a **todos** los correos, incluidos los
|
||||||
|
de otras extensiones, registrando la acción [`RenderMailLayout`].
|
||||||
|
|
||||||
|
## Vistas previas en el navegador
|
||||||
|
|
||||||
|
Con `previews = true` en `[mail]` (sólo en desarrollo), `/mail/preview` lista los correos que las
|
||||||
|
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`].
|
||||||
|
|
||||||
|
## Texto plano automático
|
||||||
|
|
||||||
|
Si un correo sólo tiene HTML, al enviarlo se genera su texto plano a partir del contenido: bloques
|
||||||
|
separados por líneas, listas con guiones, y la dirección de cada enlace entre paréntesis.
|
||||||
|
|
||||||
|
## Transportes
|
||||||
|
|
||||||
|
Se elige en `mail.transport`:
|
||||||
|
|
||||||
|
| Valor | Uso |
|
||||||
|
|--------------|-----------------------------------------------------------------------------|
|
||||||
|
| `"smtp"` | Producción. Servidor SMTP con conexiones reutilizables y cifrado TLS. |
|
||||||
|
| `"sendmail"` | Producción, con un servidor de correo local (Postfix, Exim...). |
|
||||||
|
| `"file"` | Desarrollo. Guarda cada correo como `.eml` para abrirlo con un cliente. |
|
||||||
|
| `"log"` | Por defecto. Escribe los correos en las trazas, sin enviarlos. |
|
||||||
|
| `"memory"` | Pruebas. Guarda los correos en memoria para comprobarlos con [`outbox`]. |
|
||||||
|
|
||||||
|
En entornos de pruebas con datos reales, `mail.redirect_to` entrega todos los correos a una sola
|
||||||
|
dirección, sin cambiar sus cabeceras.
|
||||||
|
|
||||||
|
Para probar el envío SMTP en desarrollo sin enviar correo real, un servidor como
|
||||||
|
[Mailpit](https://mailpit.axllent.org) recoge los correos y los muestra en el navegador:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[mail]
|
||||||
|
transport = "smtp"
|
||||||
|
|
||||||
|
[mail.smtp]
|
||||||
|
host = "localhost"
|
||||||
|
port = 1025
|
||||||
|
security = "none"
|
||||||
|
```
|
||||||
|
*/
|
||||||
|
|
||||||
|
#![doc(
|
||||||
|
html_favicon_url = "https://git.cillero.es/manuelcillero/pagetop/raw/branch/main/assets/favicon.ico"
|
||||||
|
)]
|
||||||
|
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
|
use std::sync::LazyLock;
|
||||||
|
|
||||||
|
pub mod config;
|
||||||
|
|
||||||
|
mod error;
|
||||||
|
pub use error::MailError;
|
||||||
|
|
||||||
|
mod mailbox;
|
||||||
|
pub use mailbox::Mailbox;
|
||||||
|
|
||||||
|
mod attachment;
|
||||||
|
pub use attachment::Attachment;
|
||||||
|
|
||||||
|
mod template;
|
||||||
|
pub use template::MailTemplate;
|
||||||
|
|
||||||
|
mod layout;
|
||||||
|
pub use layout::{FnRenderMailLayout, RenderMailLayout};
|
||||||
|
|
||||||
|
mod email;
|
||||||
|
pub use email::Email;
|
||||||
|
|
||||||
|
pub mod outbox;
|
||||||
|
|
||||||
|
pub mod preview;
|
||||||
|
pub use preview::{DeclareMailPreviews, MailPreviews};
|
||||||
|
|
||||||
|
mod text;
|
||||||
|
|
||||||
|
mod transport;
|
||||||
|
|
||||||
|
include_locales!(LOCALES_MAIL);
|
||||||
|
|
||||||
|
/// Prelude de `pagetop-mail`.
|
||||||
|
pub mod prelude {
|
||||||
|
pub use crate::absolute_url;
|
||||||
|
pub use crate::{Attachment, Email, MailError, MailTemplate, Mailbox};
|
||||||
|
pub use crate::{DeclareMailPreviews, MailPreviews, RenderMailLayout};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Implementa la extensión `pagetop-mail`.
|
||||||
|
pub struct Mail;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Extension for Mail {
|
||||||
|
fn name(&self) -> Lc {
|
||||||
|
Lc::t("extension_name", &LOCALES_MAIL)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn description(&self) -> Lc {
|
||||||
|
Lc::t("extension_description", &LOCALES_MAIL)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn settings(&self) -> Option<&'static dyn LoadSettings> {
|
||||||
|
Some(&config::SETTINGS)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn initialize(&self) -> Result<(), BoxError> {
|
||||||
|
// Construir el transporte al arrancar valida los ajustes; preparar la aplicación varias
|
||||||
|
// veces en el mismo proceso (las pruebas lo hacen) reutiliza el ya construido.
|
||||||
|
transport::mailer()?.log_startup();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn configure_router(&self, router: Router) -> Router {
|
||||||
|
if !config::SETTINGS.previews {
|
||||||
|
return router;
|
||||||
|
}
|
||||||
|
router
|
||||||
|
.route(preview::PREVIEW_PATH, web::get(preview::list_get))
|
||||||
|
.route(
|
||||||
|
&util::join!(preview::PREVIEW_PATH, "/{key}"),
|
||||||
|
web::get(preview::preview_get),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Devuelve la URL absoluta de una ruta de la aplicación, para los enlaces de los correos.
|
||||||
|
///
|
||||||
|
/// Antepone a la ruta la URL pública configurada en `mail.base_url` o, si no hay ninguna, la
|
||||||
|
/// dirección y el puerto de escucha del servidor (sólo útil en desarrollo). Una ruta que ya es una
|
||||||
|
/// URL externa (`https://...`) se devuelve sin cambios.
|
||||||
|
///
|
||||||
|
/// Si la ruta debe conservar el idioma de la petición en curso, constrúyela con
|
||||||
|
/// [`Context::route()`].
|
||||||
|
///
|
||||||
|
/// # Ejemplo
|
||||||
|
///
|
||||||
|
/// ```rust,no_run
|
||||||
|
/// # use pagetop::prelude::*;
|
||||||
|
/// # use pagetop_mail::prelude::*;
|
||||||
|
/// // Con `base_url = "https://example.com"`.
|
||||||
|
/// assert_eq!(absolute_url("/user/verify"), "https://example.com/user/verify");
|
||||||
|
/// ```
|
||||||
|
pub fn absolute_url(path: impl Into<RoutePath>) -> String {
|
||||||
|
let path = path.into().to_string();
|
||||||
|
if util::url_looks_external(&path) {
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
if path.starts_with('/') {
|
||||||
|
util::join!(base_url(), path)
|
||||||
|
} else {
|
||||||
|
util::join!(base_url(), "/", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// URL pública de la aplicación, sin la barra final.
|
||||||
|
fn base_url() -> &'static str {
|
||||||
|
static BASE_URL: LazyLock<String> = LazyLock::new(|| {
|
||||||
|
match config::SETTINGS
|
||||||
|
.base_url
|
||||||
|
.as_deref()
|
||||||
|
.and_then(util::non_blank)
|
||||||
|
{
|
||||||
|
Some(url) => url.trim_end_matches('/').to_owned(),
|
||||||
|
None => {
|
||||||
|
let server = &global::SETTINGS.server;
|
||||||
|
util::join!(
|
||||||
|
"http://",
|
||||||
|
&server.bind_address,
|
||||||
|
":",
|
||||||
|
server.bind_port.to_string()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
&BASE_URL
|
||||||
|
}
|
||||||
20
extensions/pagetop-mail/src/locale/en-US/extension.ftl
Normal file
20
extensions/pagetop-mail/src/locale/en-US/extension.ftl
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
extension_name = Mail
|
||||||
|
extension_description = Sends emails over SMTP, sendmail or files, with templates, HTML and attachments.
|
||||||
|
|
||||||
|
mail_footer = Message sent by { $app }.
|
||||||
|
|
||||||
|
# **< Email previews >**
|
||||||
|
|
||||||
|
preview_title = Email previews
|
||||||
|
preview_empty = No extension declares email previews.
|
||||||
|
preview_back = Back to the list
|
||||||
|
preview_from = From
|
||||||
|
preview_reply_to = Reply to
|
||||||
|
preview_to = To
|
||||||
|
preview_cc = Cc
|
||||||
|
preview_bcc = Bcc
|
||||||
|
preview_subject = Subject
|
||||||
|
preview_attachments = Attachments
|
||||||
|
preview_html = HTML
|
||||||
|
preview_text = Plain text
|
||||||
|
preview_none = None
|
||||||
20
extensions/pagetop-mail/src/locale/es-ES/extension.ftl
Normal file
20
extensions/pagetop-mail/src/locale/es-ES/extension.ftl
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
extension_name = Correo electrónico
|
||||||
|
extension_description = Envía correos por SMTP, sendmail o archivos, con plantillas, HTML y adjuntos.
|
||||||
|
|
||||||
|
mail_footer = Mensaje enviado por { $app }.
|
||||||
|
|
||||||
|
# **< Vistas previas de correos >**
|
||||||
|
|
||||||
|
preview_title = Vistas previas de correos
|
||||||
|
preview_empty = Ninguna extensión declara vistas previas de correos.
|
||||||
|
preview_back = Volver a la lista
|
||||||
|
preview_from = Remitente
|
||||||
|
preview_reply_to = Responder a
|
||||||
|
preview_to = Para
|
||||||
|
preview_cc = Cc
|
||||||
|
preview_bcc = Cco
|
||||||
|
preview_subject = Asunto
|
||||||
|
preview_attachments = Adjuntos
|
||||||
|
preview_html = HTML
|
||||||
|
preview_text = Texto plano
|
||||||
|
preview_none = Ninguno
|
||||||
138
extensions/pagetop-mail/src/mailbox.rs
Normal file
138
extensions/pagetop-mail/src/mailbox.rs
Normal file
|
|
@ -0,0 +1,138 @@
|
||||||
|
//! Direcciones de correo con nombre opcional ([`Mailbox`]).
|
||||||
|
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
|
use crate::MailError;
|
||||||
|
|
||||||
|
use std::fmt;
|
||||||
|
|
||||||
|
/// Dirección de correo, con el nombre opcional de su titular.
|
||||||
|
///
|
||||||
|
/// Se crea a partir de una cadena con la dirección sola (`"ana@example.com"`) o con nombre
|
||||||
|
/// (`"Ana Pérez <ana@example.com>"`, o con el nombre entre comillas), o de una tupla
|
||||||
|
/// `(nombre, dirección)`. Ésta última es la forma segura cuando el nombre procede de datos de
|
||||||
|
/// usuario, porque puede contener comas, comillas u otros caracteres especiales.
|
||||||
|
///
|
||||||
|
/// La dirección no se valida al crearla, sino al enviar el correo, que falla con
|
||||||
|
/// [`MailError::InvalidAddress`] si no es válida.
|
||||||
|
///
|
||||||
|
/// # Ejemplos
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// # use pagetop_mail::prelude::*;
|
||||||
|
/// let ana = Mailbox::from("Ana Pérez <ana@example.com>");
|
||||||
|
/// assert_eq!(ana.name(), Some(&"Ana Pérez".to_string()));
|
||||||
|
/// assert_eq!(ana.address(), "ana@example.com");
|
||||||
|
///
|
||||||
|
/// let luis = Mailbox::from(("Luis, el de soporte", "luis@example.com"));
|
||||||
|
/// assert_eq!(luis.name(), Some(&"Luis, el de soporte".to_string()));
|
||||||
|
///
|
||||||
|
/// let anon = Mailbox::from("no-reply@example.com");
|
||||||
|
/// assert_eq!(anon.name(), None);
|
||||||
|
/// ```
|
||||||
|
#[derive(AutoDefault, Clone, Debug, Eq, Getters, PartialEq)]
|
||||||
|
pub struct Mailbox {
|
||||||
|
/// Nombre del titular, si lo tiene.
|
||||||
|
name: Option<String>,
|
||||||
|
/// Dirección de correo.
|
||||||
|
address: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Mailbox {
|
||||||
|
/// Crea una dirección de correo sin nombre.
|
||||||
|
pub fn new(address: impl Into<String>) -> Self {
|
||||||
|
Mailbox {
|
||||||
|
name: None,
|
||||||
|
address: address.into().trim().to_owned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Crea una dirección de correo con el nombre de su titular. Un nombre vacío equivale a no
|
||||||
|
/// indicarlo, y los caracteres de control del nombre (saltos de línea, tabuladores...) se
|
||||||
|
/// cambian por espacios.
|
||||||
|
pub fn with_name(name: impl Into<String>, address: impl Into<String>) -> Self {
|
||||||
|
// `lettre` provoca un `panic!` al componer una cabecera con un nombre que tenga caracteres
|
||||||
|
// de control, y el nombre puede proceder de datos de usuario.
|
||||||
|
let name: String = name
|
||||||
|
.into()
|
||||||
|
.chars()
|
||||||
|
.map(|c| if c.is_control() { ' ' } else { c })
|
||||||
|
.collect();
|
||||||
|
Mailbox {
|
||||||
|
name: util::non_blank(&name).map(str::to_owned),
|
||||||
|
..Mailbox::new(address)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Comprueba que la dirección sea válida, con el mismo criterio que se aplica al enviar.
|
||||||
|
///
|
||||||
|
/// Sirve para validar una dirección al recibirla (p. ej. de un formulario), antes de guardarla.
|
||||||
|
/// Falla con [`MailError::InvalidAddress`] si no es válida.
|
||||||
|
///
|
||||||
|
/// ```rust
|
||||||
|
/// # use pagetop_mail::prelude::*;
|
||||||
|
/// assert!(Mailbox::new("ana@example.com").validate().is_ok());
|
||||||
|
/// assert!(Mailbox::new("ana.example.com").validate().is_err());
|
||||||
|
/// ```
|
||||||
|
pub fn validate(&self) -> Result<(), MailError> {
|
||||||
|
self.to_lettre().map(drop)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convierte la dirección al tipo de `lettre`, validándola.
|
||||||
|
pub(crate) fn to_lettre(&self) -> Result<lettre::message::Mailbox, MailError> {
|
||||||
|
let address = self.address.parse::<lettre::Address>().map_err(|source| {
|
||||||
|
MailError::InvalidAddress {
|
||||||
|
address: self.address.clone(),
|
||||||
|
source,
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
Ok(lettre::message::Mailbox::new(self.name.clone(), address))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&str> for Mailbox {
|
||||||
|
fn from(value: &str) -> Self {
|
||||||
|
let value = value.trim();
|
||||||
|
// "Nombre <dirección>": la dirección es lo que va entre los últimos `<` y `>`.
|
||||||
|
if let Some(rest) = value.strip_suffix('>')
|
||||||
|
&& let Some((name, address)) = rest.rsplit_once('<')
|
||||||
|
{
|
||||||
|
let name = name.trim();
|
||||||
|
let name = name
|
||||||
|
.strip_prefix('"')
|
||||||
|
.and_then(|n| n.strip_suffix('"'))
|
||||||
|
.unwrap_or(name);
|
||||||
|
return Mailbox::with_name(name, address);
|
||||||
|
}
|
||||||
|
Mailbox::new(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<String> for Mailbox {
|
||||||
|
fn from(value: String) -> Self {
|
||||||
|
Mailbox::from(value.as_str())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&String> for Mailbox {
|
||||||
|
fn from(value: &String) -> Self {
|
||||||
|
Mailbox::from(value.as_str())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<N: Into<String>, A: Into<String>> From<(N, A)> for Mailbox {
|
||||||
|
fn from((name, address): (N, A)) -> Self {
|
||||||
|
Mailbox::with_name(name, address)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Muestra la dirección como `Nombre <dirección>`, o sólo la dirección si no tiene nombre. Es una
|
||||||
|
/// representación para trazas y pruebas, no la codificación de las cabeceras del correo.
|
||||||
|
impl fmt::Display for Mailbox {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match &self.name {
|
||||||
|
Some(name) => write!(f, "{name} <{}>", self.address),
|
||||||
|
None => f.write_str(&self.address),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
87
extensions/pagetop-mail/src/outbox.rs
Normal file
87
extensions/pagetop-mail/src/outbox.rs
Normal file
|
|
@ -0,0 +1,87 @@
|
||||||
|
//! Correos guardados en memoria por el transporte `"memory"`, para comprobarlos en las pruebas.
|
||||||
|
//!
|
||||||
|
//! Con `transport = "memory"` en la sección `[mail]` de la configuración de pruebas, los correos no
|
||||||
|
//! se envían: se guardan aquí, ya completos (con el remitente por defecto y el documento HTML con
|
||||||
|
//! el diseño común), y las pruebas los recogen con [`take()`] o [`take_to()`].
|
||||||
|
//!
|
||||||
|
//! Los correos se acumulan mientras nadie los recoja, así que este transporte no debe usarse fuera
|
||||||
|
//! de las pruebas.
|
||||||
|
//!
|
||||||
|
//! # Ejemplo
|
||||||
|
//!
|
||||||
|
//! ```rust,no_run
|
||||||
|
//! use pagetop::prelude::*;
|
||||||
|
//! use pagetop_mail::prelude::*;
|
||||||
|
//! use pagetop_mail::outbox;
|
||||||
|
//!
|
||||||
|
//! #[pagetop::test]
|
||||||
|
//! async fn sends_welcome_email() {
|
||||||
|
//! // ... ejecuta lo que debe enviar el correo a ana@example.com ...
|
||||||
|
//!
|
||||||
|
//! let sent = outbox::take_to("ana@example.com");
|
||||||
|
//! assert_eq!(sent.len(), 1);
|
||||||
|
//! assert_eq!(sent[0].email().subject(), "Bienvenida");
|
||||||
|
//! }
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! Las pruebas de un mismo binario se ejecutan en paralelo y comparten estos correos: con
|
||||||
|
//! [`take_to()`] cada prueba recoge sólo los de sus destinatarios, sin llevarse los de otras.
|
||||||
|
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
|
use crate::Email;
|
||||||
|
|
||||||
|
use std::sync::{Mutex, MutexGuard, PoisonError};
|
||||||
|
|
||||||
|
static OUTBOX: Mutex<Vec<SentEmail>> = Mutex::new(Vec::new());
|
||||||
|
|
||||||
|
/// Correo guardado por el transporte `"memory"`.
|
||||||
|
#[derive(Clone, Debug, Getters)]
|
||||||
|
pub struct SentEmail {
|
||||||
|
/// El correo tal como se envió, con el remitente y la dirección de respuesta por defecto ya
|
||||||
|
/// aplicados, y el documento HTML completo.
|
||||||
|
email: Email,
|
||||||
|
/// Direcciones a las que se entregó (todas, incluidas las de `Cc` y `Bcc`, o sólo la de
|
||||||
|
/// `mail.redirect_to` si está configurada).
|
||||||
|
envelope_to: Vec<String>,
|
||||||
|
/// Mensaje completo en formato RFC 5322, con cabeceras y partes codificadas.
|
||||||
|
raw: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SentEmail {
|
||||||
|
/// Indica si el correo se entregó a la dirección dada (sin distinguir mayúsculas).
|
||||||
|
pub fn is_delivered_to(&self, address: &str) -> bool {
|
||||||
|
self.envelope_to
|
||||||
|
.iter()
|
||||||
|
.any(|to| to.eq_ignore_ascii_case(address.trim()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Recoge todos los correos guardados, en el orden en que se enviaron.
|
||||||
|
pub fn take() -> Vec<SentEmail> {
|
||||||
|
std::mem::take(&mut *lock())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Recoge los correos entregados a la dirección dada, en el orden en que se enviaron, y deja los
|
||||||
|
/// demás.
|
||||||
|
pub fn take_to(address: &str) -> Vec<SentEmail> {
|
||||||
|
let mut outbox = lock();
|
||||||
|
let (taken, kept) = outbox
|
||||||
|
.drain(..)
|
||||||
|
.partition(|sent: &SentEmail| sent.is_delivered_to(address));
|
||||||
|
*outbox = kept;
|
||||||
|
taken
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn push(email: Email, envelope_to: Vec<String>, raw: Vec<u8>) {
|
||||||
|
lock().push(SentEmail {
|
||||||
|
email,
|
||||||
|
envelope_to,
|
||||||
|
raw: String::from_utf8_lossy(&raw).into_owned(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Una prueba que falla con el bloqueo tomado no debe impedir que las demás sigan usándolo.
|
||||||
|
fn lock() -> MutexGuard<'static, Vec<SentEmail>> {
|
||||||
|
OUTBOX.lock().unwrap_or_else(PoisonError::into_inner)
|
||||||
|
}
|
||||||
248
extensions/pagetop-mail/src/preview.rs
Normal file
248
extensions/pagetop-mail/src/preview.rs
Normal file
|
|
@ -0,0 +1,248 @@
|
||||||
|
//! Vistas previas de los correos en el navegador ([`DeclareMailPreviews`]).
|
||||||
|
//!
|
||||||
|
//! Con `previews = true` en la sección `[mail]`, la aplicación ofrece en [`PREVIEW_PATH`] la lista
|
||||||
|
//! de los correos que declaran las extensiones, y una página para cada uno con sus cabeceras, el
|
||||||
|
//! HTML tal como se enviaría (con el diseño común), su texto plano y sus adjuntos. Así se diseñan y
|
||||||
|
//! revisan los correos sin enviarlos.
|
||||||
|
//!
|
||||||
|
//! Las vistas previas usan datos de ejemplo y no envían nada, pero muestran las plantillas a
|
||||||
|
//! cualquiera que conozca la ruta: **actívalas sólo en desarrollo**.
|
||||||
|
//!
|
||||||
|
//! Cada vista previa se genera con el contexto de la petición, así que se puede ver en otro idioma
|
||||||
|
//! añadiendo `?lang=` a la ruta (p. ej. `/mail/preview/user.password_reset?lang=en-US`), si la
|
||||||
|
//! negociación de idioma lo permite.
|
||||||
|
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
|
use crate::{Email, LOCALES_MAIL, transport};
|
||||||
|
|
||||||
|
/// Ruta de la lista de vistas previas. Cada correo se ve en `{PREVIEW_PATH}/{clave}`.
|
||||||
|
pub const PREVIEW_PATH: &str = "/mail/preview";
|
||||||
|
|
||||||
|
/// Tipo de función que genera un correo de ejemplo para su vista previa.
|
||||||
|
///
|
||||||
|
/// Recibe el contexto de la petición, con su idioma, y devuelve el correo como se enviaría, con
|
||||||
|
/// datos de ejemplo. Para que la vista previa siga el idioma de la petición, el correo debe crearse
|
||||||
|
/// con [`Email::from_template()`] o indicar el idioma con [`Email::with_langid()`].
|
||||||
|
pub type FnMailPreview = fn(cx: &Context) -> Email;
|
||||||
|
|
||||||
|
/// Tipo de función que declara vistas previas en un [`MailPreviews`].
|
||||||
|
pub type FnDeclareMailPreviews = fn(previews: &mut MailPreviews);
|
||||||
|
|
||||||
|
/// Vistas previas declaradas por las extensiones. Ver [`DeclareMailPreviews`].
|
||||||
|
#[derive(AutoDefault)]
|
||||||
|
pub struct MailPreviews {
|
||||||
|
previews: Vec<MailPreview>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct MailPreview {
|
||||||
|
key: &'static str,
|
||||||
|
title: Lc,
|
||||||
|
build: FnMailPreview,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MailPreviews {
|
||||||
|
/// Añade la vista previa de un correo.
|
||||||
|
///
|
||||||
|
/// - `key`: identificador único, que forma parte de la ruta (p. ej. `"shop.order_shipped"`).
|
||||||
|
/// Conviene empezarlo por el nombre de la extensión.
|
||||||
|
/// - `title`: título descriptivo para la lista.
|
||||||
|
/// - `build`: función que genera el correo con datos de ejemplo.
|
||||||
|
pub fn add(&mut self, key: &'static str, title: Lc, build: FnMailPreview) {
|
||||||
|
self.previews.push(MailPreview { key, title, build });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recoge las vistas previas de todas las extensiones, ordenadas por su clave.
|
||||||
|
fn collect() -> Self {
|
||||||
|
let mut previews = MailPreviews::default();
|
||||||
|
dispatch_actions(|action: &DeclareMailPreviews| (action.f)(&mut previews));
|
||||||
|
previews.previews.sort_by_key(|preview| preview.key);
|
||||||
|
previews
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Acción para declarar vistas previas de correos.
|
||||||
|
///
|
||||||
|
/// Cada extensión que envía correos puede registrar esta acción para que sus correos se puedan
|
||||||
|
/// revisar en el navegador con datos de ejemplo (ver la [documentación del módulo](self)).
|
||||||
|
///
|
||||||
|
/// # Ejemplo
|
||||||
|
///
|
||||||
|
/// ```rust,no_run
|
||||||
|
/// use pagetop::prelude::*;
|
||||||
|
/// use pagetop_mail::prelude::*;
|
||||||
|
///
|
||||||
|
/// fn order_shipped(cx: &Context) -> Email {
|
||||||
|
/// Email::new()
|
||||||
|
/// .with_to("cliente@example.com")
|
||||||
|
/// .with_subject("Tu pedido ha salido")
|
||||||
|
/// .with_html(html! { p { "Tu pedido " strong { "1234" } " ha salido hoy." } })
|
||||||
|
/// .with_langid(cx)
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// fn declare_previews(previews: &mut MailPreviews) {
|
||||||
|
/// previews.add("shop.order_shipped", Lc::n("Pedido enviado"), order_shipped);
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// struct Shop;
|
||||||
|
///
|
||||||
|
/// #[async_trait]
|
||||||
|
/// impl Extension for Shop {
|
||||||
|
/// fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||||
|
/// vec![&pagetop_mail::Mail]
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// fn actions(&self) -> Vec<ActionBox> {
|
||||||
|
/// actions![DeclareMailPreviews::new(declare_previews)]
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
pub struct DeclareMailPreviews {
|
||||||
|
f: FnDeclareMailPreviews,
|
||||||
|
weight: Weight,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ActionDispatcher for DeclareMailPreviews {
|
||||||
|
fn weight(&self) -> Weight {
|
||||||
|
self.weight
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DeclareMailPreviews {
|
||||||
|
/// Registra una función que declara vistas previas.
|
||||||
|
pub fn new(f: FnDeclareMailPreviews) -> Self {
|
||||||
|
DeclareMailPreviews { f, weight: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opcional. Las acciones de menor peso se aplican antes. Se pueden usar valores negativos.
|
||||||
|
pub fn with_weight(mut self, value: Weight) -> Self {
|
||||||
|
self.weight = value;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// **< Handlers >***********************************************************************************
|
||||||
|
|
||||||
|
// GET {PREVIEW_PATH} - Lista de las vistas previas.
|
||||||
|
pub(crate) async fn list_get(request: HttpRequest) -> Result<Markup, ErrorPage> {
|
||||||
|
Page::new(request)
|
||||||
|
.with_title(Lc::t("preview_title", &LOCALES_MAIL))
|
||||||
|
.with_child(Html::with(|cx| {
|
||||||
|
let previews = MailPreviews::collect();
|
||||||
|
html! {
|
||||||
|
h1 { (Lc::t("preview_title", &LOCALES_MAIL).using(cx)) }
|
||||||
|
@if previews.previews.is_empty() {
|
||||||
|
p { (Lc::t("preview_empty", &LOCALES_MAIL).using(cx)) }
|
||||||
|
} @else {
|
||||||
|
ul {
|
||||||
|
@for preview in &previews.previews {
|
||||||
|
li {
|
||||||
|
a href=(cx.route(preview_path(preview.key))) {
|
||||||
|
(preview.title.using(cx))
|
||||||
|
}
|
||||||
|
" "
|
||||||
|
code { (preview.key) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}))
|
||||||
|
.render()
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET {PREVIEW_PATH}/{key} - Vista previa de un correo.
|
||||||
|
pub(crate) async fn preview_get(
|
||||||
|
request: HttpRequest,
|
||||||
|
web::Path(key): web::Path<String>,
|
||||||
|
) -> Result<Markup, ErrorPage> {
|
||||||
|
let previews = MailPreviews::collect();
|
||||||
|
let Some(preview) = previews.previews.iter().find(|p| p.key == key) else {
|
||||||
|
return Err(ErrorPage::NotFound(Some(request)));
|
||||||
|
};
|
||||||
|
let cx = Context::new(request.clone());
|
||||||
|
let email = transport::prepare_preview((preview.build)(&cx));
|
||||||
|
let title = preview.title.clone();
|
||||||
|
Page::new(request)
|
||||||
|
.with_title(title.clone())
|
||||||
|
.with_child(Html::with(move |cx| render_preview(cx, &title, &email)))
|
||||||
|
.render()
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
fn preview_path(key: &str) -> String {
|
||||||
|
util::join!(PREVIEW_PATH, "/", key)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn render_preview(cx: &mut Context, title: &Lc, email: &Email) -> Markup {
|
||||||
|
let none = Lc::t("preview_none", &LOCALES_MAIL);
|
||||||
|
let list = |mailboxes: &[crate::Mailbox]| {
|
||||||
|
let mut list = String::new();
|
||||||
|
for mailbox in mailboxes {
|
||||||
|
if !list.is_empty() {
|
||||||
|
list.push_str(", ");
|
||||||
|
}
|
||||||
|
list.push_str(&mailbox.to_string());
|
||||||
|
}
|
||||||
|
list
|
||||||
|
};
|
||||||
|
let headers = [
|
||||||
|
("preview_from", email.from().map(ToString::to_string)),
|
||||||
|
(
|
||||||
|
"preview_reply_to",
|
||||||
|
email.reply_to().map(ToString::to_string),
|
||||||
|
),
|
||||||
|
("preview_to", Some(list(email.to()))),
|
||||||
|
("preview_cc", Some(list(email.cc()))),
|
||||||
|
("preview_bcc", Some(list(email.bcc()))),
|
||||||
|
("preview_subject", Some(email.subject().to_owned())),
|
||||||
|
];
|
||||||
|
html! {
|
||||||
|
p { a href=(cx.route(PREVIEW_PATH)) { (Lc::t("preview_back", &LOCALES_MAIL).using(cx)) } }
|
||||||
|
h1 { (title.using(cx)) }
|
||||||
|
dl {
|
||||||
|
@for (label, value) in headers {
|
||||||
|
dt { (Lc::t(label, &LOCALES_MAIL).using(cx)) }
|
||||||
|
dd {
|
||||||
|
@match value.filter(|v| !v.is_empty()) {
|
||||||
|
Some(value) => (value),
|
||||||
|
None => em { (none.using(cx)) },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dt { (Lc::t("preview_attachments", &LOCALES_MAIL).using(cx)) }
|
||||||
|
dd {
|
||||||
|
@if email.attachments().is_empty() {
|
||||||
|
em { (none.using(cx)) }
|
||||||
|
} @else {
|
||||||
|
ul {
|
||||||
|
@for attachment in email.attachments() {
|
||||||
|
li {
|
||||||
|
(attachment.filename()) " (" (attachment.content_type()) ", "
|
||||||
|
(attachment.body().len()) " B"
|
||||||
|
@if let Some(id) = attachment.content_id() {
|
||||||
|
", cid:" (id)
|
||||||
|
}
|
||||||
|
")"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@if let Some(html) = email.html() {
|
||||||
|
h2 { (Lc::t("preview_html", &LOCALES_MAIL).using(cx)) }
|
||||||
|
// `sandbox` vacío aísla el correo: sin scripts, sin formularios y sin navegar desde él.
|
||||||
|
iframe
|
||||||
|
title=[Lc::t("preview_html", &LOCALES_MAIL).lookup(cx)]
|
||||||
|
srcdoc=(html.as_str())
|
||||||
|
sandbox=""
|
||||||
|
style="width: 100%; height: 640px; border: 1px solid #d1d5db;" {}
|
||||||
|
}
|
||||||
|
@if let Some(text) = email.text() {
|
||||||
|
h2 { (Lc::t("preview_text", &LOCALES_MAIL).using(cx)) }
|
||||||
|
pre style="white-space: pre-wrap;" { (text) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
85
extensions/pagetop-mail/src/template.rs
Normal file
85
extensions/pagetop-mail/src/template.rs
Normal file
|
|
@ -0,0 +1,85 @@
|
||||||
|
//! Plantillas de correo ([`MailTemplate`]).
|
||||||
|
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
|
/// Plantilla de correo: asunto, contenido HTML y texto plano generados a partir de unos datos.
|
||||||
|
///
|
||||||
|
/// Una plantilla es un tipo propio con los datos que necesita el correo (nombre del destinatario,
|
||||||
|
/// enlaces, importes...). Sus métodos reciben un [`Context`] con el idioma del destinatario, así
|
||||||
|
/// que los textos se escriben con [`Lc`] y el HTML con [`html!`], igual que en un componente, y
|
||||||
|
/// las fechas se formatean con los métodos de [`Contextual`].
|
||||||
|
///
|
||||||
|
/// El correo se crea con [`Email::from_template()`](crate::Email::from_template), que llama a los
|
||||||
|
/// tres métodos. El HTML es sólo el **contenido**: al enviarlo se envuelve en el diseño común de
|
||||||
|
/// los correos (ver [`RenderMailLayout`](crate::RenderMailLayout)). El texto plano es opcional: si
|
||||||
|
/// la plantilla sólo genera HTML, al enviar el correo se obtiene a partir de él. Escríbelo sólo si
|
||||||
|
/// el generado no queda bien.
|
||||||
|
///
|
||||||
|
/// # Ejemplo
|
||||||
|
///
|
||||||
|
/// ```rust,no_run
|
||||||
|
/// use pagetop::prelude::*;
|
||||||
|
/// use pagetop_mail::prelude::*;
|
||||||
|
///
|
||||||
|
/// include_locales!(LOCALES_SHOP);
|
||||||
|
///
|
||||||
|
/// struct OrderShipped {
|
||||||
|
/// customer: String,
|
||||||
|
/// order: u32,
|
||||||
|
/// tracking_url: String,
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// impl MailTemplate for OrderShipped {
|
||||||
|
/// fn subject(&self, cx: &Context) -> String {
|
||||||
|
/// Lc::t("mail-shipped-subject", &LOCALES_SHOP)
|
||||||
|
/// .with_arg("order", self.order.to_string())
|
||||||
|
/// .lookup(cx)
|
||||||
|
/// .unwrap_or_default()
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// fn html(&self, cx: &Context) -> Option<Markup> {
|
||||||
|
/// let greeting =
|
||||||
|
/// Lc::t("mail-greeting", &LOCALES_SHOP).with_arg("name", self.customer.clone());
|
||||||
|
/// let track = Lc::t("mail-track", &LOCALES_SHOP);
|
||||||
|
/// Some(html! {
|
||||||
|
/// p { (greeting.using(cx)) }
|
||||||
|
/// p { a href=(self.tracking_url) { (track.using(cx)) } }
|
||||||
|
/// })
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// fn text(&self, cx: &Context) -> Option<String> {
|
||||||
|
/// let greeting = Lc::t("mail-greeting", &LOCALES_SHOP)
|
||||||
|
/// .with_arg("name", self.customer.clone())
|
||||||
|
/// .lookup(cx)
|
||||||
|
/// .unwrap_or_default();
|
||||||
|
/// Some(util::join!(greeting, "\n\n", &self.tracking_url))
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
///
|
||||||
|
/// async fn notify(language: &impl LangId) -> Result<(), MailError> {
|
||||||
|
/// let template = OrderShipped {
|
||||||
|
/// customer: "Ana".to_string(),
|
||||||
|
/// order: 1234,
|
||||||
|
/// tracking_url: absolute_url("/orders/1234"),
|
||||||
|
/// };
|
||||||
|
/// let cx = Context::default().with_langid(language);
|
||||||
|
/// Email::from_template(&template, &cx)
|
||||||
|
/// .with_to("ana@example.com")
|
||||||
|
/// .send()
|
||||||
|
/// .await
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
pub trait MailTemplate {
|
||||||
|
/// Asunto del correo, en el idioma del contexto.
|
||||||
|
fn subject(&self, cx: &Context) -> String;
|
||||||
|
|
||||||
|
/// Contenido HTML del correo, sin el documento que lo envuelve. Por defecto, ninguno.
|
||||||
|
fn html(&self, _cx: &Context) -> Option<Markup> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Texto plano del correo. Por defecto, ninguno: al enviarlo se genera a partir del HTML.
|
||||||
|
fn text(&self, _cx: &Context) -> Option<String> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
402
extensions/pagetop-mail/src/text.rs
Normal file
402
extensions/pagetop-mail/src/text.rs
Normal file
|
|
@ -0,0 +1,402 @@
|
||||||
|
// Conversión del HTML de un correo en su texto plano alternativo.
|
||||||
|
//
|
||||||
|
// No es un intérprete HTML completo: basta para el HTML de los correos, que normalmente sale de
|
||||||
|
// `html!` y está bien formado. Los bloques (párrafos, encabezados, listas, filas de tabla...) se
|
||||||
|
// separan con saltos de línea, los elementos de lista se marcan con "- ", los enlaces añaden su
|
||||||
|
// dirección entre paréntesis y las imágenes su texto alternativo. Se descartan `head`, `title`,
|
||||||
|
// `style` y `script`, y los comentarios.
|
||||||
|
|
||||||
|
// Elementos que separan párrafos (una línea en blanco) y que separan líneas.
|
||||||
|
const PARAGRAPHS: &[&str] = &[
|
||||||
|
"p",
|
||||||
|
"h1",
|
||||||
|
"h2",
|
||||||
|
"h3",
|
||||||
|
"h4",
|
||||||
|
"h5",
|
||||||
|
"h6",
|
||||||
|
"ul",
|
||||||
|
"ol",
|
||||||
|
"table",
|
||||||
|
"blockquote",
|
||||||
|
"pre",
|
||||||
|
"dl",
|
||||||
|
];
|
||||||
|
const LINES: &[&str] = &[
|
||||||
|
"div", "tr", "li", "dt", "dd", "section", "article", "header", "footer", "body", "html",
|
||||||
|
];
|
||||||
|
// Elementos cuyo contenido no es texto del correo.
|
||||||
|
const SKIPPED: &[&str] = &["head", "title", "style", "script"];
|
||||||
|
|
||||||
|
pub(crate) fn html_to_text(html: &str) -> String {
|
||||||
|
let mut text = Text::default();
|
||||||
|
let mut links: Vec<(usize, Option<String>)> = Vec::new();
|
||||||
|
let mut pre = 0usize;
|
||||||
|
let mut rest = html;
|
||||||
|
|
||||||
|
while let Some(start) = rest.find('<') {
|
||||||
|
text.push(&decode(&rest[..start]), pre > 0);
|
||||||
|
rest = &rest[start..];
|
||||||
|
|
||||||
|
if let Some(comment) = rest.strip_prefix("<!--") {
|
||||||
|
rest = comment.find("-->").map_or("", |end| &comment[end + 3..]);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(tag) = Tag::parse(rest) else {
|
||||||
|
// Un `<` que no abre una etiqueta es texto.
|
||||||
|
text.push("<", pre > 0);
|
||||||
|
rest = &rest[1..];
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
rest = &rest[tag.len..];
|
||||||
|
|
||||||
|
if !tag.closing && SKIPPED.contains(&tag.name.as_str()) {
|
||||||
|
let close = ["</", &tag.name].concat();
|
||||||
|
rest = match find_ignore_case(rest, &close) {
|
||||||
|
Some(pos) => {
|
||||||
|
let after = &rest[pos..];
|
||||||
|
after.find('>').map_or("", |gt| &after[gt + 1..])
|
||||||
|
}
|
||||||
|
None => "",
|
||||||
|
};
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
match (tag.name.as_str(), tag.closing) {
|
||||||
|
("br", _) => text.line_break(),
|
||||||
|
("hr", _) => {
|
||||||
|
text.block(2);
|
||||||
|
text.emit("----");
|
||||||
|
text.block(2);
|
||||||
|
}
|
||||||
|
("li", false) => {
|
||||||
|
text.block(1);
|
||||||
|
text.emit("- ");
|
||||||
|
}
|
||||||
|
("td" | "th", true) => text.space(),
|
||||||
|
("img", _) => {
|
||||||
|
if let Some(alt) = tag.attr("alt").filter(|alt| !alt.trim().is_empty()) {
|
||||||
|
text.push(&alt, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
("a", false) => links.push((text.len(), tag.attr("href"))),
|
||||||
|
("a", true) => {
|
||||||
|
if let Some((start, Some(href))) = links.pop() {
|
||||||
|
let label = text.since(start).trim().to_owned();
|
||||||
|
let target = href.strip_prefix("mailto:").unwrap_or(&href);
|
||||||
|
let is_link = !(href.is_empty()
|
||||||
|
|| href.starts_with('#')
|
||||||
|
|| href.starts_with("cid:")
|
||||||
|
|| href.starts_with("javascript:"));
|
||||||
|
if is_link && label != target && label != href {
|
||||||
|
text.emit_inline(&["(", target, ")"].concat());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
("pre", closing) => {
|
||||||
|
text.block(2);
|
||||||
|
if closing {
|
||||||
|
pre = pre.saturating_sub(1);
|
||||||
|
} else {
|
||||||
|
pre += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(name, _) if PARAGRAPHS.contains(&name) => text.block(2),
|
||||||
|
(name, _) if LINES.contains(&name) => text.block(1),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
text.push(&decode(rest), pre > 0);
|
||||||
|
text.finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Texto en construcción, con los separadores pendientes hasta que llegue más texto: así no quedan
|
||||||
|
// espacios ni saltos de línea sobrantes al principio, al final o entre bloques.
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Text {
|
||||||
|
buf: String,
|
||||||
|
newlines: usize,
|
||||||
|
space: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Text {
|
||||||
|
fn len(&self) -> usize {
|
||||||
|
self.buf.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn since(&self, start: usize) -> &str {
|
||||||
|
self.buf.get(start..).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Añade texto. Fuera de `pre` cualquier secuencia de espacios en blanco cuenta como un espacio.
|
||||||
|
fn push(&mut self, s: &str, preformatted: bool) {
|
||||||
|
if preformatted {
|
||||||
|
if !s.is_empty() {
|
||||||
|
self.flush();
|
||||||
|
self.buf.push_str(s);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for c in s.chars() {
|
||||||
|
if c.is_whitespace() {
|
||||||
|
self.space();
|
||||||
|
} else {
|
||||||
|
self.flush();
|
||||||
|
self.buf.push(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Añade un texto tal cual, tras los separadores pendientes.
|
||||||
|
fn emit(&mut self, s: &str) {
|
||||||
|
self.flush();
|
||||||
|
self.buf.push_str(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Añade un texto separado por un espacio de lo anterior en la misma línea.
|
||||||
|
fn emit_inline(&mut self, s: &str) {
|
||||||
|
self.space();
|
||||||
|
self.emit(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn space(&mut self) {
|
||||||
|
if self.newlines == 0 {
|
||||||
|
self.space = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn line_break(&mut self) {
|
||||||
|
self.newlines = (self.newlines + 1).min(2);
|
||||||
|
self.space = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn block(&mut self, newlines: usize) {
|
||||||
|
self.newlines = self.newlines.max(newlines);
|
||||||
|
self.space = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush(&mut self) {
|
||||||
|
if !self.buf.is_empty() {
|
||||||
|
if self.newlines > 0 {
|
||||||
|
let trimmed = self.buf.trim_end_matches(' ').len();
|
||||||
|
self.buf.truncate(trimmed);
|
||||||
|
for _ in 0..self.newlines {
|
||||||
|
self.buf.push('\n');
|
||||||
|
}
|
||||||
|
} else if self.space && !self.buf.ends_with([' ', '\n']) {
|
||||||
|
self.buf.push(' ');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.newlines = 0;
|
||||||
|
self.space = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finish(self) -> String {
|
||||||
|
let mut out = String::with_capacity(self.buf.len());
|
||||||
|
for line in self.buf.lines() {
|
||||||
|
out.push_str(line.trim_end());
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
out.trim().to_owned()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Etiqueta HTML leída al principio de un texto que empieza por `<`.
|
||||||
|
struct Tag<'a> {
|
||||||
|
name: String,
|
||||||
|
closing: bool,
|
||||||
|
attrs: &'a str,
|
||||||
|
// Longitud de la etiqueta completa, de `<` a `>`.
|
||||||
|
len: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Tag<'a> {
|
||||||
|
fn parse(s: &'a str) -> Option<Self> {
|
||||||
|
let body = s.strip_prefix('<')?;
|
||||||
|
let (closing, body) = match body.strip_prefix('/') {
|
||||||
|
Some(body) => (true, body),
|
||||||
|
None => (false, body),
|
||||||
|
};
|
||||||
|
// `<!DOCTYPE ...>` y similares se leen como etiquetas sin nombre conocido.
|
||||||
|
let first = body.chars().next()?;
|
||||||
|
if !(first.is_ascii_alphabetic() || first == '!') {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
// Busca el `>` final fuera de los valores entre comillas.
|
||||||
|
let mut quote = None;
|
||||||
|
let mut end = None;
|
||||||
|
for (i, c) in body.char_indices() {
|
||||||
|
match (quote, c) {
|
||||||
|
(Some(q), c) if c == q => quote = None,
|
||||||
|
(None, '"' | '\'') => quote = Some(c),
|
||||||
|
(None, '>') => {
|
||||||
|
end = Some(i);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let end = end?;
|
||||||
|
let inner = body[..end].trim_end_matches('/');
|
||||||
|
let name_len = inner
|
||||||
|
.find(|c: char| c.is_whitespace())
|
||||||
|
.unwrap_or(inner.len());
|
||||||
|
Some(Tag {
|
||||||
|
name: inner[..name_len].to_ascii_lowercase(),
|
||||||
|
closing,
|
||||||
|
attrs: &inner[name_len..],
|
||||||
|
len: s.len() - body.len() + end + 1,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Valor del atributo `name`, ya decodificado.
|
||||||
|
fn attr(&self, name: &str) -> Option<String> {
|
||||||
|
let mut rest = self.attrs;
|
||||||
|
loop {
|
||||||
|
rest = rest.trim_start();
|
||||||
|
if rest.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let key_len = rest
|
||||||
|
.find(|c: char| c == '=' || c.is_whitespace())
|
||||||
|
.unwrap_or(rest.len());
|
||||||
|
let key = &rest[..key_len];
|
||||||
|
rest = rest[key_len..].trim_start();
|
||||||
|
let value = match rest.strip_prefix('=') {
|
||||||
|
Some(after) => {
|
||||||
|
let after = after.trim_start();
|
||||||
|
let (value, next) = match after.chars().next() {
|
||||||
|
Some(q @ ('"' | '\'')) => {
|
||||||
|
let inner = &after[1..];
|
||||||
|
let end = inner.find(q).unwrap_or(inner.len());
|
||||||
|
(&inner[..end], inner.get(end + 1..).unwrap_or_default())
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
let end = after.find(char::is_whitespace).unwrap_or(after.len());
|
||||||
|
(&after[..end], &after[end..])
|
||||||
|
}
|
||||||
|
};
|
||||||
|
rest = next;
|
||||||
|
value
|
||||||
|
}
|
||||||
|
None => "",
|
||||||
|
};
|
||||||
|
if key.eq_ignore_ascii_case(name) {
|
||||||
|
return Some(decode(value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Posición de `needle` en `haystack` sin distinguir mayúsculas (ASCII).
|
||||||
|
fn find_ignore_case(haystack: &str, needle: &str) -> Option<usize> {
|
||||||
|
haystack
|
||||||
|
.to_ascii_lowercase()
|
||||||
|
.find(&needle.to_ascii_lowercase())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decodifica las entidades HTML habituales y las numéricas; deja tal cual las desconocidas.
|
||||||
|
fn decode(s: &str) -> String {
|
||||||
|
if !s.contains('&') {
|
||||||
|
return s.to_owned();
|
||||||
|
}
|
||||||
|
let mut out = String::with_capacity(s.len());
|
||||||
|
let mut rest = s;
|
||||||
|
while let Some(amp) = rest.find('&') {
|
||||||
|
out.push_str(&rest[..amp]);
|
||||||
|
rest = &rest[amp..];
|
||||||
|
let decoded = rest.find(';').filter(|&end| end <= 10).and_then(|end| {
|
||||||
|
let entity = &rest[1..end];
|
||||||
|
let c = match entity {
|
||||||
|
"amp" => Some('&'),
|
||||||
|
"lt" => Some('<'),
|
||||||
|
"gt" => Some('>'),
|
||||||
|
"quot" => Some('"'),
|
||||||
|
"apos" => Some('\''),
|
||||||
|
"nbsp" => Some(' '),
|
||||||
|
_ => entity.strip_prefix('#').and_then(|num| {
|
||||||
|
let code = match num.strip_prefix(['x', 'X']) {
|
||||||
|
Some(hex) => u32::from_str_radix(hex, 16).ok(),
|
||||||
|
None => num.parse().ok(),
|
||||||
|
};
|
||||||
|
code.and_then(char::from_u32)
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
c.map(|c| (c, end))
|
||||||
|
});
|
||||||
|
match decoded {
|
||||||
|
Some((c, end)) => {
|
||||||
|
out.push(c);
|
||||||
|
rest = &rest[end + 1..];
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
out.push('&');
|
||||||
|
rest = &rest[1..];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push_str(rest);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::html_to_text;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn blocks_lists_and_line_breaks_become_lines() {
|
||||||
|
let html = "<h1>Title</h1><p>Hello <strong>Ana</strong>,<br>welcome.</p>\
|
||||||
|
<ul><li>One</li><li>Two</li></ul><p>Bye</p>";
|
||||||
|
assert_eq!(
|
||||||
|
html_to_text(html),
|
||||||
|
"Title\n\nHello Ana,\nwelcome.\n\n- One\n- Two\n\nBye"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn whitespace_is_collapsed_outside_pre() {
|
||||||
|
let html = "<p> Lots of\n\n space </p><pre> keep\n this</pre>";
|
||||||
|
assert_eq!(html_to_text(html), "Lots of space\n\n keep\n this");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn links_show_their_target_unless_it_is_the_label() {
|
||||||
|
let html = r##"<p><a href="https://x.com/a?b=1&c=2">Open</a></p>
|
||||||
|
<p><a href="https://x.com">https://x.com</a></p>
|
||||||
|
<p><a href="mailto:ana@example.com">ana@example.com</a></p>
|
||||||
|
<p><a href="mailto:ana@example.com">Write to Ana</a></p>
|
||||||
|
<p><a href="#top">Top</a></p>"##;
|
||||||
|
assert_eq!(
|
||||||
|
html_to_text(html),
|
||||||
|
"Open (https://x.com/a?b=1&c=2)\n\nhttps://x.com\n\nana@example.com\n\n\
|
||||||
|
Write to Ana (ana@example.com)\n\nTop"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn entities_are_decoded() {
|
||||||
|
assert_eq!(
|
||||||
|
html_to_text("<p>a & b <c> "d" 'e' ©</p>"),
|
||||||
|
"a & b <c> \"d\" 'e' ©"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn head_styles_scripts_and_comments_are_dropped() {
|
||||||
|
let html = "<!DOCTYPE html><html><head><title>T</title><style>p{}</style></head>\
|
||||||
|
<body><!-- hidden --><script>x()</script><p>Visible</p></body></html>";
|
||||||
|
assert_eq!(html_to_text(html), "Visible");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tables_and_images_keep_their_text() {
|
||||||
|
let html = r#"<table><tr><td>A</td><td>B</td></tr><tr><td>C</td><td>D</td></tr></table>
|
||||||
|
<p><img src="cid:logo" alt="Logo"> <img src="x.png" alt=""></p>"#;
|
||||||
|
assert_eq!(html_to_text(html), "A B\nC D\n\nLogo");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stray_less_than_is_text() {
|
||||||
|
assert_eq!(html_to_text("<p>1 < 2</p>"), "1 < 2");
|
||||||
|
}
|
||||||
|
}
|
||||||
251
extensions/pagetop-mail/src/transport.rs
Normal file
251
extensions/pagetop-mail/src/transport.rs
Normal file
|
|
@ -0,0 +1,251 @@
|
||||||
|
// Entrega de los correos con el transporte configurado en `[mail]`.
|
||||||
|
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
|
||||||
|
use crate::config::{self, MailTransport, SmtpSecurity, SmtpSettings};
|
||||||
|
use crate::{Email, MailError, Mailbox, outbox};
|
||||||
|
|
||||||
|
use lettre::address::Envelope;
|
||||||
|
use lettre::transport::smtp::PoolConfig;
|
||||||
|
use lettre::transport::smtp::authentication::Credentials;
|
||||||
|
use lettre::transport::smtp::client::{Tls, TlsParameters};
|
||||||
|
use lettre::transport::smtp::extension::ClientId;
|
||||||
|
use lettre::{
|
||||||
|
Address, AsyncFileTransport, AsyncSendmailTransport, AsyncSmtpTransport, AsyncTransport,
|
||||||
|
Tokio1Executor,
|
||||||
|
};
|
||||||
|
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::sync::OnceLock;
|
||||||
|
|
||||||
|
// Transporte y direcciones por defecto, construidos una sola vez a partir de los ajustes.
|
||||||
|
static MAILER: OnceLock<Mailer> = OnceLock::new();
|
||||||
|
|
||||||
|
pub(crate) struct Mailer {
|
||||||
|
transport: Transport,
|
||||||
|
from: Option<Mailbox>,
|
||||||
|
reply_to: Option<Mailbox>,
|
||||||
|
redirect_to: Option<Address>,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Transport {
|
||||||
|
Smtp(AsyncSmtpTransport<Tokio1Executor>),
|
||||||
|
Sendmail(AsyncSendmailTransport<Tokio1Executor>),
|
||||||
|
File(AsyncFileTransport<Tokio1Executor>),
|
||||||
|
Log,
|
||||||
|
Memory,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Devuelve el transporte, construyéndolo en el primer uso. `Mail::initialize()` lo construye al
|
||||||
|
// arrancar para detener la aplicación si los ajustes no son válidos; fuera de una aplicación (p.
|
||||||
|
// ej. en pruebas) se construye en el primer envío.
|
||||||
|
pub(crate) fn mailer() -> Result<&'static Mailer, MailError> {
|
||||||
|
if let Some(mailer) = MAILER.get() {
|
||||||
|
return Ok(mailer);
|
||||||
|
}
|
||||||
|
let mailer = Mailer::from_settings()?;
|
||||||
|
// Si otro hilo se adelanta, se queda el suyo y se descarta éste.
|
||||||
|
Ok(MAILER.get_or_init(|| mailer))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn deliver(email: Email) -> Result<(), MailError> {
|
||||||
|
let mailer = mailer()?;
|
||||||
|
let email = email.prepare(mailer.from.as_ref(), mailer.reply_to.as_ref());
|
||||||
|
let message = email.to_message()?;
|
||||||
|
let envelope = match &mailer.redirect_to {
|
||||||
|
Some(address) => Envelope::new(message.envelope().from().cloned(), vec![address.clone()])
|
||||||
|
.map_err(MailError::Build)?,
|
||||||
|
None => message.envelope().clone(),
|
||||||
|
};
|
||||||
|
let raw = message.formatted();
|
||||||
|
|
||||||
|
match &mailer.transport {
|
||||||
|
Transport::Smtp(smtp) => {
|
||||||
|
smtp.send_raw(&envelope, &raw)
|
||||||
|
.await
|
||||||
|
.map_err(MailError::Smtp)?;
|
||||||
|
}
|
||||||
|
Transport::Sendmail(sendmail) => {
|
||||||
|
sendmail
|
||||||
|
.send_raw(&envelope, &raw)
|
||||||
|
.await
|
||||||
|
.map_err(MailError::Sendmail)?;
|
||||||
|
}
|
||||||
|
Transport::File(file) => {
|
||||||
|
file.send_raw(&envelope, &raw)
|
||||||
|
.await
|
||||||
|
.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 => {
|
||||||
|
outbox::push(email, recipients(&envelope), raw);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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.
|
||||||
|
pub(crate) fn prepare_preview(email: Email) -> Email {
|
||||||
|
let mailer = mailer().ok();
|
||||||
|
email.prepare(
|
||||||
|
mailer.and_then(|m| m.from.as_ref()),
|
||||||
|
mailer.and_then(|m| m.reply_to.as_ref()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Direcciones a las que se entrega el correo.
|
||||||
|
fn recipients(envelope: &Envelope) -> Vec<String> {
|
||||||
|
envelope.to().iter().map(ToString::to_string).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Mailer {
|
||||||
|
fn from_settings() -> Result<Self, MailError> {
|
||||||
|
let settings = &*config::SETTINGS;
|
||||||
|
let transport = match settings.transport {
|
||||||
|
MailTransport::Smtp => Transport::Smtp(smtp_transport(&settings.smtp)?),
|
||||||
|
MailTransport::Sendmail => Transport::Sendmail(match &settings.sendmail.command {
|
||||||
|
Some(command) => AsyncSendmailTransport::new_with_command(command),
|
||||||
|
None => AsyncSendmailTransport::new(),
|
||||||
|
}),
|
||||||
|
MailTransport::File => {
|
||||||
|
let dir = PathBuf::from(&settings.file.dir);
|
||||||
|
std::fs::create_dir_all(&dir).map_err(|source| MailError::CreateDir {
|
||||||
|
path: dir.clone(),
|
||||||
|
source,
|
||||||
|
})?;
|
||||||
|
Transport::File(AsyncFileTransport::new(dir))
|
||||||
|
}
|
||||||
|
MailTransport::Log => Transport::Log,
|
||||||
|
MailTransport::Memory => Transport::Memory,
|
||||||
|
};
|
||||||
|
let redirect_to = match settings.redirect_to.as_deref().and_then(util::non_blank) {
|
||||||
|
Some(address) => Some(address.parse::<Address>().map_err(|source| {
|
||||||
|
invalid_setting(
|
||||||
|
"mail.redirect_to",
|
||||||
|
MailError::InvalidAddress {
|
||||||
|
address: address.to_owned(),
|
||||||
|
source,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})?),
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
if let Some(url) = settings.base_url.as_deref().and_then(util::non_blank)
|
||||||
|
&& !(url.starts_with("http://") || url.starts_with("https://"))
|
||||||
|
{
|
||||||
|
return Err(invalid_setting(
|
||||||
|
"mail.base_url",
|
||||||
|
MailError::InvalidUrl(url.to_owned()),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(Mailer {
|
||||||
|
transport,
|
||||||
|
from: setting_mailbox("mail.from", settings.from.as_deref())?,
|
||||||
|
reply_to: setting_mailbox("mail.reply_to", settings.reply_to.as_deref())?,
|
||||||
|
redirect_to,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Avisa en las trazas de los ajustes que conviene revisar.
|
||||||
|
pub(crate) fn log_startup(&self) {
|
||||||
|
let settings = &*config::SETTINGS;
|
||||||
|
match self.transport {
|
||||||
|
Transport::Log => trace::warn!(
|
||||||
|
"mail.transport is \"log\": emails are written to the log, not delivered"
|
||||||
|
),
|
||||||
|
Transport::Memory => trace::warn!(
|
||||||
|
"mail.transport is \"memory\": emails are kept in memory, not delivered \
|
||||||
|
(tests only)"
|
||||||
|
),
|
||||||
|
Transport::Smtp(_) | Transport::Sendmail(_) | Transport::File(_) => {
|
||||||
|
if self.from.is_none() {
|
||||||
|
trace::warn!("mail.from is not set: every email must set its own sender");
|
||||||
|
}
|
||||||
|
if settings
|
||||||
|
.base_url
|
||||||
|
.as_deref()
|
||||||
|
.and_then(util::non_blank)
|
||||||
|
.is_none()
|
||||||
|
{
|
||||||
|
trace::warn!(
|
||||||
|
"mail.base_url is not set: links in emails point to {}",
|
||||||
|
crate::base_url()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if settings.previews {
|
||||||
|
trace::warn!(
|
||||||
|
"mail.previews is enabled: email previews are public at {} (development only)",
|
||||||
|
crate::preview::PREVIEW_PATH
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if let Some(address) = &self.redirect_to {
|
||||||
|
trace::warn!("mail.redirect_to is set: all emails are delivered only to {address}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn smtp_transport(smtp: &SmtpSettings) -> Result<AsyncSmtpTransport<Tokio1Executor>, MailError> {
|
||||||
|
let tls_parameters = || {
|
||||||
|
TlsParameters::builder(smtp.host.clone())
|
||||||
|
.dangerous_accept_invalid_certs(smtp.accept_invalid_certs)
|
||||||
|
.build()
|
||||||
|
.map_err(|err| invalid_setting("mail.smtp", MailError::Smtp(err)))
|
||||||
|
};
|
||||||
|
let (tls, default_port) = match smtp.security {
|
||||||
|
SmtpSecurity::None => (Tls::None, 25),
|
||||||
|
SmtpSecurity::Opportunistic => (Tls::Opportunistic(tls_parameters()?), 25),
|
||||||
|
SmtpSecurity::StartTls => (Tls::Required(tls_parameters()?), 587),
|
||||||
|
SmtpSecurity::Tls => (Tls::Wrapper(tls_parameters()?), 465),
|
||||||
|
};
|
||||||
|
let mut builder = AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(&smtp.host)
|
||||||
|
.port(smtp.port.unwrap_or(default_port))
|
||||||
|
.tls(tls)
|
||||||
|
.timeout(Some(std::time::Duration::from_secs(smtp.timeout_secs)))
|
||||||
|
.pool_config(PoolConfig::new().max_size(smtp.pool_max_size));
|
||||||
|
if let Some(username) = smtp.username.as_deref().and_then(util::non_blank) {
|
||||||
|
builder = builder.credentials(Credentials::new(
|
||||||
|
username.to_owned(),
|
||||||
|
smtp.password.clone().unwrap_or_default(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if let Some(name) = smtp.hello_name.as_deref().and_then(util::non_blank) {
|
||||||
|
builder = builder.hello_name(ClientId::Domain(name.to_owned()));
|
||||||
|
}
|
||||||
|
Ok(builder.build())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lee una dirección de los ajustes, comprobando que sea válida.
|
||||||
|
fn setting_mailbox(key: &'static str, value: Option<&str>) -> Result<Option<Mailbox>, MailError> {
|
||||||
|
let Some(value) = value.and_then(util::non_blank) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let mailbox = Mailbox::from(value);
|
||||||
|
mailbox
|
||||||
|
.to_lettre()
|
||||||
|
.map_err(|err| invalid_setting(key, err))?;
|
||||||
|
Ok(Some(mailbox))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn invalid_setting(key: &'static str, source: MailError) -> MailError {
|
||||||
|
MailError::InvalidSetting {
|
||||||
|
key,
|
||||||
|
source: Box::new(source),
|
||||||
|
}
|
||||||
|
}
|
||||||
379
extensions/pagetop-mail/tests/email.rs
Normal file
379
extensions/pagetop-mail/tests/email.rs
Normal file
|
|
@ -0,0 +1,379 @@
|
||||||
|
// The tests run with `config/common.toml` of this crate: memory transport, a default sender and
|
||||||
|
// `https://example.com/` as base URL. Tests in a binary run in parallel and share the outbox, so
|
||||||
|
// each test uses its own recipient and collects its emails with `outbox::take_to()`.
|
||||||
|
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
use pagetop_mail::outbox::{self, SentEmail};
|
||||||
|
use pagetop_mail::prelude::*;
|
||||||
|
|
||||||
|
async fn send_one(email: Email, recipient: &str) -> SentEmail {
|
||||||
|
email.send().await.unwrap();
|
||||||
|
let mut sent = outbox::take_to(recipient);
|
||||||
|
assert_eq!(sent.len(), 1, "expected exactly one email for {recipient}");
|
||||||
|
sent.remove(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// **< Mailbox >************************************************************************************
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn mailbox_parses_address_with_and_without_name() {
|
||||||
|
let plain = Mailbox::from(" ana@example.com ");
|
||||||
|
assert_eq!(plain.name(), None);
|
||||||
|
assert_eq!(plain.address(), "ana@example.com");
|
||||||
|
|
||||||
|
let named = Mailbox::from("Ana Pérez <ana@example.com>");
|
||||||
|
assert_eq!(named.name().map(String::as_str), Some("Ana Pérez"));
|
||||||
|
assert_eq!(named.address(), "ana@example.com");
|
||||||
|
|
||||||
|
let quoted = Mailbox::from("\"Pérez, Ana\" <ana@example.com>");
|
||||||
|
assert_eq!(quoted.name().map(String::as_str), Some("Pérez, Ana"));
|
||||||
|
|
||||||
|
let tuple = Mailbox::from((" ", "ana@example.com"));
|
||||||
|
assert_eq!(tuple.name(), None, "a blank name must be dropped");
|
||||||
|
|
||||||
|
assert_eq!(named.to_string(), "Ana Pérez <ana@example.com>");
|
||||||
|
assert_eq!(plain.to_string(), "ana@example.com");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn mailbox_validates_its_address() {
|
||||||
|
assert!(
|
||||||
|
Mailbox::from("Ana Pérez <ana@example.com>")
|
||||||
|
.validate()
|
||||||
|
.is_ok()
|
||||||
|
);
|
||||||
|
for invalid in [
|
||||||
|
"",
|
||||||
|
"ana",
|
||||||
|
"ana@",
|
||||||
|
"@example.com",
|
||||||
|
"ana @example.com",
|
||||||
|
"a@b@example.com",
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
matches!(
|
||||||
|
Mailbox::new(invalid).validate(),
|
||||||
|
Err(MailError::InvalidAddress { .. })
|
||||||
|
),
|
||||||
|
"{invalid:?} must be rejected"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn control_characters_in_names_cannot_inject_headers() {
|
||||||
|
// `lettre` panics on a header with control characters; the name may come from user data.
|
||||||
|
let mailbox = Mailbox::with_name("Ana\r\nBcc: evil@example.com", "control@example.com");
|
||||||
|
assert_eq!(
|
||||||
|
mailbox.name().map(String::as_str),
|
||||||
|
Some("Ana Bcc: evil@example.com")
|
||||||
|
);
|
||||||
|
|
||||||
|
let sent = send_one(
|
||||||
|
Email::new()
|
||||||
|
.with_to(mailbox)
|
||||||
|
.with_subject("Hi\r\nBcc: evil@example.com")
|
||||||
|
.with_text("Hi"),
|
||||||
|
"control@example.com",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(sent.envelope_to(), &["control@example.com".to_string()]);
|
||||||
|
assert!(!sent.raw().contains("\r\nBcc:"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// **< Composition >********************************************************************************
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn text_email_uses_default_sender_and_reaches_every_recipient() {
|
||||||
|
let sent = send_one(
|
||||||
|
Email::new()
|
||||||
|
.with_to("text-to@example.com")
|
||||||
|
.with_cc("text-cc@example.com")
|
||||||
|
.with_bcc("text-bcc@example.com")
|
||||||
|
.with_subject("Plain text")
|
||||||
|
.with_text("Hello"),
|
||||||
|
"text-to@example.com",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let from = sent.email().from().unwrap();
|
||||||
|
assert_eq!(from.address(), "tests@example.com");
|
||||||
|
assert_eq!(sent.envelope_to().len(), 3);
|
||||||
|
assert!(sent.is_delivered_to("TEXT-BCC@example.com"));
|
||||||
|
assert!(sent.raw().contains("Subject: Plain text"));
|
||||||
|
assert!(
|
||||||
|
sent.raw()
|
||||||
|
.lines()
|
||||||
|
.any(|line| line.starts_with("Message-ID: <") && line.ends_with("@example.com>")),
|
||||||
|
"Message-ID must use the sender domain"
|
||||||
|
);
|
||||||
|
assert!(sent.raw().contains("Content-Type: text/plain"));
|
||||||
|
// Bcc recipients get the email but must not appear in its headers.
|
||||||
|
assert!(!sent.raw().contains("text-bcc@example.com"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn explicit_sender_overrides_default_sender() {
|
||||||
|
let sent = send_one(
|
||||||
|
Email::new()
|
||||||
|
.with_from(("Support", "support@example.com"))
|
||||||
|
.with_reply_to("help@example.com")
|
||||||
|
.with_to("override@example.com")
|
||||||
|
.with_text("Hi"),
|
||||||
|
"override@example.com",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
sent.email().from().unwrap().address(),
|
||||||
|
"support@example.com"
|
||||||
|
);
|
||||||
|
assert!(sent.raw().contains("From: Support <support@example.com>"));
|
||||||
|
assert!(sent.raw().contains("Reply-To: help@example.com"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn text_and_html_are_sent_as_alternatives() {
|
||||||
|
let sent = send_one(
|
||||||
|
Email::new()
|
||||||
|
.with_to("alternative@example.com")
|
||||||
|
.with_subject("Both")
|
||||||
|
.with_text("Text version")
|
||||||
|
.with_html(html! { p { "HTML version" } }),
|
||||||
|
"alternative@example.com",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
assert!(sent.raw().contains("multipart/alternative"));
|
||||||
|
assert!(sent.raw().contains("text/plain"));
|
||||||
|
assert!(sent.raw().contains("text/html"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn html_content_is_wrapped_in_the_default_layout() {
|
||||||
|
let sent = send_one(
|
||||||
|
Email::new()
|
||||||
|
.with_to("layout@example.com")
|
||||||
|
.with_subject("Layout <test>")
|
||||||
|
.with_langid(&Locale::resolve("es-ES"))
|
||||||
|
.with_html(html! { p { "Body content" } }),
|
||||||
|
"layout@example.com",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let html = sent.email().html().unwrap().as_str();
|
||||||
|
assert!(html.starts_with("<!DOCTYPE html>"));
|
||||||
|
assert!(html.contains(r#"<html lang="es-ES">"#));
|
||||||
|
assert!(html.contains("<title>Layout <test></title>"));
|
||||||
|
assert!(html.contains("<p>Body content</p>"));
|
||||||
|
assert!(
|
||||||
|
html.contains("Mensaje enviado por"),
|
||||||
|
"footer must follow the email language"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn html_document_is_sent_without_layout() {
|
||||||
|
let sent = send_one(
|
||||||
|
Email::new()
|
||||||
|
.with_to("document@example.com")
|
||||||
|
.with_html_document(html! { html { body { "Own document" } } }),
|
||||||
|
"document@example.com",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
sent.email().html().unwrap().as_str(),
|
||||||
|
"<html><body>Own document</body></html>"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// **< Attachments >********************************************************************************
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn attachments_are_sent_as_mixed_parts_with_guessed_content_type() {
|
||||||
|
let sent = send_one(
|
||||||
|
Email::new()
|
||||||
|
.with_to("attachment@example.com")
|
||||||
|
.with_text("See attached")
|
||||||
|
.with_attachment(Attachment::new("report.pdf", b"%PDF-1.4".to_vec()))
|
||||||
|
.with_attachment(
|
||||||
|
Attachment::new("data.bin", vec![0u8, 1, 2]).with_content_type("text/csv"),
|
||||||
|
),
|
||||||
|
"attachment@example.com",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let raw = sent.raw();
|
||||||
|
assert!(raw.contains("multipart/mixed"));
|
||||||
|
assert!(raw.contains("Content-Type: application/pdf"));
|
||||||
|
assert!(raw.contains(r#"filename="report.pdf""#));
|
||||||
|
assert!(raw.contains("Content-Type: text/csv"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn inline_images_are_related_to_the_html() {
|
||||||
|
let sent = send_one(
|
||||||
|
Email::new()
|
||||||
|
.with_to("inline@example.com")
|
||||||
|
.with_html(html! { img src="cid:logo"; })
|
||||||
|
.with_attachment(
|
||||||
|
Attachment::new("logo.png", vec![137u8, 80, 78, 71]).with_content_id("logo"),
|
||||||
|
),
|
||||||
|
"inline@example.com",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let raw = sent.raw();
|
||||||
|
assert!(raw.contains("multipart/related"));
|
||||||
|
assert!(raw.contains("Content-ID: <logo>"));
|
||||||
|
assert!(!raw.contains("multipart/mixed"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn inline_images_without_html_are_sent_as_attachments() {
|
||||||
|
let sent = send_one(
|
||||||
|
Email::new()
|
||||||
|
.with_to("inline-text@example.com")
|
||||||
|
.with_text("No HTML")
|
||||||
|
.with_attachment(Attachment::new("logo.png", vec![1u8]).with_content_id("logo")),
|
||||||
|
"inline-text@example.com",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
assert!(sent.raw().contains("multipart/mixed"));
|
||||||
|
assert!(!sent.raw().contains("multipart/related"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn attachment_reads_file_from_disk() {
|
||||||
|
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml");
|
||||||
|
let attachment = Attachment::from_path(path).await.unwrap();
|
||||||
|
assert_eq!(attachment.filename(), "Cargo.toml");
|
||||||
|
assert!(!attachment.body().is_empty());
|
||||||
|
assert!(!attachment.is_inline());
|
||||||
|
|
||||||
|
let missing = Attachment::from_path("does/not/exist.pdf").await;
|
||||||
|
assert!(matches!(missing, Err(MailError::ReadAttachment { .. })));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn invalid_content_type_fails_on_send() {
|
||||||
|
let result = Email::new()
|
||||||
|
.with_to("bad-type@example.com")
|
||||||
|
.with_attachment(Attachment::new("x", vec![]).with_content_type("not a type"))
|
||||||
|
.send()
|
||||||
|
.await;
|
||||||
|
assert!(matches!(result, Err(MailError::InvalidContentType(_))));
|
||||||
|
}
|
||||||
|
|
||||||
|
// **< Errors >*************************************************************************************
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn email_without_recipients_fails() {
|
||||||
|
let result = Email::new().with_text("Nobody").send().await;
|
||||||
|
assert!(matches!(result, Err(MailError::NoRecipients)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn invalid_address_fails() {
|
||||||
|
let result = Email::new().with_to("not-an-address").send().await;
|
||||||
|
let Err(MailError::InvalidAddress { address, .. }) = result else {
|
||||||
|
panic!("expected an invalid address error, got {result:?}");
|
||||||
|
};
|
||||||
|
assert_eq!(address, "not-an-address");
|
||||||
|
}
|
||||||
|
|
||||||
|
// **< Templates >**********************************************************************************
|
||||||
|
|
||||||
|
struct Greeting {
|
||||||
|
name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MailTemplate for Greeting {
|
||||||
|
fn subject(&self, cx: &Context) -> String {
|
||||||
|
util::join!("Hello ", &self.name, " [", cx.langid().to_string(), "]")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn html(&self, _cx: &Context) -> Option<Markup> {
|
||||||
|
Some(html! { p { "Hello " (self.name) } })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn text(&self, _cx: &Context) -> Option<String> {
|
||||||
|
Some(util::join!("Hello ", &self.name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn template_builds_subject_html_and_text_in_the_context_language() {
|
||||||
|
let cx = Context::default().with_langid(&Locale::resolve("es-ES"));
|
||||||
|
let email = Email::from_template(
|
||||||
|
&Greeting {
|
||||||
|
name: "Ana".to_string(),
|
||||||
|
},
|
||||||
|
&cx,
|
||||||
|
)
|
||||||
|
.with_to("template@example.com");
|
||||||
|
|
||||||
|
assert_eq!(email.subject(), "Hello Ana [es-ES]");
|
||||||
|
assert_eq!(email.text().map(String::as_str), Some("Hello Ana"));
|
||||||
|
assert_eq!(email.langid().to_string(), "es-ES");
|
||||||
|
|
||||||
|
let sent = send_one(email, "template@example.com").await;
|
||||||
|
let html = sent.email().html().unwrap().as_str();
|
||||||
|
assert!(html.contains(r#"<html lang="es-ES">"#));
|
||||||
|
assert!(html.contains("<p>Hello Ana</p>"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// **< URLs >***************************************************************************************
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn absolute_url_prepends_the_configured_base_url() {
|
||||||
|
assert_eq!(
|
||||||
|
absolute_url("/user/verify"),
|
||||||
|
"https://example.com/user/verify"
|
||||||
|
);
|
||||||
|
assert_eq!(absolute_url("user"), "https://example.com/user");
|
||||||
|
assert_eq!(
|
||||||
|
absolute_url(RoutePath::new("/search").with_param("q", "mail")),
|
||||||
|
"https://example.com/search?q=mail"
|
||||||
|
);
|
||||||
|
assert_eq!(absolute_url("https://other.org/x"), "https://other.org/x");
|
||||||
|
}
|
||||||
|
|
||||||
|
// **< Plain text from HTML >***********************************************************************
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn html_only_email_gets_plain_text_from_its_content() {
|
||||||
|
let sent = send_one(
|
||||||
|
Email::new()
|
||||||
|
.with_to("auto-text@example.com")
|
||||||
|
.with_html(html! {
|
||||||
|
p { "Hello " strong { "Ana" } }
|
||||||
|
p { a href="https://example.com/x" { "Open" } }
|
||||||
|
}),
|
||||||
|
"auto-text@example.com",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
// Generated from the content, before the layout: the footer is not part of it.
|
||||||
|
assert_eq!(
|
||||||
|
sent.email().text().map(String::as_str),
|
||||||
|
Some("Hello Ana\n\nOpen (https://example.com/x)")
|
||||||
|
);
|
||||||
|
assert!(sent.raw().contains("multipart/alternative"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn explicit_text_is_not_replaced() {
|
||||||
|
let sent = send_one(
|
||||||
|
Email::new()
|
||||||
|
.with_to("own-text@example.com")
|
||||||
|
.with_text("Own text")
|
||||||
|
.with_html(html! { p { "HTML" } }),
|
||||||
|
"own-text@example.com",
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
assert_eq!(sent.email().text().map(String::as_str), Some("Own text"));
|
||||||
|
}
|
||||||
55
extensions/pagetop-mail/tests/layout.rs
Normal file
55
extensions/pagetop-mail/tests/layout.rs
Normal file
|
|
@ -0,0 +1,55 @@
|
||||||
|
// The action registry is built once per test binary, so the custom layout lives in its own file.
|
||||||
|
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
use pagetop_mail::outbox;
|
||||||
|
use pagetop_mail::prelude::*;
|
||||||
|
|
||||||
|
struct TestApp;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Extension for TestApp {
|
||||||
|
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||||
|
vec![&pagetop_mail::Mail]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actions(&self) -> Vec<ActionBox> {
|
||||||
|
actions![
|
||||||
|
RenderMailLayout::new(heavier_layout).with_weight(10),
|
||||||
|
RenderMailLayout::new(custom_layout),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn custom_layout(cx: &Context, email: &Email, content: &Markup) -> Markup {
|
||||||
|
html! {
|
||||||
|
html lang=(cx.langid().to_string()) {
|
||||||
|
body { h1 { (email.subject()) } div class="custom" { (content) } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn heavier_layout(_cx: &Context, _email: &Email, _content: &Markup) -> Markup {
|
||||||
|
html! { "heavier layout must not be used" }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn lightest_registered_layout_replaces_the_default_one() {
|
||||||
|
Application::prepare(&TestApp).await;
|
||||||
|
|
||||||
|
Email::new()
|
||||||
|
.with_to("custom-layout@example.com")
|
||||||
|
.with_subject("Custom")
|
||||||
|
.with_html(html! { p { "Content" } })
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let sent = outbox::take_to("custom-layout@example.com");
|
||||||
|
assert_eq!(
|
||||||
|
sent[0].email().html().unwrap().as_str(),
|
||||||
|
concat!(
|
||||||
|
r#"<html lang="en-US"><body><h1>Custom</h1>"#,
|
||||||
|
r#"<div class="custom"><p>Content</p></div></body></html>"#
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
64
extensions/pagetop-mail/tests/preview.rs
Normal file
64
extensions/pagetop-mail/tests/preview.rs
Normal file
|
|
@ -0,0 +1,64 @@
|
||||||
|
// `config/common.toml` enables the previews. The action registry is built once per test binary, so
|
||||||
|
// the previews declared here live in their own file.
|
||||||
|
|
||||||
|
use pagetop::prelude::*;
|
||||||
|
use pagetop_mail::prelude::*;
|
||||||
|
|
||||||
|
struct TestApp;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl Extension for TestApp {
|
||||||
|
fn dependencies(&self) -> Vec<ExtensionRef> {
|
||||||
|
vec![&pagetop_mail::Mail]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn actions(&self) -> Vec<ActionBox> {
|
||||||
|
actions![DeclareMailPreviews::new(declare_previews)]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn declare_previews(previews: &mut MailPreviews) {
|
||||||
|
previews.add("test.welcome", Lc::n("Welcome email"), welcome);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn welcome(cx: &Context) -> Email {
|
||||||
|
Email::new()
|
||||||
|
.with_to("Ana <ana@example.com>")
|
||||||
|
.with_subject("Welcome")
|
||||||
|
.with_html(html! { p { "Hello " a href="https://example.com/start" { "start" } } })
|
||||||
|
.with_attachment(Attachment::new("terms.pdf", b"%PDF".to_vec()))
|
||||||
|
.with_langid(cx)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn get(app: &Router, uri: &str) -> (web::http::StatusCode, String) {
|
||||||
|
let req = web::test::TestRequest::get().uri(uri).to_request();
|
||||||
|
let resp = web::test::send_request(app, req).await;
|
||||||
|
let status = resp.status();
|
||||||
|
(status, web::test::read_body_text(resp).await)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[pagetop::test]
|
||||||
|
async fn previews_are_listed_and_rendered_without_sending() {
|
||||||
|
let app = web::test::init_router(Application::prepare(&TestApp).await.test());
|
||||||
|
|
||||||
|
let (status, body) = get(&app, "/mail/preview").await;
|
||||||
|
assert_eq!(status, web::http::StatusCode::OK);
|
||||||
|
assert!(body.contains(r#"href="/mail/preview/test.welcome""#));
|
||||||
|
assert!(body.contains("Welcome email"));
|
||||||
|
|
||||||
|
let (status, body) = get(&app, "/mail/preview/test.welcome").await;
|
||||||
|
assert_eq!(status, web::http::StatusCode::OK);
|
||||||
|
// Default sender applied, as when sending.
|
||||||
|
assert!(body.contains("PageTop Tests <tests@example.com>"));
|
||||||
|
assert!(body.contains("Ana <ana@example.com>"));
|
||||||
|
// The HTML goes in an isolated iframe, already wrapped in the layout.
|
||||||
|
assert!(body.contains("srcdoc=\"<!DOCTYPE html>"));
|
||||||
|
assert!(body.contains(r#"sandbox="""#));
|
||||||
|
// Generated plain text and attachments.
|
||||||
|
assert!(body.contains("Hello start (https://example.com/start)"));
|
||||||
|
assert!(body.contains("terms.pdf (application/pdf, 4 B)"));
|
||||||
|
assert!(pagetop_mail::outbox::take_to("ana@example.com").is_empty());
|
||||||
|
|
||||||
|
let (status, _) = get(&app, "/mail/preview/missing").await;
|
||||||
|
assert_eq!(status, web::http::StatusCode::NOT_FOUND);
|
||||||
|
}
|
||||||
|
|
@ -67,6 +67,7 @@ case "$CRATE" in
|
||||||
--exclude-path "extensions/pagetop-aliner/**/*"
|
--exclude-path "extensions/pagetop-aliner/**/*"
|
||||||
--exclude-path "extensions/pagetop-bootsier/**/*"
|
--exclude-path "extensions/pagetop-bootsier/**/*"
|
||||||
--exclude-path "extensions/pagetop-htmx/**/*"
|
--exclude-path "extensions/pagetop-htmx/**/*"
|
||||||
|
--exclude-path "extensions/pagetop-mail/**/*"
|
||||||
--exclude-path "extensions/pagetop-seaorm/**/*"
|
--exclude-path "extensions/pagetop-seaorm/**/*"
|
||||||
--exclude-path "extensions/pagetop-user/**/*"
|
--exclude-path "extensions/pagetop-user/**/*"
|
||||||
)
|
)
|
||||||
|
|
@ -87,6 +88,10 @@ case "$CRATE" in
|
||||||
CHANGELOG_FILE="extensions/pagetop-htmx/CHANGELOG.md"
|
CHANGELOG_FILE="extensions/pagetop-htmx/CHANGELOG.md"
|
||||||
PATH_FLAGS=(--include-path "extensions/pagetop-htmx/**/*")
|
PATH_FLAGS=(--include-path "extensions/pagetop-htmx/**/*")
|
||||||
;;
|
;;
|
||||||
|
pagetop-mail)
|
||||||
|
CHANGELOG_FILE="extensions/pagetop-mail/CHANGELOG.md"
|
||||||
|
PATH_FLAGS=(--include-path "extensions/pagetop-mail/**/*")
|
||||||
|
;;
|
||||||
pagetop-seaorm)
|
pagetop-seaorm)
|
||||||
CHANGELOG_FILE="extensions/pagetop-seaorm/CHANGELOG.md"
|
CHANGELOG_FILE="extensions/pagetop-seaorm/CHANGELOG.md"
|
||||||
PATH_FLAGS=(--include-path "extensions/pagetop-seaorm/**/*")
|
PATH_FLAGS=(--include-path "extensions/pagetop-seaorm/**/*")
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue