Send Emails From Your Web Server With the PHP mail() Function and PHPMailer
Most businesses choose to create a professional email account to boost their credibility and build customer trust. To accomplish this, you just need to buy a domain and set up your business email on an email client or a server.
If you build your website or web application with the PHP programming language, you can send emails directly from your web server. The PHP mail functionality enables you to create custom mail forms and send basic text-based emails to multiple recipients.
There are two ways to send emails in PHP ‒ using the built-in PHP mail() function or a mail-sending library such as PHPMailer.
In this article, we’ll cover the differences between PHPMailer and the mail() function, showing you how to send emails with both.
What Is PHP Mail?
PHP mail is a function for sending emails with PHP scripts. The built-in PHP function can target multiple recipients per email sending. However, it isn’t suitable for bulk emailing without using an external PHP mailing package like PHPMailer.
PHPMailer vs mail() Function: Pros and Cons
PHP mail allows PHP-based website administrators to send mail from their web server using PHP scripts. It’s a popular alternative to getting a third-party email hosting service, as the PHP function is integrated with the web server.
Sending emails in PHP is possible via the native PHP mail() function or an external PHP mailing package like PHPMailer. Here’s a brief coverage of each method, including their advantages and disadvantages:
PHP mail() Function
Mail() is a PHP function that uses PHP scripts to send simple emails. The mail function includes three mandatory parameters ‒ $to, $subject, and $message. Optional parameters to utilize include $headers and $parameters. We’ll cover them in more detail later.
This built-in PHP function returns a boolean value upon execution ‒ TRUE if the server successfully receives the email for sending or FALSE on failure.
Advantages:
- Pre-installed and ready to use, all you need is to have PHP.
- Backward-compatible, a PHP version change won’t break the script.
- Easy to learn.
Disadvantages:
- Hard to set up with SMTP – will trigger recipient spam filters.
- Not suitable for sending a large number of emails.
- The TRUE return value doesn’t guarantee email delivery.
PHPMailer
PHPMailer is a popular mail-sending library that supports the process via the mail() function or through a Simple Mail Transfer Protocol (SMTP) server. It gives access to a set of functions for sending mail, simplifying the manual PHP mail configuration process.
Advantages:
- Introduces complex email structures, such as HTML documents and attachments.
- Supports SMTP, and authentication is integrated over SSL and TLS.
- Can send a lot of emails in a short period.
Disadvantages:
- Requires installation.
- Steep learning curve.
How to Use PHPMailer to Send Emails
In this section, we’ll cover the steps of using PHPMailer to send mail. We recommend using an authenticated SMTP connection with PHPMailer to increase your emails’ deliverability against spam filters.
Installing PHPMailer
Installing PHPMailer is quite simple, especially when using Composer.
Use the composer command to activate Composer version 1.10. If you need the new 2.0 version or you’re using PHP version 8.0 or later, execute the composer2 command.
Follow these steps to install PHPMailer manually:
- Connect to your account via an SSH client.
- From your cPanel dashboard, go to Advanced → SSH Access and take note of the SSH IP, port, username, and password under the SSH details.
- Open PuTTY and enter your SSH information in the Host Name (or IP address) and Port fields. Then, click Open.
- Once a command window appears, type in your SSH username and password and hit Enter. Remember that PuTTY will not display the password, so don’t be surprised if it doesn’t appear on the screen.
- Execute the following command to navigate to the public_html directory:
- Run the following command to install Composer:
- Wait a moment until the installation process is finished. Here’s what it should look like:
Understanding PHPMailer Components
To understand how PHPMailer works, let’s review each script component above.
use PHPMailer\PHPMailer\PHPMailer;
– imports the PHPMailer class to the global namespace.require '../vendor/autoload.php';
– includes various libraries that PHPMailer needs.$mail = new PHPMailer;
– creates a new PHPMailer object.$mail->isSMTP();
– tells PHPMailer class to use the custom SMTP configuration defined in the script instead of the local mail server.$mail->SMTPDebug = 2;
– detects if something goes wrong with the SMTP connection.$mail->Host = 'smtp.server.com';
– this is where the SMTP server address should be specified.$mail->Port = 587;
– set the SMTP port here. We’ll pick SMTP port 587 as the default mail submission port for all types of SMTP data transmission.$mail->SMTPAuth = true;
– activates SMTP authentication.$mail->Username = 'mymail@myawesomedomain.tld';
– specify your email address here.$mail->Password = 'My$tr0ngPa55w0rd!;
– enter your email password here.$mail->setFrom('mymail@myawesomedomain.tld', 'Your Name');
– this is where you insert the sender’s email address.$mail->addReplyTo('mymail@myawesomedomain.tld', 'Your Name');
– informs the recipient which address they should reply to.$mail->addAddress('recipient@domain.tld', 'Receiver Name');
– insert the recipient’s address here.$mail->Subject = 'Checking if PHPMailer works';
– add the email subject here.$mail->msgHTML(file_get_contents('message.html'), __DIR__);
– reads an HTML message body from an external file. The file_get_contents() function will load the content from message.html, a local file located in the public_html directory, and include it in the message.$mail->Body = 'This is just a plain text message body';
– contains the mail message body.//$mail->addAttachment('attachment.txt');
– if you want to include attachments, add the file names and remove the double slash from this statement.if (!$mail->send()) {
– defines what happens when the script is executed.echo 'Mailer Error: ' . $mail->ErrorInfo;
– you will see an error message and details of the error if the script fails to send.} else {
– extends the if statement and describes what happens if the previous condition is not met.echo 'The email message was sent!';
– means the email sending process is successful.
The SMTPDebug = 2; line is only applicable when you test a script and want to see how it operates. Remember to change it to SMTPDebug = 0; when you are done with the test to prevent receivers from catching the SMTP protocol delivery report.
Follow the steps below:
- Create an email account by accessing cPanel, then go to Emails → Email Accounts → Create email account.
- Fill in the new email address and set a password. Then, click Create. Remember this information as you will use it to send mail via PHPMailer.
- From the same page, go to Configuration Settings → Manual Configuration and take note of the SMTP Port and Hostname.
- Access the cPanel dashboard and navigate to Files → File Manager. Click on the public_html folder and select Add New to create a new file. Name the file phpmailer.php and click Create.
- Double-click on the phpmailer.php file, and copy and paste the code below after making all the necessary changes. Make sure to replace the mymail@myawesomedomain.tld and recipient@domain.tld with your existing domain and My$tr0ngPa55w0rd! with your email account password.
6. After editing the code, click Save & Close. To execute the script, enter yourdomain.tld/phpmailer.php in your web browser.
Creating a PHPMailer Contact Form
Other than using PHPMailer to send out simple PHP mail, users can create various contact forms with it, such as feedback surveys.
Similar to previous PHP scripts, create a new PHP file in the public_html folder and name it formscript.php. Copy and paste the script below into the new file and modify the values accordingly:
Pro Tip
Taking user input from $_POST and using it unsanitized is not safe due to cross-site scripting (XSS) attacks. To avoid this, check out the best practices for PHP variable sanitization.
Save your changes and run the script from your browser.
Here’s what the result will look like:
If a visitor submits a message via the form, they will get a confirmation. The form’s content will be sent to the email address you entered here:
Pro Tip
If the PHPMailer contact form doesn’t work, change the $mail->SMTPDebug = 0; line to $mail->SMTPDebug = 2 to identify the cause. Don’t forget to remove the line or change the 2 to 0 after.
Visit PHPMailer’s official repository on GitHub to check out other examples of how to use this mail-sending library.
If you’re a WordPress user, use a contact form plugin like Formidable Forms, Contact Form 7, or WPForms to streamline the form-building process.
How to Send Emails Using the PHP Mail() Function
Another method to send emails directly from PHP is the built-in mail() function. To use the PHP mailer feature, users hosting their PHP application or site on a local server will need to configure a Sendmail program by changing the php.ini file in their PHP installation folder.
If you use a hosting server, Sendmail usually comes already pre-configured. However, you must ensure that your hosting provider allows you to manage the Sendmail service option manually.
By default, the Sendmail service is already enabled. Nevertheless, double-check to be sure.
Important! Titan Mail enables the PHP mail() function by default. Thus, you can’t switch it on or off in hPanel.
Understanding PHP Mail Components
To help you understand the PHP mail() function, we’ll review the components of the PHP script used in the previous section.
The first two lines above enable error reporting to inform you if the PHP script has failed to execute.
This line contains the sender’s email address. Most hosting providers forbid adding random email addresses here due to spoofing risk. Therefore, it’s better to use one with your domain name to execute the script successfully.
The recipient’s email address goes here. Separate the email addresses with commas if you want to send multiple emails.
Enter the email subject line here.
Here, input the body of your email message.
This line is commonly used to include additional headers like From, Reply-To, and Cc. You can separate them with the CRLF.
This script executes the mail() function and checks whether it has run successfully.
The message above will appear if the mail() function is executed successfully.
Alternatively, you will see this message if the mail() function fails.
Although additional headers are optional, it’s essential to include the From header when sending mail. Otherwise, you’ll receive a notification like this:
For more information about the Sendmail function and its parameters, refer to the official PHP documentation.
Creating a Test File for PHP Mail
After assuring that Sendmail is active, create a PHP mail file inside the public_html directory.
Here’s how to do it:
- From cPanel, navigate to Files → File Manager to access File Manager.
- Double-click the public_html folder and select the New File icon at the top. Name this new file testmail.php and hit Create.
- Double-click on testmail.php to edit it. You can use the basic PHP code below but change the parameters accordingly. We’ll describe the script components in more detail in the following subsection:
- Click Save & Close once finished.
- Send the email by accessing yourdomain/testmail.php from your web browser. Remember to change “yourdomain” to the domain used when creating testmail.php.
Sending HTML Emails With PHP
PHP mail() function can also be used to send an HTML email. This format is highly customizable compared to a plain text message.
The process to send HTML mail is the same, but you need to include an HTML message and additional parameter headers this time.
Here is an example of a basic script to send an HTML email:
How to Troubleshoot Common PHP Mail and PHPMailer Errors
In the following section, we’ll review some of the most common issues that might occur when using the PHP mail() function or PHPMailer and how to fix them.
Sender Address Rejected: Not Owned by the User
This error means the server could not authenticate the sender using the provided details. To fix it, check the email address you’ve used to send the message and ensure it corresponds to an existing one.
Also, make sure your Sender Policy Framework (SPF) is enabled. Check your SPF record by going to cPanel, and navigating to Emails → Email Accounts → DNS settings → Manage Email Delivery.
If the SPF record is enabled, it will be shown as Active.
Gmail Couldn’t Verify That Domain.TLD Sent This Message
If you see this warning when testing a PHP mail script, the cause might be one of the following:
- There is no SPF record in the domain’s DNS Zone. If the record is missing, or you’re using external nameservers, add a new SPF TXT record manually via hPanel or cPanel.
- You used invalid SMTP authentication details. Make sure to use an existing email address that belongs to you.
Mail Goes to the Spam Folder
There are various reasons why PHP mail might trigger spam filters. Some of the most common causes include:
- Misleading or spam-like subject. It usually happens when using terms such as “test” or “urgent.” Be sure to set a clear intent in the Subject line.
- Incorrect sender address. Adding the wrong address can invoke security measures to filter your email to prevent spoofing and scams.
- Using spam trigger words. Remove spammy words like “a great offer” and “this is not spam” from your message to increase your email’s credibility.
- Your mailing list doesn’t have an unsubscribe link. Ensure to include an unsubscribe button to prevent this issue and build reader trust.
Could Not Connect to SMTP Host
Newer PHP versions usually have stricter SSL behavior. If the PHP mail() function fails to execute after updating your PHP to the latest version, this might be what causes it.
Using PHPMailer with some hosting providers usually triggers this code error as well.
For example, according to the PHPMailer wiki, GoDaddy blocks outbound SMTP connections via ports 25, 465, and 587 to third-party servers like Gmail and Hotmail except their own. Furthermore, it doesn’t support integration with third-party SMTP servers.
Use the following script to resolve this error: