Initial commit: Mail service with Brevo SMTP
- Express server with REST API for sending emails - SQLite database for persistent email history - Web interface with form (recipient, CC, subject, text/HTML) - Email footer with embedded image (CID attachment) - Nodemailer configured for Brevo SMTP relay Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
14
.env.example
Normal file
14
.env.example
Normal file
@@ -0,0 +1,14 @@
|
||||
# Server
|
||||
PORT=3000
|
||||
|
||||
# Email Configuration
|
||||
MAIL_PROVIDER=smtp
|
||||
MAIL_FROM_EMAIL=noreply@example.com
|
||||
MAIL_FROM_NAME=Secure Portal
|
||||
|
||||
# SMTP (Brevo)
|
||||
SMTP_HOST=smtp-relay.brevo.com
|
||||
SMTP_PORT=587
|
||||
SMTP_USER=your-email@example.com
|
||||
SMTP_PASSWORD=your-smtp-password
|
||||
SMTP_SECURE=false
|
||||
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
node_modules/
|
||||
.env
|
||||
data/*.db
|
||||
BIN
assets/homeicon.png
Normal file
BIN
assets/homeicon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 670 B |
104
docs/plans/2026-01-16-mail-service-design.md
Normal file
104
docs/plans/2026-01-16-mail-service-design.md
Normal file
@@ -0,0 +1,104 @@
|
||||
# Mail-Service Design
|
||||
|
||||
**Datum:** 2026-01-16
|
||||
**Status:** Genehmigt
|
||||
|
||||
## Übersicht
|
||||
|
||||
Weboberfläche zum Testen des Mail-Versands über Brevo (SMTP). Node.js-basiert mit persistenter Historie.
|
||||
|
||||
## Technologie-Stack
|
||||
|
||||
- **Backend:** Node.js, Express
|
||||
- **Mail:** Nodemailer
|
||||
- **Datenbank:** SQLite (better-sqlite3)
|
||||
- **Frontend:** HTML, CSS, Vanilla JS
|
||||
|
||||
## Projektstruktur
|
||||
|
||||
```
|
||||
mail-service/
|
||||
├── .env # Konfiguration (SMTP, Port)
|
||||
├── .env.example # Vorlage ohne sensible Daten
|
||||
├── package.json
|
||||
├── src/
|
||||
│ ├── server.js # Express-Server, Routen
|
||||
│ ├── mailer.js # Nodemailer-Konfiguration
|
||||
│ └── database.js # SQLite-Setup und Queries
|
||||
├── public/
|
||||
│ ├── index.html # Hauptseite mit Formular
|
||||
│ ├── style.css # Styling
|
||||
│ └── script.js # Frontend-Logik
|
||||
└── data/
|
||||
└── emails.db # SQLite-Datenbank
|
||||
```
|
||||
|
||||
## Datenbank-Schema
|
||||
|
||||
**Tabelle `emails`:**
|
||||
|
||||
| Spalte | Typ | Beschreibung |
|
||||
|--------|-----|--------------|
|
||||
| id | INTEGER | Primary Key, Auto-Increment |
|
||||
| to_email | TEXT | Empfänger-Adresse |
|
||||
| cc_email | TEXT | CC-Adresse (optional) |
|
||||
| subject | TEXT | Betreff |
|
||||
| body | TEXT | Nachrichteninhalt |
|
||||
| is_html | INTEGER | 0 = Text, 1 = HTML |
|
||||
| status | TEXT | "success" oder "failed" |
|
||||
| error_message | TEXT | Fehlermeldung falls fehlgeschlagen |
|
||||
| created_at | TEXT | ISO-Timestamp |
|
||||
|
||||
## API-Endpunkte
|
||||
|
||||
| Methode | Route | Beschreibung |
|
||||
|---------|-------|--------------|
|
||||
| GET | `/` | Weboberfläche (index.html) |
|
||||
| POST | `/api/send` | Mail versenden |
|
||||
| GET | `/api/history` | Historie abrufen (letzte 50) |
|
||||
| DELETE | `/api/history/:id` | Einzelnen Eintrag löschen |
|
||||
| DELETE | `/api/history` | Gesamte Historie löschen |
|
||||
|
||||
## Weboberfläche
|
||||
|
||||
Zweispaltiges Layout:
|
||||
- **Links:** Mail-Formular (Empfänger, CC, Betreff, Text/HTML-Toggle, Nachricht)
|
||||
- **Rechts:** Versand-Historie mit Status-Icons und Lösch-Buttons
|
||||
|
||||
## Fehlerbehandlung
|
||||
|
||||
| Fehlertyp | Behandlung |
|
||||
|-----------|------------|
|
||||
| Ungültige E-Mail-Adresse | Validierung Frontend + Backend |
|
||||
| SMTP-Verbindungsfehler | In DB als "failed" speichern |
|
||||
| Authentifizierungsfehler | Hinweis auf .env-Konfiguration |
|
||||
| Timeout | Nach 30 Sekunden Abbruch |
|
||||
| Leere Pflichtfelder | Frontend verhindert Absenden |
|
||||
|
||||
## Konfiguration (.env)
|
||||
|
||||
```env
|
||||
# Server
|
||||
PORT=3000
|
||||
|
||||
# Email Configuration
|
||||
MAIL_PROVIDER=smtp
|
||||
MAIL_FROM_EMAIL=noreply@businesshelpdesk.biz
|
||||
MAIL_FROM_NAME=Secure Portal
|
||||
|
||||
# SMTP (Brevo)
|
||||
SMTP_HOST=smtp-relay.brevo.com
|
||||
SMTP_PORT=587
|
||||
SMTP_USER=<user>
|
||||
SMTP_PASSWORD=<password>
|
||||
SMTP_SECURE=false
|
||||
```
|
||||
|
||||
## Ausführung
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm start
|
||||
```
|
||||
|
||||
Server läuft auf http://localhost:3000
|
||||
1274
package-lock.json
generated
Normal file
1274
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
19
package.json
Normal file
19
package.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "mail-service",
|
||||
"version": "1.0.0",
|
||||
"description": "Web interface for testing email sending via Brevo SMTP",
|
||||
"main": "src/server.js",
|
||||
"scripts": {
|
||||
"start": "node src/server.js",
|
||||
"dev": "node --watch src/server.js"
|
||||
},
|
||||
"keywords": ["mail", "smtp", "brevo", "nodemailer"],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"better-sqlite3": "^11.0.0",
|
||||
"dotenv": "^16.4.0",
|
||||
"express": "^4.18.0",
|
||||
"nodemailer": "^6.9.0"
|
||||
}
|
||||
}
|
||||
65
public/index.html
Normal file
65
public/index.html
Normal file
@@ -0,0 +1,65 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Mail-Service</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="panel form-panel">
|
||||
<h2>Mail Versenden</h2>
|
||||
<form id="mailForm">
|
||||
<div class="form-group">
|
||||
<label for="to">Empfänger *</label>
|
||||
<input type="email" id="to" name="to" required placeholder="empfaenger@example.com">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="cc">CC</label>
|
||||
<input type="email" id="cc" name="cc" placeholder="cc@example.com">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="subject">Betreff *</label>
|
||||
<input type="text" id="subject" name="subject" required placeholder="Betreff der E-Mail">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label>Format</label>
|
||||
<div class="radio-group">
|
||||
<label>
|
||||
<input type="radio" name="format" value="text" checked> Text
|
||||
</label>
|
||||
<label>
|
||||
<input type="radio" name="format" value="html"> HTML
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="body">Nachricht *</label>
|
||||
<textarea id="body" name="body" required rows="8" placeholder="Ihre Nachricht..."></textarea>
|
||||
</div>
|
||||
|
||||
<button type="submit" id="submitBtn">Senden</button>
|
||||
</form>
|
||||
|
||||
<div id="status" class="status hidden"></div>
|
||||
</div>
|
||||
|
||||
<div class="panel history-panel">
|
||||
<div class="history-header">
|
||||
<h2>Versand-Historie</h2>
|
||||
<button id="clearHistory" class="btn-secondary">Leeren</button>
|
||||
</div>
|
||||
<div id="historyList" class="history-list">
|
||||
<p class="empty-message">Keine E-Mails gesendet</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="script.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
149
public/script.js
Normal file
149
public/script.js
Normal file
@@ -0,0 +1,149 @@
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const form = document.getElementById('mailForm');
|
||||
const status = document.getElementById('status');
|
||||
const submitBtn = document.getElementById('submitBtn');
|
||||
const historyList = document.getElementById('historyList');
|
||||
const clearHistoryBtn = document.getElementById('clearHistory');
|
||||
|
||||
// Load history on page load
|
||||
loadHistory();
|
||||
|
||||
// Form submission
|
||||
form.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
const formData = new FormData(form);
|
||||
const data = {
|
||||
to: formData.get('to'),
|
||||
cc: formData.get('cc') || undefined,
|
||||
subject: formData.get('subject'),
|
||||
body: formData.get('body'),
|
||||
isHtml: formData.get('format') === 'html'
|
||||
};
|
||||
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.textContent = 'Sende...';
|
||||
hideStatus();
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/send', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
showStatus('E-Mail erfolgreich gesendet!', 'success');
|
||||
form.reset();
|
||||
} else {
|
||||
showStatus(result.error, 'error');
|
||||
}
|
||||
|
||||
loadHistory();
|
||||
} catch (error) {
|
||||
showStatus('Netzwerkfehler: ' + error.message, 'error');
|
||||
} finally {
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = 'Senden';
|
||||
}
|
||||
});
|
||||
|
||||
// Clear history
|
||||
clearHistoryBtn.addEventListener('click', async () => {
|
||||
if (!confirm('Gesamte Historie löschen?')) return;
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/history', { method: 'DELETE' });
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
loadHistory();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error clearing history:', error);
|
||||
}
|
||||
});
|
||||
|
||||
// Load history from server
|
||||
async function loadHistory() {
|
||||
try {
|
||||
const response = await fetch('/api/history');
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
renderHistory(result.history);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading history:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Render history list
|
||||
function renderHistory(history) {
|
||||
if (!history || history.length === 0) {
|
||||
historyList.innerHTML = '<p class="empty-message">Keine E-Mails gesendet</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
historyList.innerHTML = history.map(item => `
|
||||
<div class="history-item ${item.status}">
|
||||
<div class="history-item-header">
|
||||
<span class="history-item-status">
|
||||
${item.status === 'success' ? '✓ Erfolgreich' : '✗ Fehlgeschlagen'}
|
||||
</span>
|
||||
<button class="delete-btn" onclick="deleteHistoryItem(${item.id})" title="Löschen">✕</button>
|
||||
</div>
|
||||
<div class="history-item-date">${formatDate(item.created_at)}</div>
|
||||
<div class="history-item-to">An: ${escapeHtml(item.to_email)}${item.cc_email ? `, CC: ${escapeHtml(item.cc_email)}` : ''}</div>
|
||||
<div class="history-item-subject">Betreff: ${escapeHtml(item.subject)}</div>
|
||||
${item.error_message ? `<div class="history-item-error">Fehler: ${escapeHtml(item.error_message)}</div>` : ''}
|
||||
</div>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
// Delete single history item
|
||||
window.deleteHistoryItem = async (id) => {
|
||||
try {
|
||||
const response = await fetch(`/api/history/${id}`, { method: 'DELETE' });
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
loadHistory();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error deleting item:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Show status message
|
||||
function showStatus(message, type) {
|
||||
status.textContent = message;
|
||||
status.className = `status ${type}`;
|
||||
}
|
||||
|
||||
// Hide status message
|
||||
function hideStatus() {
|
||||
status.className = 'status hidden';
|
||||
}
|
||||
|
||||
// Format date
|
||||
function formatDate(dateStr) {
|
||||
const date = new Date(dateStr + 'Z');
|
||||
return date.toLocaleString('de-DE', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
}
|
||||
|
||||
// Escape HTML to prevent XSS
|
||||
function escapeHtml(text) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
});
|
||||
257
public/style.css
Normal file
257
public/style.css
Normal file
@@ -0,0 +1,257 @@
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
|
||||
background: #f5f5f5;
|
||||
color: #333;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.container {
|
||||
display: flex;
|
||||
gap: 20px;
|
||||
padding: 20px;
|
||||
max-width: 1400px;
|
||||
margin: 0 auto;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.panel {
|
||||
background: white;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.form-panel {
|
||||
flex: 1;
|
||||
max-width: 600px;
|
||||
}
|
||||
|
||||
.history-panel {
|
||||
flex: 1;
|
||||
max-width: 500px;
|
||||
}
|
||||
|
||||
h2 {
|
||||
margin-bottom: 20px;
|
||||
color: #2c3e50;
|
||||
font-size: 1.5rem;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
label {
|
||||
display: block;
|
||||
margin-bottom: 6px;
|
||||
font-weight: 500;
|
||||
color: #555;
|
||||
}
|
||||
|
||||
input[type="text"],
|
||||
input[type="email"],
|
||||
textarea {
|
||||
width: 100%;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
transition: border-color 0.2s;
|
||||
}
|
||||
|
||||
input:focus,
|
||||
textarea:focus {
|
||||
outline: none;
|
||||
border-color: #3498db;
|
||||
}
|
||||
|
||||
textarea {
|
||||
resize: vertical;
|
||||
min-height: 150px;
|
||||
}
|
||||
|
||||
.radio-group {
|
||||
display: flex;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.radio-group label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-weight: normal;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
button {
|
||||
background: #3498db;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 12px 24px;
|
||||
border-radius: 4px;
|
||||
font-size: 16px;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
button:hover {
|
||||
background: #2980b9;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
background: #bdc3c7;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: #95a5a6;
|
||||
padding: 8px 16px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background: #7f8c8d;
|
||||
}
|
||||
|
||||
.status {
|
||||
margin-top: 16px;
|
||||
padding: 12px;
|
||||
border-radius: 4px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.status.success {
|
||||
background: #d4edda;
|
||||
color: #155724;
|
||||
border: 1px solid #c3e6cb;
|
||||
}
|
||||
|
||||
.status.error {
|
||||
background: #f8d7da;
|
||||
color: #721c24;
|
||||
border: 1px solid #f5c6cb;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.history-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.history-header h2 {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.history-list {
|
||||
max-height: calc(100vh - 180px);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.history-item {
|
||||
padding: 12px;
|
||||
border: 1px solid #eee;
|
||||
border-radius: 4px;
|
||||
margin-bottom: 10px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.history-item.success {
|
||||
border-left: 4px solid #27ae60;
|
||||
}
|
||||
|
||||
.history-item.failed {
|
||||
border-left: 4px solid #e74c3c;
|
||||
}
|
||||
|
||||
.history-item-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.history-item-status {
|
||||
font-weight: 600;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.history-item.success .history-item-status {
|
||||
color: #27ae60;
|
||||
}
|
||||
|
||||
.history-item.failed .history-item-status {
|
||||
color: #e74c3c;
|
||||
}
|
||||
|
||||
.history-item-date {
|
||||
font-size: 12px;
|
||||
color: #888;
|
||||
}
|
||||
|
||||
.history-item-to {
|
||||
font-size: 14px;
|
||||
color: #333;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.history-item-subject {
|
||||
font-size: 13px;
|
||||
color: #666;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.history-item-error {
|
||||
font-size: 12px;
|
||||
color: #e74c3c;
|
||||
margin-top: 6px;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.delete-btn {
|
||||
background: none;
|
||||
border: none;
|
||||
color: #bbb;
|
||||
cursor: pointer;
|
||||
padding: 4px 8px;
|
||||
font-size: 16px;
|
||||
transition: color 0.2s;
|
||||
}
|
||||
|
||||
.delete-btn:hover {
|
||||
color: #e74c3c;
|
||||
background: none;
|
||||
}
|
||||
|
||||
.empty-message {
|
||||
text-align: center;
|
||||
color: #999;
|
||||
padding: 40px 20px;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.container {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.form-panel,
|
||||
.history-panel {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.history-list {
|
||||
max-height: 400px;
|
||||
}
|
||||
}
|
||||
66
src/database.js
Normal file
66
src/database.js
Normal file
@@ -0,0 +1,66 @@
|
||||
const Database = require('better-sqlite3');
|
||||
const path = require('path');
|
||||
|
||||
const dbPath = path.join(__dirname, '..', 'data', 'emails.db');
|
||||
const db = new Database(dbPath);
|
||||
|
||||
// Initialize database schema
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS emails (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
to_email TEXT NOT NULL,
|
||||
cc_email TEXT,
|
||||
subject TEXT NOT NULL,
|
||||
body TEXT NOT NULL,
|
||||
is_html INTEGER DEFAULT 0,
|
||||
status TEXT NOT NULL,
|
||||
error_message TEXT,
|
||||
created_at TEXT DEFAULT (datetime('now'))
|
||||
)
|
||||
`);
|
||||
|
||||
const insertEmail = db.prepare(`
|
||||
INSERT INTO emails (to_email, cc_email, subject, body, is_html, status, error_message)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
const getHistory = db.prepare(`
|
||||
SELECT * FROM emails ORDER BY created_at DESC LIMIT 50
|
||||
`);
|
||||
|
||||
const deleteEmail = db.prepare(`
|
||||
DELETE FROM emails WHERE id = ?
|
||||
`);
|
||||
|
||||
const deleteAllEmails = db.prepare(`
|
||||
DELETE FROM emails
|
||||
`);
|
||||
|
||||
module.exports = {
|
||||
saveEmail(email, status, errorMessage = null) {
|
||||
const result = insertEmail.run(
|
||||
email.to,
|
||||
email.cc || null,
|
||||
email.subject,
|
||||
email.body,
|
||||
email.isHtml ? 1 : 0,
|
||||
status,
|
||||
errorMessage
|
||||
);
|
||||
return result.lastInsertRowid;
|
||||
},
|
||||
|
||||
getHistory() {
|
||||
return getHistory.all();
|
||||
},
|
||||
|
||||
deleteEmail(id) {
|
||||
const result = deleteEmail.run(id);
|
||||
return result.changes > 0;
|
||||
},
|
||||
|
||||
clearHistory() {
|
||||
const result = deleteAllEmails.run();
|
||||
return result.changes;
|
||||
}
|
||||
};
|
||||
84
src/mailer.js
Normal file
84
src/mailer.js
Normal file
@@ -0,0 +1,84 @@
|
||||
const nodemailer = require('nodemailer');
|
||||
const path = require('path');
|
||||
|
||||
const transporter = nodemailer.createTransport({
|
||||
host: process.env.SMTP_HOST,
|
||||
port: parseInt(process.env.SMTP_PORT, 10),
|
||||
secure: process.env.SMTP_SECURE === 'true',
|
||||
auth: {
|
||||
user: process.env.SMTP_USER,
|
||||
pass: process.env.SMTP_PASSWORD
|
||||
},
|
||||
connectionTimeout: 30000,
|
||||
greetingTimeout: 30000,
|
||||
socketTimeout: 30000
|
||||
});
|
||||
|
||||
const FOOTER_NAME = process.env.MAIL_FOOTER_NAME || 'Joachim Hummel';
|
||||
const FOOTER_IMAGE = path.join(__dirname, '..', 'assets', 'homeicon.png');
|
||||
|
||||
function getHtmlFooter() {
|
||||
return `
|
||||
<br/><br/>
|
||||
<hr style="border: none; border-top: 1px solid #ddd; margin: 20px 0;"/>
|
||||
<table cellpadding="0" cellspacing="0" style="font-family: Arial, sans-serif; font-size: 14px; color: #666;">
|
||||
<tr>
|
||||
<td style="vertical-align: middle; padding-right: 10px;">
|
||||
<img src="cid:homeicon" alt="Home" width="40" height="40" style="display: block;"/>
|
||||
</td>
|
||||
<td style="vertical-align: middle;">
|
||||
<strong>Absender</strong><br/>
|
||||
${FOOTER_NAME}
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
`;
|
||||
}
|
||||
|
||||
function getTextFooter() {
|
||||
return `\n\n---\nAbsender - ${FOOTER_NAME}`;
|
||||
}
|
||||
|
||||
async function sendMail(email) {
|
||||
const mailOptions = {
|
||||
from: `"${process.env.MAIL_FROM_NAME}" <${process.env.MAIL_FROM_EMAIL}>`,
|
||||
to: email.to,
|
||||
subject: email.subject,
|
||||
attachments: [
|
||||
{
|
||||
filename: 'homeicon.png',
|
||||
path: FOOTER_IMAGE,
|
||||
cid: 'homeicon'
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
if (email.cc) {
|
||||
mailOptions.cc = email.cc;
|
||||
}
|
||||
|
||||
if (email.isHtml) {
|
||||
mailOptions.html = email.body + getHtmlFooter();
|
||||
} else {
|
||||
mailOptions.text = email.body + getTextFooter();
|
||||
// Also send HTML version with footer for better display
|
||||
mailOptions.html = `<pre style="font-family: inherit; white-space: pre-wrap;">${email.body}</pre>` + getHtmlFooter();
|
||||
}
|
||||
|
||||
const info = await transporter.sendMail(mailOptions);
|
||||
return info;
|
||||
}
|
||||
|
||||
async function verifyConnection() {
|
||||
try {
|
||||
await transporter.verify();
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
sendMail,
|
||||
verifyConnection
|
||||
};
|
||||
126
src/server.js
Normal file
126
src/server.js
Normal file
@@ -0,0 +1,126 @@
|
||||
require('dotenv').config();
|
||||
|
||||
const express = require('express');
|
||||
const path = require('path');
|
||||
const db = require('./database');
|
||||
const mailer = require('./mailer');
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3000;
|
||||
|
||||
// Middleware
|
||||
app.use(express.json());
|
||||
app.use(express.static(path.join(__dirname, '..', 'public')));
|
||||
|
||||
// Email validation helper
|
||||
function isValidEmail(email) {
|
||||
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
return re.test(email);
|
||||
}
|
||||
|
||||
// API Routes
|
||||
|
||||
// Send email
|
||||
app.post('/api/send', async (req, res) => {
|
||||
const { to, cc, subject, body, isHtml } = req.body;
|
||||
|
||||
// Validation
|
||||
if (!to || !subject || !body) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Empfänger, Betreff und Nachricht sind Pflichtfelder'
|
||||
});
|
||||
}
|
||||
|
||||
if (!isValidEmail(to)) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Ungültige Empfänger-E-Mail-Adresse'
|
||||
});
|
||||
}
|
||||
|
||||
if (cc && !isValidEmail(cc)) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Ungültige CC-E-Mail-Adresse'
|
||||
});
|
||||
}
|
||||
|
||||
const email = { to, cc, subject, body, isHtml: !!isHtml };
|
||||
|
||||
try {
|
||||
const info = await mailer.sendMail(email);
|
||||
const id = db.saveEmail(email, 'success');
|
||||
console.log(`Email sent successfully: ${info.messageId}`);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'E-Mail erfolgreich gesendet',
|
||||
messageId: info.messageId,
|
||||
id
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Email sending failed:', error.message);
|
||||
const id = db.saveEmail(email, 'failed', error.message);
|
||||
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: `Versand fehlgeschlagen: ${error.message}`,
|
||||
id
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Get history
|
||||
app.get('/api/history', (req, res) => {
|
||||
try {
|
||||
const history = db.getHistory();
|
||||
res.json({ success: true, history });
|
||||
} catch (error) {
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Delete single entry
|
||||
app.delete('/api/history/:id', (req, res) => {
|
||||
const id = parseInt(req.params.id, 10);
|
||||
|
||||
if (isNaN(id)) {
|
||||
return res.status(400).json({ success: false, error: 'Ungültige ID' });
|
||||
}
|
||||
|
||||
try {
|
||||
const deleted = db.deleteEmail(id);
|
||||
if (deleted) {
|
||||
res.json({ success: true, message: 'Eintrag gelöscht' });
|
||||
} else {
|
||||
res.status(404).json({ success: false, error: 'Eintrag nicht gefunden' });
|
||||
}
|
||||
} catch (error) {
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Clear all history
|
||||
app.delete('/api/history', (req, res) => {
|
||||
try {
|
||||
const count = db.clearHistory();
|
||||
res.json({ success: true, message: `${count} Einträge gelöscht` });
|
||||
} catch (error) {
|
||||
res.status(500).json({ success: false, error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Start server
|
||||
app.listen(PORT, () => {
|
||||
console.log(`Mail-Service läuft auf http://localhost:${PORT}`);
|
||||
|
||||
// Verify SMTP connection on startup
|
||||
mailer.verifyConnection().then(result => {
|
||||
if (result.success) {
|
||||
console.log('SMTP-Verbindung erfolgreich verifiziert');
|
||||
} else {
|
||||
console.warn('SMTP-Verbindung konnte nicht verifiziert werden:', result.error);
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user