free web page counters

How to send emails from your web server with  PHPMailer

Sedang Trending 2 hari yang lalu

Sep 23, 2025

Matleena S.

6min Read

How to nonstop emails from your web server with  PHPMailer

Email is basal for websites. It handles everything from password resets to customer inquiries. The PHP mail() usability tin nonstop elemental messages, but it often fails to present to inboxes and lacks features businesses trust on.

PHPMailer fixes these problems by providing authenticated SMTP, unafraid encryption, HTML formatting, and support for attachments. This ensures your messages look master and really scope recipients.

To get nan astir retired of PHPMailer, you should cognize really to:

  • Install nan room pinch Composer aliases manually
  • Configure SMTP settings for reliable delivery
  • Use halfway PHPMailer components for illustration setFrom(), addAddress(), and Body
  • Create a moving interaction shape pinch validation
  • Connect PHPMailer to Gmail and different providers
  • Troubleshoot communal errors for illustration SMTP relationship failures and DNS authentication issues

What is PHPMailer?

PHPMailer is simply a PHP room that provides a elemental measurement to nonstop emails straight from a server. Unlike nan basal PHP mail() function, it supports precocious features like:

  • SMTP authentication and encryption (SSL/TLS)
  • HTML messages and plain matter alternatives
  • File attachments and inline images
  • Custom headers and reply-to addresses

These capabilities make PHPMailer nan preferred prime for developers who request unafraid and master email handling successful their applications.

Is PHPMailer amended than nan mail() function?

Yes, PHPMailer is amended than nan mail() function for astir usage cases. Here’s why:

  • Reliability. Works pinch SMTP, reducing nan chance of emails landing successful spam.
  • Security. Supports modern authentication methods for illustration TLS.
  • Flexibility. Allows attachments, HTML formatting, and precocious headers.
  • Compatibility. Widely supported and updated pinch new PHP versions.

If you’re building thing beyond nan simplest script, PHPMailer offers acold much power and consistency than mail().

How to usage PHPMailer to nonstop emails

Follow these wide steps to nonstop emails pinch PHPMailer:

  1. Download and instal PHPMailer utilizing Composer aliases GitHub.
  2. Load nan library successful your PHP book pinch an autoloader aliases manually.
  3. Create a caller PHPMailer instance.
  4. Configure SMTP settings (server, port, username, password).
  5. Set email details for illustration sender, recipient, subject, and body.
  6. Send nan email and grip imaginable errors.

Here’s a elemental example:

