After configuring email sender

This commit is contained in:
Your Name 2026-11-01 19:52:40 +02:00
parent d392ae0867
commit e68287affd
7 changed files with 135 additions and 50 deletions

View File

@ -110,6 +110,21 @@ CERTBOT_DOMAIN1=tloto.net
# Second name on the same certificate (www). Used by ssl:dns-init --expand.
CERTBOT_DOMAIN2=www.tloto.net
APP_PUBLIC_URL=https://tloto.net:9443
# --- SMTP / Email Sender (Microsoft 365 via GoDaddy) ---
# Authenticate as the primary mailbox; display an alias as From (no extra paid mailbox).
# Prerequisite: info@tloto.net is an alias of admin@tloto.net with Send As allowed in M365.
EMAIL_TRANSPORT=smtp
SMTP_HOST=smtp.office365.com
SMTP_PORT=587
SMTP_SECURE=false
SMTP_USER=admin@tloto.net
SMTP_PASS=your-admin-mailbox-password
EMAIL_FROM="Tloto" <info@tloto.net>
EMAIL_REPLY_TO=info@tloto.net
VERIFY_EMAIL_PATH=/verify-email
RESET_PASSWORD_PATH=/reset-password
PASSWORD_RESET_EXPIRY_HOURS=1
# Admin page Options → SSL certificates (live TLS probes from the backend container).
# Defaults to APP_PUBLIC_URL host + www. Override if apex is served on gateway :443:
# SSL_STATUS_HOSTS=tloto.net,www.tloto.net

View File

@ -67,23 +67,20 @@ APP_PUBLIC_URL=http://localhost:5173
# PROMETHEUS_URL=http://prometheus:9090
# VPS_MONITOR_TIMEOUT_MS=8000
# EMAIL_TRANSPORT=console # omit or set smtp when SMTP_* vars are configured
# SMTP_HOST=smtp.gmail.com
# SMTP_PORT=587
# SMTP_SECURE=false
# SMTP_USER=your@gmail.com
# SMTP_PASS=your-app-password
# EMAIL_FROM=your@gmail.com
VERIFY_EMAIL_PATH=/verify-email
RESET_PASSWORD_PATH=/reset-password
PASSWORD_RESET_EXPIRY_HOURS=1
# SMTP (required when EMAIL_TRANSPORT=smtp)
# SMTP_HOST=smtp.example.com
# SMTP (required when EMAIL_TRANSPORT=smtp). Prefer repo-root .env on VPS (Compose injects these).
# Tloto production = Microsoft 365 / GoDaddy only (not Gmail):
# EMAIL_TRANSPORT=smtp
# SMTP_HOST=smtp.office365.com
# SMTP_PORT=587
# SMTP_SECURE=false
# SMTP_USER=your-smtp-user
# SMTP_PASS=your-smtp-password
# EMAIL_FROM=Tloto <noreply@yourdomain.com>
# SMTP_USER=admin@tloto.net
# SMTP_PASS=your-mailbox-password-or-app-password
# EMAIL_FROM="Tloto" <info@tloto.net>
# EMAIL_REPLY_TO=info@tloto.net
# Candle Predict engine (performance tuning for production scale)
# CANDLE_PREDICT_ENGINE_TICK_MS=3000 # main loop interval (ms)

View File

