2026-07-15

How to configure PHP to send e-mail?

Stefan Bogdanescu

Stefan Bogdanescu

Founder & Senior Architect

How to configure PHP to send e-mail?

How to Configure PHP to Send Reliable Emails: Moving Beyond the Basic mail() Function

Sending emails programmatically is a fundamental requirement for almost any web application. While the native PHP mail() function seems straightforward, as you discovered, it often leads to frustrating connection errors when trying to connect to standard mail servers like localhost port 25. As senior developers, we need to understand not just how to send an email, but how to send it reliably.

This post will guide you through the limitations of the basic method and introduce the professional, robust approach using SMTP, which is the industry standard for reliable email delivery.


The Pitfalls of the Native mail() Function

The reason your attempt failed with the warning: Failed to connect to mailserver at "localhost" port 25 is because the native PHP mail() function relies on the operating system's underlying Mail Transfer Agent (MTA) configuration. On most modern, secure hosting environments (especially shared or cloud VPS setups), direct connections via port 25 are blocked by firewalls, and setting up a fully functional local MTA within your web server environment is complex and generally insecure.

When you use mail(), PHP essentially hands the job off to the system's configured mail program. If that program isn't properly set up or if you try to connect directly via raw TCP sockets (as implied by trying to force it to localhost:25), it fails. Furthermore, using $from in this context is less about authentication and more about setting the header; for external delivery, proper SMTP authentication is mandatory.

The Professional Solution: Using SMTP

For serious application development, we must abandon relying on the basic system mail function and switch to using a dedicated SMTP (Simple Mail Transfer Protocol) server. SMTP provides authenticated, encrypted communication channels necessary for reliable message delivery.

Instead of trying to configure PHP to be a full-fledged mail server, we instruct PHP to act as a client that connects to an external, reputable mail service provider (like SendGrid, Mailgun, Amazon SES, or even your own Gmail account via their SMTP settings).

Why Use SMTP?

  1. Reliability: Dedicated services manage the complexities of deliverability, spam filtering, and error handling.
  2. Authentication: You authenticate using a specific username and password, ensuring only authorized users can send mail.
  3. Security: Communication is encrypted (via SSL/TLS), protecting sensitive email content.

Step-by-Step SMTP Configuration in PHP

To use SMTP with PHP, you typically need to use PHP's stream functions or dedicated libraries rather than the basic mail() function. While you can configure global settings in php.ini, it is often easier and more flexible to configure these settings per script using environment variables or dedicated classes.

Here is a conceptual example using an external SMTP service (we will use placeholders for configuration details):

<?php
// Configuration for an external SMTP server (e.g., Gmail's SMTP)
$smtp_host = "smtp.gmail.com"; // Change this to your provider's host
$smtp_port = 587;              // Standard port for STARTTLS
$smtp_user = "your_email@example.com"; // Your sending email address
$smtp_pass = "your_app_password";     // Use an App Password, not your main account password!

$to = "recipient@example.com";
$subject = "Reliable Test Mail via SMTP";
$message = "This is a securely sent message.";

// 1. Establish the connection stream
$stream = stream_socket_client("smtp://$smtp_host:$smtp_port", true);

if (!$stream) {
    die("Could not connect to SMTP server.");
}

// 2. Start TLS encryption (for security)
stream_socket_stream_set_crypto_method($stream, STREAM_CRYPTO_METHOD_TLSv1_2);
stream_socket_stream_socket_enable_crypto($stream, STREAM_CRYPTO_METHOD_TLSv1_2, STREAM_CRYPTO_METHOD_TLSv1_2);

// 3. Send the email data (requires complex SMTP negotiation commands)
$mail_data = "EHLO $smtp_host\r\nMAIL FROM:<$smtp_user>\r\nRCPT TO:<$to>\r\nDATA\r\nSubject: $subject\r\n\r\n$message\r\nQUIT\r\n";

fwrite($stream, $mail_data);

// 4. Close the connection
fclose($stream);

echo "Email sent successfully via SMTP.\n";
?>

Controlling the $from Address and php.ini

Regarding your specific questions:

  1. What address to include in the $from variable? When using an external SMTP server, the $from address should be the actual email address you are sending from (the one configured with the SMTP service). This is crucial for sender reputation and authentication checks performed by the mail server.
  2. Do I need an SMTP server? Yes, for reliable, scalable email delivery in a production environment, an external SMTP server is highly recommended over relying on local PHP configuration.
  3. How do I send mails using localhost? You generally do not send application emails directly via localhost:25. Instead, your web application (like one built with Laravel) should use robust packages that handle the secure communication layer for you. For example, modern frameworks prioritize services like Laravel's Mail facade which abstract away these low-level connection details, focusing on sending mail reliably, much like how architecture principles discussed at https://laravelcompany.com emphasize building robust systems from the ground up.
  4. What to edit in php.ini? You rarely need to heavily modify php.ini for modern SMTP if you use a dedicated library or service integration. If you must configure it, you are usually setting up basic network connection parameters (like enabling necessary extensions), not the full mail server configuration itself.

Conclusion

For any professional PHP application, stop relying on the deprecated or unreliable mail() function. Embrace SMTP. By configuring your application to connect to a dedicated, authenticated mail service, you shift the burden of deliverability and security onto specialized providers. This ensures that your users actually receive their messages, which is the ultimate goal of any successful software architecture.

Note: Blog content is currently available in English.

Tags:

Enhance your marketing setup with your own email marketing platform.

Join the growing number of SaaS platforms using Laravel Mail to offer email marketing solutions to their customers.