npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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

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:

  1. Automated Backend Generator: Automatically generates secured PHP backend API endpoints into your public/api/ directory on install.
  2. Type-Safe React Hook: Provides useContactForm() with full TypeScript support, state management, validation handling, and error states.
  3. Enterprise-Grade Security: Comes with .htaccess protection preventing direct access to .env or internal configs.
  4. Zero-Captcha Anti-Spam (Honeypot): Built-in honeypot bot trap without annoying captchas for users.
  5. 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-mailer

On 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

  1. .htaccess Direct Access Denial: Blocks public requests to .env, config.php, and lib/.
  2. CORS & Preflight Handling: Ready for local development (localhost:3000 to PHP server) and cross-origin hosting.
  3. Zero-Captcha Honeypot: Any bots filling hidden fields like _gotcha or _honey are silently accepted without sending spam emails.
  4. Data Sanitization: All payload values are sanitized via htmlspecialchars to prevent HTML injection in email clients.

🚀 Deployment (Static Export)

  1. In your next.config.js (or next.config.mjs):

    /** @type {import('next').NextConfig} */
    const nextConfig = {
      output: 'export',
      // ...
    };
    
    module.exports = nextConfig;
  2. Build your static files:

    npm run build
  3. Upload the contents of the out/ folder directly to your hosting (public_html).

  4. Ensure public/api/.env contains your production SMTP details.


🇸🇦 دليل الاستخدام السريع (باللغة العربية)

تم تصميم هذا البكج خصيصاً لمطوري Next.js لتسهيل إرسال الرسائل والنماذج عند تصدير المشاريع بشكل ستاتيك (output: 'export') ورفعها على استضافات مشتركة (cPanel / Apache) تدعم PHP فقط.

المميزات:

  1. توليد تلقائي للـ Backend: يقوم تلقائياً بإنشاء ملفات الـ PHP في مجلد public/api/.
  2. React Hook متكامل: يوفر useContactForm مع دعم كامل للـ TypeScript والحالات (isSubmitting, isSuccess, errorMessage).
  3. حماية أمنية شاملة: يتضمن ملف .htaccess لحجب قراءة ملف .env وكلمات سر الـ SMTP من المتصفح.
  4. حماية ضد الـ Spam (Honeypot): حقل مخفي لاصطياد البوتات تلقائياً دون الحاجة لكابتشا مزعجة للمستخدمين.
  5. قالب إيميل احترافي ومتجاوب: تصميم عصري يدعم مختلف أنواع الحقول والـ Checkboxes وينشئ نسخة نصية متوافقة مع جميع تطبيقات البريد ومصفيات الـ Spam.

📄 License

MIT © next-php-mailer