How do I send PHP mail via SMTP or with my cPanel email?

How Do I Send PHP Mail via SMTP or with My cPanel Email?

How do I send PHP mail using my cPanel email account?

Sending email via PHP is a common requirement for web applications.

Using your cPanel email with SMTP is a secure, reliable way to ensure that emails are delivered without falling into spam folders or failing authentication. In this comprehensive guide, I will walk you through the steps to send PHP mail using SMTP, address common issues, and provide best practices to improve security and deliverability.

What Is PHP Mail and Why Use SMTP with cPanel Email?

The default PHP mail() function provides a simple way to send emails, but it has limitations:

  • Emails often land in spam due to insufficient authentication.
  • Limited ability to send emails via third-party email servers.
  • Lack of advanced features like encryption.

Using SMTP (Simple Mail Transfer Protocol) with your cPanel email ensures proper authentication, encryption, and compatibility with major email providers like Gmail, Yahoo, and Outlook.

This article or knowledge base answers the following: 

  • How do you enable the PHP mail function in cPanel?
  • How do you set up the cPanel send email PHP function?
  • How do you access your cPanel SMTP settings?
  • How to setup SMTP or email notification for WordPress or my Website 

Step-by-Step Guide to Send PHP Mail via SMTP Using cPanel

Step 1: Create an Email Account in cPanel

  1. Log in to your cPanel account.
  2. Go to the Email Accounts section under the "Email" tab.
  3. Click on Create and:
    • Enter the email address you want (e.g., admin@yourdomain.com).
    • Set a secure password.
    • Choose the storage space.
  4. Click Create Account.

Note: For AkolagTech's client, by default, your AkolagTech's cPanel hosting comes with a default email account, and it usually your cPanel username and the same password; exampleusername@example.com

Step 2: Note Your Email Settings

Where can I find my Email settings from cPanel?

Example of your cPanel Email client's settings:

In cPanel, navigate to Email Accounts → Click Connect Devices beside your email address. Copy the following details:

  • Incoming Server: mail.yourdomain.com
    • IMAP Port: 993 POP3 Port: 995 
  • Outgoing Server (SMTP): mail.yourdomain.com
    • IMAP, POP3, and SMTP require authentication.
  • SMTP Port: 465 (SSL) or 587 (TLS)
  • Username: Your full email address (e.g., admin@yourdomain.com).
  • Password: The one you set earlier.

Step 3: Install PHPMailer in Your PHP Application

Using PHPMailer simplifies the process of sending emails via SMTP. To install it:

  1. If you’re using Composer (preferred), run the following command:
    bash
     
    composer require phpmailer/phpmailer
  2. Alternatively, download the library from GitHub PHPMailer Repository and include it in your project.

How to enable PHP mail() function in cPanel WHM?

  • Login to your cPanel WHM with your admin credential
  • Navigate to "Home »Server Configuration »Tweak Settings"  or Search for "tweak" in the search bar
  • Select "Mail" from the menu or type "PHP" from the find search bar
  • Scroll down to the "Prevent “nobody” from sending mail [?]" section and select "off"
  • Scroll down to the bottom and hit the Save button
  • And you just enable PHP mail function for your cPanel client via WHM

How to enable PHP mail() function in cpanel, WHM

Note: it is not advisable to enable this feature because you can expose your cPanel client to spamming, the recommendation is to enable "Prevent “nobody” from sending mail [?]" and the SMPT option is better and more secure

If AkolagTech is your hosting provider, the PHP mail() function to send an e-mail is disabled by default to prevent spamming emails, and you can send an email via SMTP. If you are using another hosting provider and the PHP mail feature is not enabled, you can ask your provider to enable it


I would like to send an email notification or would like to send an email from my PHP code

  • If you use the PHP mail function, The PHP mail function is a method to send an email directly from your website. 
  • This would allow you to send an email response to your end users.
  • Auto respond to a Newsletter, submit action, and more
  • You can read more about the function and what it does on PHP's website: http://php.net/manual/en/function.mail.php
  • If you are new to PHP coding, you can learn the basics, for beginners, recommend w3schools 

Example of PHP code within HTML 

<!DOCTYPE html>
<html>
<body>

