Add of mailing script for contact form

This commit is contained in:
N0Xx committed 2026-10-09 23:34:51 +02:00
1 parent a1c679b60a
commit 904f75c8de
7 files changed
+7637 -11

No files matched your search

+135
View File
@@ -0,0 +1,135 @@
<?php
/**
* Portfolio contact form -> Proton Mail (SMTP submission)
*
* Receives the form as JSON from js/main.js and sends it to your inbox
* through smtp.protonmail.ch:587 (STARTTLS).
* No secret lives in this file: the SMTP token is read from
* ../portfolio-private/smtp-config.php, outside the web root.
*/
declare(strict_types=1);
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as MailException;
header('Content-Type: application/json; charset=utf-8');
header('X-Content-Type-Options: nosniff');
header('Cache-Control: no-store');
function reply(int $code, bool $ok, string $msg): never
{
http_response_code($code);
echo json_encode(['success' => $ok, 'message' => $msg]);
exit;
}
// ---------- Private folder (outside the web root) ----------
$private = getenv('PORTFOLIO_PRIVATE_DIR') ?: dirname(__DIR__) . '/portfolio-private';
$configFile = $private . '/smtp-config.php';
if (!is_readable($configFile)) {
error_log("contact.php: config not readable at $configFile");
reply(500, false, 'The contact form is not configured yet.');
}
$cfg = require $configFile;
require $private . '/PHPMailer/Exception.php';
require $private . '/PHPMailer/PHPMailer.php';
require $private . '/PHPMailer/SMTP.php';
// ---------- Request checks ----------
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
reply(405, false, 'Method not allowed.');
}
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if ($origin !== '' && !in_array($origin, $cfg['allowed_origins'] ?? [], true)) {
reply(403, false, 'Forbidden.');
}
$raw = (string) file_get_contents('php://input', false, null, 0, 20000);
$in = json_decode($raw, true);
if (!is_array($in)) {
reply(400, false, 'Invalid request.');
}
// Honeypot: bots tick the hidden box. Pretend it worked, send nothing.
if (!empty($in['botcheck'])) {
reply(200, true, 'Message sent.');
}
// ---------- Validation ----------
function field(array $in, string $key, int $max): string
{
return mb_substr(trim((string) ($in[$key] ?? '')), 0, $max);
}
$name = field($in, 'name', 100);
$email = field($in, 'email', 150);
$company = field($in, 'company', 100);
$subject = field($in, 'subject', 150);
$message = field($in, 'message', 4000);
// Header-bound fields must not contain line breaks (header injection).
foreach ([$name, $email, $company, $subject] as $v) {
if (preg_match('/[\r\n]/', $v)) {
reply(400, false, 'Invalid characters in the form.');
}
}
if ($name === '' || $subject === '' || $message === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
reply(422, false, 'Fill in your name, a valid email, a subject and a message.');
}
// ---------- Rate limit per IP ----------
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
$store = sys_get_temp_dir() . '/portfolio-contact-' . hash('sha256', $ip . ($cfg['rate_salt'] ?? ''));
$now = time();
$hits = [];
if (is_readable($store)) {
foreach (explode(',', (string) file_get_contents($store)) as $t) {
if ((int) $t > $now - 3600) {
$hits[] = (int) $t;
}
}
}
if (count($hits) >= (int) ($cfg['max_per_hour'] ?? 5)) {
reply(429, false, 'Too many messages from your connection. Try again in an hour.');
}
// ---------- Send through Proton ----------
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = $cfg['smtp_host'] ?? 'smtp.protonmail.ch';
$mail->Port = (int) ($cfg['smtp_port'] ?? 587);
$mail->SMTPSecure = $cfg['smtp_secure'] ?? PHPMailer::ENCRYPTION_STARTTLS;
$mail->SMTPAutoTLS = $mail->SMTPSecure !== '';
$mail->SMTPAuth = $cfg['smtp_auth'] ?? true;
$mail->Username = $cfg['smtp_user'];
$mail->Password = $cfg['smtp_token'];
$mail->CharSet = PHPMailer::CHARSET_UTF8;
$mail->Timeout = 15;
// Proton only accepts the address tied to the token as sender.
$mail->setFrom($cfg['smtp_user'], 'Portfolio: ' . $name);
$mail->addAddress($cfg['to']);
$mail->addReplyTo($email, $name); // "Reply" answers the visitor directly
$mail->Subject = '[Portfolio] ' . $subject;
$mail->isHTML(false);
$mail->Body =
"New message from your portfolio\n"
. "-------------------------------\n"
. "Name: $name\n"
. "Email: $email\n"
. ($company !== '' ? "Company: $company\n" : '')
. 'Date: ' . date('Y-m-d H:i:s T') . "\n\n"
. $message . "\n";
$mail->send();
$hits[] = $now;
file_put_contents($store, implode(',', $hits), LOCK_EX);
reply(200, true, "Message sent. Thanks, I'll get back to you soon.");
} catch (MailException $e) {
error_log('contact.php SMTP error: ' . $mail->ErrorInfo);
reply(502, false, 'The message could not be sent.');
}
+14 -11
View File
@@ -1,9 +1,9 @@
/* ===== Contact form settings =====
1. Create a free key at https://web3forms.com with nelson.thomas.contact@pm.me
2. Paste it below. Messages then arrive straight in your Proton inbox.
Without a key (or if the service is unreachable), the form opens the
visitor's mail app with the message already written. */
var WEB3FORMS_KEY = "YOUR_ACCESS_KEY";
The form posts to contact.php on your own server, which sends the message
to your Proton inbox over SMTP (see LISEZMOI.txt).
If the server can't be reached (e.g. site opened as a local file), the form
opens the visitor's mail app with the message already written. */
var CONTACT_ENDPOINT = "contact.php";
var CONTACT_EMAIL = "nelson.thomas.contact@pm.me";
(function(){
@@ -57,14 +57,17 @@ var CONTACT_EMAIL = "nelson.thomas.contact@pm.me";
if(!form.checkValidity()){form.reportValidity();say('Fill in your name, a valid email, a subject and a message.','err');return}
if(form.botcheck.checked)return;
var d={name:form.name.value.trim(),email:form.email.value.trim(),company:form.company.value.trim(),subject:form.subject.value.trim(),message:form.message.value.trim()};
if(!WEB3FORMS_KEY||WEB3FORMS_KEY==='YOUR_ACCESS_KEY'){mailtoFallback(d);return}
btn.disabled=true;btn.textContent='Sending...';say('');
fetch('https://api.web3forms.com/submit',{method:'POST',headers:{'Content-Type':'application/json',Accept:'application/json'},
body:JSON.stringify({access_key:WEB3FORMS_KEY,from_name:'Portfolio: '+d.name,replyto:d.email,subject:'[Portfolio] '+d.subject,name:d.name,email:d.email,company:d.company,message:d.message})})
.then(function(r){return r.json()})
fetch(CONTACT_ENDPOINT,{method:'POST',headers:{'Content-Type':'application/json',Accept:'application/json'},
body:JSON.stringify({name:d.name,email:d.email,company:d.company,subject:d.subject,message:d.message,botcheck:false})})
.then(function(r){
if(r.success){form.reset();say('Message sent. Thanks, I\'ll get back to you soon.','ok')}
else throw new Error(r.message);
return r.json().catch(function(){throw new Error('network')}).then(function(j){return {status:r.status,body:j}});
})
.then(function(r){
if(r.body.success){form.reset();say(r.body.message,'ok');return}
// Visitor-side problems (bad field, too many messages): show the server's message
if(r.status===422||r.status===429||r.status===400){say(r.body.message,'err');return}
throw new Error('server');
})
.catch(function(){mailtoFallback(d)})
.finally(function(){btn.disabled=false;btn.textContent='Send message'});