@damshly/next-php-mailer
v1.0.0
Published
Zero-config PHP Mailer bridge and type-safe React Hook for Next.js Static Export deployments on shared hosting / cPanel
Maintainers
Readme
next-php-mailer ✉️🚀
Zero-config PHP Mailer bridge and type-safe React Hook for Next.js Static Export (
output: 'export') deployed on PHP / cPanel / Apache shared hosting.
🌟 Why next-php-mailer?
When building modern websites with Next.js and deploying them as static exports (output: 'export') to traditional Shared Hosting (cPanel / Apache / LiteSpeed / Nginx) without Node.js runtime, handling dynamic form submissions (e.g. Contact Us, Quote Requests, Newsletter) becomes challenging.
next-php-mailer provides a seamless bridge:
- Automated Backend Generator: Automatically generates secured PHP backend API endpoints into your
public/api/directory on install. - Type-Safe React Hook: Provides
useContactForm()with full TypeScript support, state management, validation handling, and error states. - Enterprise-Grade Security: Comes with
.htaccessprotection preventing direct access to.envor internal configs. - Zero-Captcha Anti-Spam (Honeypot): Built-in honeypot bot trap without annoying captchas for users.
- Modern Responsive Email Templates: Generates clean, responsive HTML emails along with plain-text fallback (
AltBody) for 100% spam-filter compatibility.
📦 Installation
# npm
npm install next-php-mailer
# pnpm
pnpm add next-php-mailer
# yarn
yarn add next-php-mailerOn installation, the package automatically copies backend templates into your project's public/api/ folder.
You can also run the initialization manually at any time:
npx next-php-mailer⚙️ Configuration (public/api/.env)
Edit the generated public/api/.env file with your SMTP credentials:
# SMTP Server Configuration
SMTP_HOST=smtp.gmail.com
SMTP_PORT=465
[email protected]
SMTP_PASS=your-app-password
# Email Settings
[email protected]
FROM_NAME="My Next.js Website"
[email protected]
# Optional Settings
DEFAULT_SUBJECT="New Contact Form Submission"
ALLOWED_ORIGIN=*Tip for Gmail: Use an App Password generated from your Google Account settings (Security -> 2-Step Verification -> App Passwords).
💻 Frontend Usage
Simple Contact Form
"use client";
import React from "react";
import { useContactForm } from "next-php-mailer";
export default function ContactPage() {
const { formData, handleChange, handleSubmit, isSubmitting, isSuccess, isError, errorMessage } =
useContactForm({
name: "",
email: "",
message: "",
_gotcha: "", // Honeypot spam trap
});
return (
<form onSubmit={handleSubmit} className="max-w-md mx-auto space-y-4">
{/* Honeypot field - hidden from real users */}
<input
type="text"
name="_gotcha"
value={formData._gotcha}
onChange={handleChange}
style={{ display: "none" }}
tabIndex={-1}
autoComplete="off"
/>
<div>
<label>Name</label>
<input
type="text"
name="name"
required
value={formData.name}
onChange={handleChange}
className="w-full border p-2 rounded"
/>
</div>
<div>
<label>Email</label>
<input
type="email"
name="email"
required
value={formData.email}
onChange={handleChange}
className="w-full border p-2 rounded"
/>
</div>
<div>
<label>Message</label>
<textarea
name="message"
rows={4}
required
value={formData.message}
onChange={handleChange}
className="w-full border p-2 rounded"
/>
</div>
<button
type="submit"
disabled={isSubmitting}
className="px-4 py-2 bg-blue-600 text-white rounded disabled:opacity-50"
>
{isSubmitting ? "Sending..." : "Send Message"}
</button>
{isSuccess && <p className="text-green-600">Your message has been sent successfully!</p>}
{isError && <p className="text-red-600">{errorMessage || "Failed to send message."}</p>}
</form>
);
}Advanced Usage (Callbacks & Custom Fields)
"use client";
import { useContactForm } from "next-php-mailer";
export function CustomQuoteForm() {
const { formData, handleChange, setFieldValue, handleSubmit, isSubmitting } = useContactForm(
{
fullName: "",
email: "",
service: "web-dev",
newsletter: false,
_subject: "Custom Quote Request from Website", // Custom email subject
},
{
apiEndpoint: "/api/send-email.php",
resetOnSuccess: true,
onSuccess: (response, values) => {
alert("Thanks! We received your request.");
},
onError: (error) => {
alert(`Error: ${error}`);
},
}
);
return (
<form onSubmit={handleSubmit}>
{/* Dynamic Subject */}
<input type="hidden" name="_subject" value={formData._subject} />
{/* Checkbox handling */}
<label>
<input
type="checkbox"
name="newsletter"
checked={formData.newsletter}
onChange={handleChange}
/>
Subscribe to updates
</label>
{/* Custom Component handler */}
{/* <CustomSelect onChange={(val) => setFieldValue('service', val)} /> */}
<button type="submit" disabled={isSubmitting}>
Submit
</button>
</form>
);
}🛡️ Built-in Security Features
.htaccessDirect Access Denial: Blocks public requests to.env,config.php, andlib/.- CORS & Preflight Handling: Ready for local development (
localhost:3000to PHP server) and cross-origin hosting. - Zero-Captcha Honeypot: Any bots filling hidden fields like
_gotchaor_honeyare silently accepted without sending spam emails. - Data Sanitization: All payload values are sanitized via
htmlspecialcharsto prevent HTML injection in email clients.
🚀 Deployment (Static Export)
In your
next.config.js(ornext.config.mjs):/** @type {import('next').NextConfig} */ const nextConfig = { output: 'export', // ... }; module.exports = nextConfig;Build your static files:
npm run buildUpload the contents of the
out/folder directly to your hosting (public_html).Ensure
public/api/.envcontains your production SMTP details.
🇸🇦 دليل الاستخدام السريع (باللغة العربية)
تم تصميم هذا البكج خصيصاً لمطوري Next.js لتسهيل إرسال الرسائل والنماذج عند تصدير المشاريع بشكل ستاتيك (output: 'export') ورفعها على استضافات مشتركة (cPanel / Apache) تدعم PHP فقط.
المميزات:
- توليد تلقائي للـ Backend: يقوم تلقائياً بإنشاء ملفات الـ PHP في مجلد
public/api/. - React Hook متكامل: يوفر
useContactFormمع دعم كامل للـ TypeScript والحالات (isSubmitting,isSuccess,errorMessage). - حماية أمنية شاملة: يتضمن ملف
.htaccessلحجب قراءة ملف.envوكلمات سر الـ SMTP من المتصفح. - حماية ضد الـ Spam (Honeypot): حقل مخفي لاصطياد البوتات تلقائياً دون الحاجة لكابتشا مزعجة للمستخدمين.
- قالب إيميل احترافي ومتجاوب: تصميم عصري يدعم مختلف أنواع الحقول والـ Checkboxes وينشئ نسخة نصية متوافقة مع جميع تطبيقات البريد ومصفيات الـ Spam.
📄 License
MIT © next-php-mailer