<?php
echo "Hello world, My PHP Code";
?> 

</body>
</html>

Example of PHP mail function:

The mail() function enables you to send emails directly from a script that you can include in your HTML code.

To learn more about the PHP Mail function, click here

Syntax: 

mail(to,subject,message,headers,parameters);

  • to: the receiver's email address
  • subject: The subject of the email, you can not add newline characters to subject "\n"
  • message: For the body or message to be sent, you can use newline "\n" for the message, each line can not exceed 70 characters
  • headers: Optional, this is an additional email add-on like "CC", "BCC"
  • from: the sender of the email

<?php

//testing my first php mail()

mail('user@domain.com', 'Subject Line Here', 'Body of Message Here', 'From: info@domain.com');

?>

To send a test email using the PHP Mail function

  • You can test your PHP script copy and paste the code below
  • Note: Make sure you change the email "test@example.com" to the right email 

Example #1: send a test email with variable and values syntax

<? 

$to      = 'test@example.com'; 

$subject = 'The test for php mail function'; 

$message = 'Hello'; 

$headers = 'From: test@test.com' . "\r\n" . 

    'Reply-To: test@test.com' . "\r\n" . 

    'X-Mailer: PHP/' . phpversion(); 

mail($to, $subject, $message, $headers); 

?>

Example #1.2: send a test email for a line that is larger than 70 characters

<?php

// The message

$message = "Line 1\r\nLine 2\r\nLine 3";

// In case any of our lines are larger than 70 characters, we should use wordwrap()

$message = wordwrap($message, 70, "\r\n");

// Send

mail('caffeinated@example.com', 'My Subject', $message);

?>

Example #2: Sending PHP mail with extra headers.

The addition of basic headers, telling the MUA the From and Reply-To addresses:

<?php

$to      = 'nobody@example.com';

$subject = 'the subject';

$message = 'hello';

$headers = 'From: webmaster@example.com' . "\r\n" .

    'Reply-To: webmaster@example.com' . "\r\n" .

    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

?>

Write the PHP Code

Here’s a working example of PHP code to send emails using PHPMailer:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php'; // Load PHPMailer library

$mail = new PHPMailer(true);

