Jul 21, 2022 Show
Domantas G. 9min Read If your website or web application is built on PHP, you can utilize the PHP mail feature to send emails. It can come in handy for creating custom-built mail forms and sending simple text-based email messages. There are typically two ways of sending emails with PHP – using the inbuilt PHP mail() function or an email sending library such as PHPMailer. In this tutorial, we’ll go over how to send emails using both methods and identify some common PHP mail issues, and how to fix them. Download Website Launch Checklist
How to Send Emails Using PHP mail() FunctionThe first method to send emails directly from a PHP script is by using the built-in mail() function. To use the PHP send mail 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 is usually already configured. However, you need to make sure that your hosting provider allows you to manually manage the Sendmail service option. Hostinger users can toggle this function by accessing the hPanel and navigating to Emails -> Mail Service Control. By default, the Sendmail service is already enabled. Nevertheless, double-check it to be sure. Creating a Test File for PHP MailAfter making sure that Sendmail is active, we’ll create a PHP mail script file and place it in the public_html directory. Here’s how to do it:
<?php ini_set( 'display_errors', 1 ); error_reporting( E_ALL ); $from = ""; $to = ""; $subject = "Checking PHP mail"; $message = "PHP mail works just fine"; $headers = "From:" . $from; if(mail($to,$subject,$message, $headers)) { echo "The email message was sent."; } else { echo "The email message was not sent."; } ?>
Understanding PHP Mail ComponentsTo help you understand the PHP mail() function, we’ll go over the components of the PHP script we used in the previous section: ini_set( 'display_errors', 1 ); error_reporting( E_ALL ); The first two lines above enable error reporting to tell you if the PHP script has failed to execute. $from = ""; This line should contain the sender’s email address. Most hosting providers forbid adding random email addresses here, as they can be used for spoofing. Thus, it’s better to use one with your domain name to execute the script successfully. $to = ""; The recipient’s email address goes here. If you want to deliver the message to multiple recipients, separate their email addresses with commas. $subject = "Checking PHP mail"; Enter the subject line for the email here. $message = "PHP mail works just fine"; Here, input the body of your email message. $headers = "From:" . $from; This line is commonly used to add additional headers, such as From, Reply-To, and Cc – these extra headers should be separated with a CRLF ( if (mail ($to,$subject,$message,$headers)) This line is used to execute the function and check whether it has run successfully. echo "The email message was sent."; The message above will appear when the script is executed successfully. Alternatively, the message below will be displayed. echo "The email message was not sent."; Keep in mind that although additional headers are optional, it’s essential to mention the From header when sending mail. Otherwise, you’ll receive a notification like: Warning: mail(): "sendmail_from" not set in php.ini or custom "From:" header missing. For more information about the Sendmail function and its parameters, consult the official PHP documentation. Sending HTML Mails in PHPPHP mail() function can also be used to send HTML-formatted emails. This format is highly customizable compared to plain text messages. 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 email with HTML formatting: <?php ini_set( 'display_errors', 1 ); error_reporting( E_ALL ); $from = ""; $to = ""; $subject = "Checking PHP mail"; $message = " <html> <head> <title>This is a test HTML email</title> </head> <body> <p>Hi, it’s a test email. Please ignore.</p> </body> </html> "; // The content-type header must be set when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; $headers = "From:" . $from; if(mail($to,$subject,$message, $headers)) { echo "Message was sent."; } else { echo "Message was not sent."; } ?> How to Use PHPMailer to Send EmailsIf you want to send multiple emails, it’s recommended to utilize an external PHP mailing package. The native PHP mail() function is not suited for larger volumes of emails, as it opens and closes a Simple Mail Transfer Protocol (SMTP) socket connection with each email. There are many PHP mail packages to choose from, including Pear Mail and Swift Mailer. In this article, we’ll use PHPMailer. PHPMailer is a popular mail sending library that supports mail sending via the mail() function or through an SMTP server. It gives access to a set of functions for sending emails, simplifying the process of configuring PHP mail. How to Install PHPMailerInstalling PHPMailer is quite simple, especially if you have Composer installed – many shared hosting plans include this tool. Important! We recommend using Composer 2 if you are running PHP 8. To install PHPMailer manually, connect your hosting account via the SSH terminal by following these steps:
Important! If you are using Composer 2, run the
Using PHPMailer with Hostinger SMTPAfter installing PHPMailer, you can start using it to send PHP emails. In this section, we’ll show you how to send email through the Hostinger SMTP server using PHPMailer:
<?php require 'vendor/autoload.php'; use PHPMailer\PHPMailer\PHPMailer; $mail = new PHPMailer; $mail->isSMTP(); $mail->SMTPDebug = 2; $mail->Host = 'smtp.hostinger.com'; $mail->Port = 587; $mail->SMTPAuth = true; $mail->Username = ''; $mail->Password = 'EMAIL_ACCOUNT_PASSWORD'; $mail->setFrom('', 'Your Name'); $mail->addReplyTo('', 'Your Name'); $mail->addAddress('', 'Receiver Name'); $mail->Subject = 'Testing PHPMailer'; $mail->msgHTML(file_get_contents('message.html'), __DIR__); $mail->Body = 'This is a plain text message body'; //$mail->addAttachment('test.txt'); if (!$mail->send()) { echo 'Mailer Error: ' . $mail->ErrorInfo; } else { echo 'The email message was sent.'; } ?>
Understanding PHPMailer ComponentsTo understand how PHPMailer works, let’s take a look at each component of the script above. use PHPMailer\PHPMailer\PHPMailer; The line above imports the PHPMailer class to the global namespace. require '../vendor/autoload.php'; This line includes various libraries that PHPMailer needs. $mail = new PHPMailer; This creates a new PHPMailer object. $mail->isSMTP(); The code here is used to tell the PHPMailer class to use the custom SMTP configuration defined in the script instead of the local mail server. $mail->SMTPDebug = 2; The $mail->Host = 'smtp.hostinger.com'; This is where the SMTP server address should be specified. $mail->Port = 587; Set the SMTP port here. $mail->SMTPAuth = true; This line is used to turn on SMTP authentication. $mail->Username = ''; Specify your email address here. $mail->Password = 'EMAIL_ACCOUNT_PASSWORD'; Here, enter your email password. $mail->setFrom('', 'Your Name'); This is where you should insert the sender’s email address. $mail->addReplyTo('', 'Your Name'); This line will let the recipient know which address they should reply to. $mail->addAddress('', 'Receiver Name'); Insert the recipient’s address here. $mail->Subject = 'Testing PHPMailer'; Add the email’s subject line here. $mail->msgHTML(file_get_contents('message.html'), __DIR__); This line is used to read an HTML message body from an external file. The $mail->Body = 'This is a plain text message body'; This line contains the mail message body. //$mail->addAttachment('test.txt'); If you want to include attachments, include the file names and remove the double slashes from this statement. if (!$mail->send()) { This line defines what happens when the script is executed. echo 'Mailer Error: ' . $mail->ErrorInfo; It’ll display an error message with an explanation if the script fails to send. } else {
echo 'The email message was sent!'; If the email was sent successfully, this message will appear. Pro TipThe line SMTPDebug = 2; is only useful when you test a script and want to see how it works. Remember to change it to SMTPDebug = 0; if you are done with the test, preventing the receivers from seeing the SMTP delivery report. Creating a PHPMailer Contact FormAside from using PHPMailer to send out simple PHP mail, users can also utilize it to create a contact form, allowing their audience to get in touch with them. Like with the previous PHP scripts, creating a new PHP file in the public_html folder is essential before proceeding. Name it formscript.php. Then, copy and paste the script below into the newly created file and modify the information inside it accordingly: <?php require 'vendor/autoload.php'; use PHPMailer\PHPMailer\PHPMailer; $mail = new PHPMailer; $mail->isSMTP(); $mail->Host = 'smtp.hostinger.com'; $mail->Port = 587; $mail->SMTPAuth = true; $mail->Username = ''; $mail->Password = 'EMAIL_ACCOUNT_PASSWORD'; $mail->setFrom('', 'Mr. Drago'); $mail->addAddress('', 'Receiver Name'); if ($mail->addReplyTo($_POST['email'], $_POST['name'])) { $mail->Subject = 'PHPMailer contact form'; $mail->isHTML(false); $mail->Body = <<<EOT Email: {$_POST['email']} Name: {$_POST['name']} Message: {$_POST['message']} EOT; if (!$mail->send()) { $msg = 'Sorry, something went wrong. Please try again later.'; } else { $msg = 'Message sent! Thanks for contacting us.'; } } else { $msg = 'Share it with us!'; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Contact form</title> </head> <body> <h2>Do You Have Anything in Mind?</h2> <?php if (!empty($msg)) { echo "<h2>$msg</h2>"; } ?> <form method="POST"> <label for="name">Name: <input type="text" name="name" id="name"></label><br><br> <label for="email">Email: <input type="email" name="email" id="email"></label><br><br> <label for="message">Message: <textarea name="message" id="message" rows="8" cols="20"></textarea></label><br><br> <input type="submit" value="Send"> </form> </body> </html> Pro TipTaking user input from $_POST and using it unsanitized can be insecure because of XSS (cross-site scripting) attacks. To avoid this, check out the best practices for PHP variable sanitization. Save your changes, then run the script from your browser. Here’s what the result will look like: If a visitor submits a message through the form, they will get a confirmation message, and the form’s content will arrive in the inbox of the email address you entered here: $mail->addAddress('', 'Receiver Name'); Pro TipIf the PHPMailer contact form does not work, add the $mail->SMTPDebug = 2; line to see what causes the issue. Don’t forget to erase it or change the 2 to 0 once you’re done. To see other examples of using this mail sending library, visit PHPMailer’s official GitHub repository. If you’re a WordPress user, you can instead use contact form plugins such as Formidable Forms, Gravity Forms, or WPForms to create contact forms. How to Troubleshoot Common PHP Mail and PHPMailer ErrorsIn the following sections, we’ll go over 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 UserThis error means that the server was unable to authenticate the sender using the provided details. To fix it, check the email address you’ve used to send the message and make sure it corresponds to an existing one. If it’s pointing to a wrong address, change it. Also, make sure your Sender Policy Framework (SPF) is enabled. If you use Hostinger, check your SPF record by going to the hPanel, and navigate 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 YourDomain.com Sent This MessageIf you see this warning when testing a PHP mail script, the reason might be one of the following:
Mail Goes to the Spam FolderThere are various reasons why PHP mail might trigger spam filters. Some of the most common ones are:
ConclusionThe PHP mail() function is suitable for sending small volumes of simple text-based messages. Meanwhile, PHPMailer is a better method for sending mass emails or creating a contact form. To recap, in order to send an email using the PHP mail feature, create a new PHP file in the public_html directory and input the mail() function. Then, execute the script using your browser. As for sending emails with PHPMailer, you’ll need to install the tool, create an email account for it, and include the values from your SMTP settings in PHPMailer’s script. It’s also essential to create a new PHP file in the public_html folder. This tutorial contains basic syntax examples which can be further used for developing a contact form or other extensions for your website. If you have any tips, tricks, or ideas, feel free to share them in the comments section below. Domantas leads the content and SEO teams forward with fresh ideas and out of the box approaches. Armed with extensive SEO and marketing knowledge, he aims to spread the word of Hostinger to every corner of the world. During his free time, Domantas likes to hone his web development skills and travel to exotic places. How can I use PHP mail with Gmail?Writing the PHP Code to Send Email using Gmail SMTP. Step 1: Download PHPMailer library from this github link. ... . Step 2: Writing the PHP Code to make an SMTP connection. ... . Step 3: Include packages and files for PHPMailer and SMTP protocol: ... . Step 4: Initialize PHP Mailer and set SMTP as mailing protocol:. How do I fix PHP email?If it's still not working: change the sender ($sender) to a local email (use the same email as used for recipient). Upload the modified php file and retry. Contact your provider if it still does not work. Tell your provider that the standard php "mail()" function returns TRUE, but not mail will be sent.
Why is PHP not sending email?It could be, for example, because you're missing necessary parameters, have typos in your recipient's email address, or need to set up an SMTP relay. Out of all the possible options as to why your PHP mail() isn't sending email, we found that most issues stem from Postfix being configured incorrectly.
How do I enable PHP email?To check/change your PHP mail configuration:. Open your php. ini file (if you don't know where this is, see below). Search for the line that reads [mail function]. Add/change the details of your mail server. This could be a local mail server or the mail server of your ISP.. Save/close the php. ... . Restart your web server.. |