@ -14,6 +14,7 @@ const MAIL_ENV_KEYS = [
'SMTP_USER',
'SMTP_PASS',
'EMAIL_FROM',
'EMAIL_REPLY_TO',
'APP_PUBLIC_URL',
'VERIFY_EMAIL_PATH',
'RESET_PASSWORD_PATH',
@ -238,7 +239,10 @@ export const config = {
secure: process.env.SMTP_SECURE === 'true',
user: (process.env.SMTP_USER || '').trim(),
pass: (process.env.SMTP_PASS || '').replace(/\s+/g, ''),
/** Visible From (can be an alias, e.g. info@ while SMTP_USER is admin@). */
from: process.env.EMAIL_FROM || '',
/** Optional Reply-To (defaults to the address inside EMAIL_FROM). */
replyTo: (process.env.EMAIL_REPLY_TO || '').trim(),
verificationExpiryHours: parseInt(process.env.EMAIL_VERIFICATION_EXPIRY_HOURS || '24', 10),
verificationSendMax: parseInt(process.env.EMAIL_VERIFICATION_SEND_MAX || '5', 10),
passwordResetExpiryHours: parseInt(process.env.PASSWORD_RESET_EXPIRY_HOURS || '1', 10),

View File

@ -1,15 +1,22 @@
/**
* Verify SMTP credentials (e.g. after configuring Gmail App Password on VPS).
* Verify SMTP credentials and print the resolved From / Reply-To headers.
*
* From repo root:
* npm run phase-b:verify-smtp
*
* From backend/ (DB not required):
* npm run verify-smtp
* Optional test send (does not log the password):
* SMTP_TEST_TO=you@example.com npm run phase-b:verify-smtp
*/
import nodemailer from 'nodemailer';
import { config } from '../config';
import { isSmtpConfigured, verifySmtpConnection } from '../services/emailService';
import {
isSmtpConfigured,
resolveFromAddress,
resolveReplyToAddress,
verifySmtpConnection,
normalizeSmtpPass,
} from '../services/emailService';
async function main(): Promise<void> {
console.log('Email transport:', config.email.transport);
@ -24,25 +31,68 @@ async function main(): Promise<void> {
process.exit(1);
}
const from = resolveFromAddress();
const replyTo = resolveReplyToAddress();
console.log('SMTP host:', config.email.host);
console.log('SMTP port:', config.email.port);
console.log('SMTP user:', config.email.user);
console.log('EMAIL_FROM:', config.email.from);
console.log('SMTP user (auth):', config.email.user);
console.log('EMAIL_FROM (env):', config.email.from);
console.log('Resolved From:', from);
console.log('Resolved Reply-To:', replyTo || '(none)');
await verifySmtpConnection();
console.log('SMTP connection OK — credentials accepted by the mail server.');
const testTo = (process.env.SMTP_TEST_TO || '').trim();
if (testTo) {
const transport = nodemailer.createTransport({
host: config.email.host,
port: config.email.port,
secure: config.email.port === 465 ? true : config.email.secure,
requireTLS: config.email.port === 587,
auth: {
user: config.email.user,
pass: normalizeSmtpPass(config.email.pass),
},
});
const info = await transport.sendMail({
from,
replyTo,
to: testTo,
subject: 'Tloto SMTP test',
text: [
'This is a test message from Tloto.',
`Auth user: ${config.email.user}`,
`From header: ${from}`,
`Reply-To: ${replyTo || '(none)'}`,
`Time: ${new Date().toISOString()}`,
].join('\n'),
});
console.log('Test message accepted by SMTP. messageId:', info.messageId);
console.log('Check the inbox for', testTo, '— From should show info@tloto.net (or your EMAIL_FROM).');
} else {
console.log('Tip: set SMTP_TEST_TO=you@example.com to send a real test message.');
}
process.exit(0);
}
main().catch((e) => {
const msg = e instanceof Error ? e.message : String(e);
console.error('SMTP verification failed:', msg);
if (msg.includes('535') || msg.includes('BadCredentials')) {
if (msg.includes('535') || msg.includes('BadCredentials') || msg.includes('Authentication unsuccessful')) {
console.error(
'\nGmail: use an App Password (not your normal Gmail password).\n' +
' https://myaccount.google.com/apppasswords\n' +
' SMTP_USER must be the same @gmail.com account that owns the app password.\n' +
' Remove spaces from SMTP_PASS (16 characters, no spaces).'
'\nAuth rejected. Tloto uses Microsoft 365 / GoDaddy only (not Gmail):\n' +
' SMTP_HOST=smtp.office365.com SMTP_PORT=587 SMTP_SECURE=false\n' +
' SMTP_USER=admin@tloto.net (mailbox password)\n' +
' EMAIL_FROM="Tloto" <info@tloto.net> (alias / Send As)\n' +
' EMAIL_REPLY_TO=info@tloto.net'
);
}
if (msg.includes('SendAsDenied') || msg.includes('not allowed to send') || msg.includes('550 5.7')) {
console.error(
'\nServer rejected From address. Grant “Send As” / confirm info@tloto.net is an alias of admin@tloto.net.'
);
}
process.exit(1);

View File

@ -85,20 +85,24 @@ function formatEmailSendError(context: string, e: unknown): Error {
return new Error(`Failed to send ${context}: ${detail}`);
}
function resolveFromAddress(): string {
const from = config.email.from!;
/**
* Visible From header (EMAIL_FROM).
* Tloto production uses Microsoft 365: SMTP_USER=admin@…, EMAIL_FROM=info@… (alias).
*/
export function resolveFromAddress(): string {
const from = (config.email.from || '').trim();
const user = config.email.user;
if (!user) return from;
const fromEmail = from.match(/<([^>]+)>/)?.[1] ?? from.trim();
const host = config.email.host.toLowerCase();
const usesGmail = host.includes('gmail.com') || host.includes('googlemail.com');
if (usesGmail && user.endsWith('@gmail.com') && !fromEmail.endsWith('@gmail.com')) {
return `"${PLATFORM_NAME}" <${user}>`;
if (!from) return user ? `"${PLATFORM_NAME}" <${user}>` : `"${PLATFORM_NAME}"`;
return from;
}
return from;
/** Reply-To: EMAIL_REPLY_TO, else the address inside EMAIL_FROM. */
export function resolveReplyToAddress(): string | undefined {
const explicit = (config.email.replyTo || '').trim();
if (explicit) return explicit;
const from = resolveFromAddress();
const angled = from.match(/<([^>]+)>/)?.[1];
return angled?.trim() || undefined;
}
/** Shared branded HTML shell (no external image — works in all mail clients). */
@ -158,6 +162,7 @@ export async function sendVerificationEmail(to: string, verifyUrl: string): Prom
const transport = getSmtpTransporter();
await transport.sendMail({
from: resolveFromAddress(),
replyTo: resolveReplyToAddress(),
to,
subject,
text,
@ -207,6 +212,7 @@ export async function sendPasswordResetEmail(to: string, resetUrl: string): Prom
const transport = getSmtpTransporter();
await transport.sendMail({
from: resolveFromAddress(),
replyTo: resolveReplyToAddress(),
to,
subject,
text,
@ -274,6 +280,7 @@ export async function sendSecurityAlertEmail(
const transport = getSmtpTransporter();
await transport.sendMail({
from: resolveFromAddress(),
replyTo: resolveReplyToAddress(),
to,
subject,
text,
@ -335,6 +342,7 @@ async function sendUserSecurityEmail(
const transport = getSmtpTransporter();
await transport.sendMail({
from: resolveFromAddress(),
replyTo: resolveReplyToAddress(),
to,
subject,
text,

View File

@ -82,6 +82,7 @@ x-backend-common: &backend-common
SMTP_USER: ${SMTP_USER:-}
SMTP_PASS: ${SMTP_PASS:-}
EMAIL_FROM: ${EMAIL_FROM:-}
EMAIL_REPLY_TO: ${EMAIL_REPLY_TO:-}
VERIFY_EMAIL_PATH: ${VERIFY_EMAIL_PATH:-/verify-email}
RESET_PASSWORD_PATH: ${RESET_PASSWORD_PATH:-/reset-password}
PASSWORD_RESET_EXPIRY_HOURS: ${PASSWORD_RESET_EXPIRY_HOURS:-1}

View File

@ -266,40 +266,50 @@ TRON_API_KEY=…
Après toute modification de secrets dans `.env`, redémarrez la stack (`sudo npm run phase-b:up` ou équivalent). Rebuild `prediqo-web` uniquement si vous changez les `VITE_*`.
### Configuration SMTP (Gmail)
### Configuration SMTP (Microsoft 365 / GoDaddy — recommandé pour `tloto.net`)
L’erreur `535-5.7.8 Username and Password not accepted` signifie que **Gmail refuse le mot de passe SMTP**. Le mot de passe normal du compte Gmail **ne fonctionne pas** : il faut un **mot de passe d’application**.
Objectif : les destinataires voient **`info@tloto.net`** comme expéditeur, en s’authentifiant avec la boîte **`admin@tloto.net`** (l’alias ne nécessite pas d’abonnement supplémentaire).
1. Activer la **validation en 2 étapes** sur le compte Gmail expéditeur.
2. Créer un mot de passe d’application : [https://myaccount.google.com/apppasswords](https://myaccount.google.com/apppasswords) → application « Mail », appareil « Prediqo VPS ».
3. Copier les **16 caractères** (sans espaces) dans `.env` :
**Prérequis GoDaddy / Microsoft 365 (à vérifier avant de changer le VPS) :**
1. `info@tloto.net` est bien un **alias / adresse proxy** de la boîte `admin@tloto.net` (pas une boîte séparée non liée).
2. L’envoi « **Send As** » / envoi depuis l’alias est autorisé pour ce compte (souvent automatique pour les alias M365 ; sinon Admin center → Users → Mail → Email aliases / Send as).
3. SMTP client authentifié activé pour la boîte (standard M365 : `smtp.office365.com:587` STARTTLS).
Dans le **`.env` à la racine du VPS** (secrets hors Git) :
```env
EMAIL_TRANSPORT=smtp
SMTP_HOST=smtp.gmail.com
SMTP_HOST=smtp.office365.com
SMTP_PORT=587
SMTP_SECURE=false
SMTP_USER=votre-compte@gmail.com
SMTP_PASS=xxxxxxxxxxxxxxxx
EMAIL_FROM="Tloto" <votre-compte@gmail.com>
APP_PUBLIC_URL=https://prediqo.redirectme.net:9443
SMTP_USER=admin@tloto.net
SMTP_PASS=mot-de-passe-de-la-boite-admin
EMAIL_FROM="Tloto" <info@tloto.net>
EMAIL_REPLY_TO=info@tloto.net
APP_PUBLIC_URL=https://tloto.net
RESET_PASSWORD_PATH=/reset-password
VERIFY_EMAIL_PATH=/verify-email
```
`SMTP_USER` doit être **le même compte Gmail** que celui qui a généré le mot de passe d’application.
- `SMTP_USER` / `SMTP_PASS` = authentification (boîte principale).
- `EMAIL_FROM` = en-tête **From** visible (alias).
- `EMAIL_REPLY_TO` = réponses vers l’alias (sinon dérivé de `EMAIL_FROM`).
**Tester la connexion SMTP (après `git pull`) :**
**Tester (après `git pull` + recreate backend pour injecter les env) :**
```bash
sudo docker compose up -d --force-recreate backend
sudo npm run phase-b:verify-smtp
# Envoi réel de test (remplacer l’adresse) :
sudo docker compose run --rm --no-deps -e SMTP_TEST_TO=votre@email.com backend node dist/scripts/verifySmtp.js
```
Puis redémarrer le backend :
Contrôler dans la boîte de réception : From = `info@tloto.net`, Reply-To = `info@tloto.net`.
```bash
sudo npm run phase-b:up
```
Si erreur du type `SendAsDenied` / `550 5.7.60` : l’alias n’a pas le droit d’envoyer — corriger dans M365/GoDaddy avant de retenter.
> **Tloto n’utilise plus Gmail** comme expéditeur. Uniquement Microsoft 365 (`admin@` / alias `info@`).
> **Ne pas committer `.env`** — il est ignoré par Git.
### Base de données PostgreSQL (sur l’hôte) — **obligatoire avant le 1er démarrage**