<?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require 'vendor/autoload.php'; $mail = caller PHPMailer(true); try { // SMTP configuration $mail->isSMTP(); $mail->Host = 'smtp.example.com'; $mail->SMTPAuth = true; $mail->Username = 'your@email.com'; $mail->Password = 'password'; $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $mail->Port = 587; // Email settings $mail->setFrom('your@email.com', 'Your Name'); $mail->addAddress('recipient@domain.com'); $mail->Subject = 'Test Email'; $mail->Body = 'This is simply a trial email sent utilizing PHPMailer.'; $mail->send(); echo 'Message has been sent'; } drawback (Exception $e) { echo "Error: {$mail->ErrorInfo}"; }

Installing PHPMailer

The easiest measurement to instal PHPMailer is pinch Composer, nan PHP dependency manager. Run this bid successful your project’s guidelines directory:

composer require phpmailer/phpmailer

After installation, you’ll spot PHPMailer wrong nan vendor/ files of your project:

/your-project /vendor /phpmailer /phpmailer

To usage it, load nan Composer autoloader astatine nan apical of your PHP script:

require 'vendor/autoload.php';

If you don’t usage Composer, you tin besides download PHPMailer from GitHub. In that case, spot nan PHPMailer files successful your task and see nan files manually:

require 'PHPMailer/src/PHPMailer.php'; require 'PHPMailer/src/SMTP.php'; require 'PHPMailer/src/Exception.php';

Composer is powerfully recommended for beginners since it handles limitations and makes updates easier.

Understanding PHPMailer components

PHPMailer provides galore methods and properties to build master emails. Here are nan astir important ones, on pinch short examples you tin reuse:

  • setFrom() – defines nan sender’s reside and name.
$mail->setFrom('no-reply@domain.com', 'Website Name');
  • addAddress() – adds 1 aliases much recipients.
$mail->addAddress('user@example.com', 'John Doe'); $mail->addAddress('admin@example.com'); // aggregate recipients
  • addReplyTo() – specifies nan reply-to email. Useful for interaction forms.
$mail->addReplyTo('support@domain.com', 'Support Team');
  • Subject – sets nan taxable statement of nan email.
$mail->Subject = 'Order Confirmation';
  • Body – nan main HTML aliases plain matter content.
$mail->Body = '<h1>Thank you!</h1><p>Your bid has been received.</p>';
  • AltBody – plain-text fallback for clients that don’t support HTML.
$mail->AltBody = 'Thank you! Your bid has been received.';
  • addAttachment() – attaches files.
$mail->addAttachment('/path/to/invoice.pdf', 'Invoice.pdf');

These building blocks springiness you afloat power complete really your email looks and works, making it much reliable than PHP’s basal mail() function.

Using PHPMailer pinch Hostinger SMTP

Most hosting providers, including Hostinger, let you to nonstop emails utilizing their SMTP servers. This is nan recommended method, arsenic it improves deliverability and reduces nan consequence of your emails being flagged arsenic spam.

To usage Hostinger’s SMTP pinch PHPMailer, you’ll request these details:

  • SMTP server: smtp.hostinger.com
  • Port: 587 (TLS) aliases 465 (SSL)
  • Username: your afloat email reside (for example, yourname@yourdomain.com)
  • Password: nan password for that email account

Here’s an illustration configuration:

$mail->isSMTP(); $mail->Host = 'smtp.hostinger.com'; $mail->SMTPAuth = true; $mail->Username = 'your@hostinger.com'; $mail->Password = 'password'; $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // aliases ENCRYPTION_SMTPS for larboard 465 $mail->Port = 587;

🔑 Beginner tips:

  • Make judge you’ve already created an email relationship successful hPanel → Emails → Manage → Create caller account.
  • The SMTP password is nan 1 you group erstwhile creating nan email account, not your Hostinger login password.
  • Test your credentials successful Webmail first. If you tin log successful there, they should besides activity pinch PHPMailer.

Once configured, PHPMailer will usage Hostinger’s servers to present emails securely.

Creating a PHPMailer interaction form

PHPMailer is often utilized for interaction forms. You’ll request an HTML shape connected nan page and a PHP handler that uses PHPMailer to nonstop nan message.

Step 1. Add a basal HTML form

This shape will cod nan visitor’s name, email, and message. Save it arsenic index.html aliases spot it wrong your webpage:

<form method="POST" action="/contact.php"> <label for="name">Name</label> <input id="name" name="name" type="text" required> <label for="email">Email</label> <input id="email" name="email" type="email" required> <label for="message">Message</label> <textarea id="message" name="message" rows="6" required></textarea> <button type="submit">Send</button> </form>

Step 2. Handle nan POST petition pinch PHPMailer

Now that nan shape is ready, create a PHP book (contact.php) to process nan submission and nonstop it via PHPMailer. This book takes nan submitted shape data, sanitizes it, and sends it to your email address:

<?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; require 'vendor/autoload.php'; if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Basic validation and sanitization $name = trim($_POST['name'] ?? ''); $email = trim($_POST['email'] ?? ''); $message = trim($_POST['message'] ?? ''); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { exit('Invalid email address.'); } // Escape personification contented earlier including it successful HTML $safeName = htmlspecialchars($name, ENT_QUOTES, 'UTF-8'); $safeEmail = htmlspecialchars($email, ENT_QUOTES, 'UTF-8'); $safeMessage = nl2br(htmlspecialchars($message, ENT_QUOTES, 'UTF-8')); $mail = caller PHPMailer(true); effort { // SMTP $mail->isSMTP(); $mail->Host = 'smtp.hostinger.com'; $mail->SMTPAuth = true; $mail->Username = 'your@hostinger.com'; $mail->Password = 'password'; $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // 587 $mail->Port = 587; // Email content $mail->setFrom('your@hostinger.com', 'Website Contact'); $mail->addAddress('your@hostinger.com', 'Inbox'); $mail->addReplyTo($email, $name); $mail->Subject = 'New interaction shape submission'; $mail->isHTML(true); $mail->Body = "<p><strong>Name:</strong> {$safeName}</p> <p><strong>Email:</strong> {$safeEmail}</p> <p><strong>Message:</strong><br>{$safeMessage}</p>"; $mail->AltBody = "Name: {$name}\nEmail: {$email}\nMessage:\n{$message}"; // Optional record upload // if (!empty($_FILES['attachment']['tmp_name'])) { // $mail->addAttachment($_FILES['attachment']['tmp_name'], $_FILES['attachment']['name']); // } $mail->send(); echo 'Message sent successfully.'; } drawback (Exception $e) { echo 'Error: ' . $mail->ErrorInfo; } }

Useful tips:

  • Validate input connected some customer and server sides to forestall spam and abuse.
  • Set From to an reside connected your domain. Use addReplyTo() for nan visitor’s email truthful replies spell to them.
  • Consider adding a elemental honeypot section aliases CAPTCHA to trim bot submissions.

How to troubleshoot PHPMailer errors

PHPMailer provides elaborate correction messages. Here are immoderate communal ones:

Could not link to SMTP host

This correction usually intends your SMTP server reside aliases larboard is incorrect. Common causes include:

  • Wrong server name. Double-check your hosting provider’s SMTP details. For example, pinch Hostinger, it’s usually smtp.hostinger.com.
  • Blocked port. Many servers artifact larboard 25. Instead, usage port 587 (TLS) aliases 465 (SSL).
  • Firewall restrictions. If you’re testing locally (like connected XAMPP aliases WAMP), your ISP aliases firewall whitethorn artifact outgoing SMTP connections.

👉 If you’re unsure, inquire your hosting supplier which SMTP settings to usage and corroborate whether ports are unfastened connected your network.

SMTP connect() failed

This correction often points to grounded authentication. In different words, PHPMailer is reaching nan server, but your login specifications aren’t accepted. This could beryllium because of:

  • Username issues. Always usage your afloat email reside arsenic nan SMTP username.
  • Incorrect password. If you changed your email password recently, update it successful your script.
  • Encryption mismatch. Make judge you’re utilizing nan correct information method. For example:
    • Port 587 → PHPMailer::ENCRYPTION_STARTTLS
    • Port 465 → PHPMailer::ENCRYPTION_SMTPS

👉 If nan problem persists, effort logging into your email relationship via webmail to corroborate nan credentials are correct.

Message rejected owed to SPF/DKIM/DMARC

This intends nan recipient’s message server rejected your connection because your domain doesn’t person due authentication records. These are DNS records that beryllium you’re authorized to nonstop email from your domain:

  • SPF (Sender Policy Framework). Tells message servers which IPs aliases hosts tin nonstop emails for your domain.
  • DKIM (DomainKeys Identified Mail). Adds a integer signature that verifies your connection wasn’t tampered with.
  • DMARC (Domain-based Message Authentication, Reporting & Conformance). Tells receiving servers really to grip messages that neglect SPF aliases DKIM checks.

👉 To hole this, log successful to your domain registrar aliases hosting sheet and adhd nan required DNS records. Most hosting providers, including Hostinger, supply step-by-step guides for mounting up SPF, DKIM, and DMARC.

Without these records, your emails are overmuch much apt to onshore successful spam aliases beryllium rejected entirely.

Can I nonstop emails from PHPMailer to Gmail aliases different email services?

Yes. PHPMailer useful pinch Gmail, Outlook, Yahoo, and astir different providers. You conscionable request nan correct SMTP settings and authentication method. For example, usage these specs for Gmail:

  • SMTP server: smtp.gmail.com
  • Port: 587 (TLS) aliases 465 (SSL)
  • Username: your afloat Gmail address
  • Password: your App Password if 2-step verification is enabled
  • In your Google Account, create an App Password nether Security → 2-Step Verification → App passwords and usage it successful $mail->Password.

Example:

$mail->isSMTP(); $mail->Host = 'smtp.gmail.com'; $mail->SMTPAuth = true; $mail->Username = 'yourname@gmail.com'; $mail->Password = 'your-app-password'; // not your regular login $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $mail->Port = 587;

There whitethorn beryllium immoderate supplier limits to consider. Many free mailboxes limit regular sends. For example, Gmail has a debased regular headdress for SMTP. If you request higher measurement aliases faster delivery, see a dedicated email work successful nan future. PHPMailer tin talk to immoderate SMTP server, truthful switching later is straightforward.

General checklist:

  • Use nan provider’s recommended larboard and encryption.
  • Authenticate pinch nan correct credentials.
  • Set From to a domain you power for amended deliverability.
  • Add SPF, DKIM, and DMARC records to your domain to build trust.

Is email still nan backbone of online services?

Absolutely. Email remains nan astir reliable measurement to present transactional messages, trading campaigns, and customer support replies, moreover arsenic caller connection devices emerge. For businesses, master email setups pinch automation prevention clip and amended engagement.

If you want to standard beyond manual emails, explore email trading automation to streamline campaigns and customer communication.

All of nan tutorial contented connected this website is taxable to Hostinger's rigorous editorial standards and values.

Author

The author

Matleena Salminen

Matleena is simply a seasoned Content Writer pinch 5 years of contented trading experience. She has a peculiar liking successful emerging integer trading trends, website building, and AI. In her free time, Matleena enjoys cups of bully coffee, tends to her pavilion garden, and studies Japanese. Follow her connected LinkedIn