try {
// Server settings
$mail->SMTPDebug = 0; // Set to 2 for verbose debug output
$mail->isSMTP();
$mail->Host = 'mail.yourdomain.com'; // Your SMTP server
$mail->SMTPAuth = true;
$mail->Username = 'admin@yourdomain.com'; // SMTP username
$mail->Password = 'your_password'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // Encryption type
$mail->Port = 465; // Port for SSL

// Recipients
$mail->setFrom('admin@yourdomain.com', 'Your Name');
$mail->addAddress('recipient@example.com'); // Add recipient

// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'Test Email';
$mail->Body = '<p>This is a test email sent via PHP using SMTP and cPanel email.</p>';
$mail->AltBody = 'This is the plain text version of the email content.';

$mail->send();
echo 'Email has been sent successfully';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>

Test Your Script

Save the script as send_email.php, upload it to your server, and run it in your browser (e.g., https://yourdomain.com/send_email.php).

 

How do I set up SMTP or email notifications for WordPress or my website?

Please follow the steps below if you would like to send out email notifications from your WordPress/Website, such as WooCommerce, WPForm, and other plugins.
Note: Most of the time, WordPress cannot send email notifications until you have configured your email. By default, if you host with us (Akolag Hosting), we do not enable the PHP mail function for security protection, preventing sending emails as nobody.

Various plugins would allow you to accomplish this task, and you do not have to write code to set up notifications.
I recommend installing either WPForm or WP SMTP MAIL by wp form to set up your SMTP/email notification. This will require your email authentication.

Please follow the steps in the link below
https://wpforms.com/how-to-fix-wordpress-contact-form-not-sending-email-issue/

Note: you can use another plugin to accomplish this, but the most important thing is to allow your WordPress/Website to send out an email on your behalf

 

Common Issues and Solutions

Authentication Errors

  • Error: "SMTP Error: Could not authenticate."
    • Solution: Double-check your SMTP username and password. Ensure they match the email account credentials you created in cPanel.

Emails Going to Spam

  • Error: Emails are being flagged as spam.
    • Solution: Ensure proper SPF, DKIM, and DMARC records are configured for your domain in cPanel. These records authenticate your domain to prevent spoofing.

TLS/SSL Errors

  • Error: "Connection failed due to SSL/TLS errors."
    • Solution: Ensure the correct encryption (SSL/TLS) and port (465/587) are used in the PHPMailer configuration.

Cannot Connect to SMTP Server

  • Error: "Could not connect to SMTP host."
    • Solution: Verify that the firewall or hosting provider isn’t blocking outbound SMTP connections on ports 465/587.

Best Practices for Email Security

  1. Use Encryption: Always use SSL or TLS for secure email communication.
  2. Configure SPF, DKIM, and DMARC Records:
    • SPF: Authorizes your server to send emails on behalf of your domain.
    • DKIM: Adds a digital signature to verify the sender.
    • DMARC: Prevents unauthorized usage of your domain.
    • Set these records in the DNS zone editor of your cPanel.
  3. Enable Two-Factor Authentication (2FA): Add an extra layer of security to your cPanel account.
  4. Monitor Email Logs: Use cPanel’s "Track Delivery" feature to monitor email delivery and diagnose issues.
  5. Avoid Overloading SMTP Server: Use rate limiting if sending bulk emails to prevent server blacklisting.

Keywords and Related Topics to Boost Traffic

Primary Keywords:

  • PHP mail via SMTP
  • Send an email using PHPMailer
  • Configure cPanel email SMTP

Secondary Keywords:

  • Troubleshoot PHP mail errors
  • SMTP authentication PHP
  • Secure email sending PHP
  • SPF, DKIM setup in cPanel

Related Topics:

  • "How to Set Up SPF, DKIM, and DMARC in cPanel"
  • "Top 5 Email Libraries for PHP in 2024"
  • "Troubleshooting Common SMTP Issues in PHP"
  • "Best Practices for Secure Email Sending in Web Applications"

Advanced Tips to Rank #1 on Search Engines

  1. Unique, High-Quality Content:

    • Use real-life examples, troubleshooting cases, and practical solutions.
    • Add videos or infographics to explain concepts visually.
  2. Internal Linking:

    • Link to other articles or guides on your website to keep visitors engaged.
  3. SEO Optimization:

    • Ensure keywords are naturally integrated into the title, headings, and body.
    • Add an engaging meta description to increase click-through rates.
  4. Backlink Building:

    • Contact tech bloggers and forums to share your guide and gain backlinks.
  5. Regular Updates:

    • Keep the article updated with new information, such as changes in cPanel or PHP versions.
  6. User Engagement:

    • Add a comments section for users to ask questions and interact.
    • Include a downloadable PDF version of the guide for added value.

==========================================================================

NEED A HOSTING SOLUTION OR LOOKING TO SWITCH HOSTING PROVIDER


 

To access your default email or create email 

  • For steps to access webmail on AkolagTech(If you have a hosting plan with us) cPanel click here

Links to other useful resources:

  • php email, smtp email, sendmail, cpanel send email php how to enable php mail function in cpanel , cpanel send email php, smtp settings cpanel, cpanel smtp, cpanel email, wordpress email, smtp for wordpress, woocommerce email, website email, email notification
  • 15 Users Found This Useful
Was this answer helpful?

Related Articles

How to sign up for AkolagTech hosting plan - Video

How to sign up for AkolagTech hosting plan?Video Tutorial on how to sign up for hosting plan

AkolagTech hosting platform login and navigation - Video

How to log-in and navigate to AkolagTech platform video tutorial 

AkolagTech Hosting Platform Tutorial (Web, Email, Cloud) info

How to log-in and navigate through the hosting platform  Access to your product and services...

HOW TO INSTALL SOFTWARE, PLUGINS, AND APPS ON YOUR AKOLAGTECH HOSTING ACCOUNT?

ABOUT THE HOSTING PLATFORM AkolagTech hosting platform for SME/SMB, developers (web developers,...

How to access AkolagTech's cPanel and single sign-on

Thanks for signing up for our hosting platform, we make your hosting with us simple. AkolagTech...