Wednesday 26 December 2018

PHP: How to Send Emails Using PHP mail


How to send emails using PHP mail and PHPMailer
In this tutorial, we will learn about PHP mail and how to use it. We’ll also show you how to configure and use PHPMailer — a popular mail sending library.
Overall, email is an integral part of any project or business. Nowadays, being quick and responsive is a huge value, especially when it comes to answering your customers. In a lot of cases, responsiveness and well-planned communication are the deciding factors that users take into consideration when making purchases.
While there are numerous ways to deliver mails, we’ll be looking into PHP mail specifically. At the very core, you can send emails via PHP in two ways:
  • by using PHP’s inbuilt mail() function;
  • by using a third-party library such as PHPMailer with SMTP.
Let’s see how each one works and how we can use it to deliver emails!

What you’ll need

Before you begin this guide you’ll need the following:

Method 1 — Using PHP mail() function

The mail() function in PHP allows sending email using a local sendmail program. Whenever you call the mail() function, it invokes a local sendmail program, usually configured by the system administrator. If your web hosting is at Hostinger, you can enable/disable this functionality in Emails -> Mail Service Control section.
Mail Service Control section in Hostinger panelThe sendmail service is enabled by default. But in case it’s not, you can do it in just a few clicks.
Managing sendmail, POP3/IMAP, and SMTP services

Step 1 — Creating a test file for PHP mail

First of all, we will need to create a file for the PHP mail script. We’ll place it in the public_html directory so that it could be easily accessed through the domain name. You may use the File Manager or an FTP client for this task. Let’s name the file testmail.php.
PHP mail test file example

Step 2 — Understanding PHP mail

Let’s introduce ourselves with the components of a basic PHP mail script:
  1. <?php
  2. ini_set( 'display_errors', 1 );
  3. error_reporting( E_ALL );
  4. $from = "test@hostinger-tutorials.com";
  5. $to = "test@gmail.com";
  6. $subject = "Checking PHP mail";
  7. $message = "PHP mail works just fine";
  8. $headers = "From:" . $from;
  9. mail($to,$subject,$message, $headers);
  10. echo "The email message was sent.";
  11. ?>
The first two lines enable error reporting. This will let help in case the script fails to execute. The remaining ingredients are:
$fromEmail sender address. Most hosting providers do not allow using random email addresses here, as it can be used for spoofing. You should enter an email address created for your domain name to successfully execute the PHP mail.
$toThe recipient email address. As we are sending this for testing purposes it can be a personal email.
$subjectThe subject of the email message.
$messageThis section is for the message content.
$headers Headers specify vital information, such as the sender address, the reply-to location and more.
mail ($to,$subject,$message,$headers) This is the function that executes PHP mail.
echo “The PHP mail was went successfully.”The following message will appear once the script executes.
For more information about sendmail and its components, you can refer to the official PHP documentation.

Step 3 — Running the PHP mail script

If you placed your PHP script in the public_html directory, you can it run by accessing YourDomain.com/testmail.php. You should see the following message:
PHP mail sent successfullyHere’s an example of the received PHP mail using the above code:
PHP mail arrival exampleCongratulations! You now understand the basic syntax of PHP mail and can use it to send messages.

Method 2 — Using PHPMailer

PHPMailer is a popular mail sending library for PHP. It supports mail sending via mail() function or SMTP. In short, PHPMailer is an effective method to send emails in a PHP based environment.

Step 1 — Gathering details for PHPMailer

To use PHPMailer with Hostinger SMTP, you will first need to create an email account. You can do this at Email Account section in the web hosting panel.
Creating a new email accountOnce you’re done, grab your SMTP details located in the same section:
SMTP, IMAP, and POP3 details on Hostinger
You should have four ingredients by now, which are:
  1. Email account username
  2. Email account password
  3. SMTP host
  4. SMTP port

Step 2 — Installing PHPMailer

Since we have all the required details, we can begin the PHPMailer setup. One easy way to do it is by using Composer. It’s pre-installed on our shared hosting plans, so you’ll only need to connect via SSH and execute the following command:
cd public_html
And then run:
composer require phpmailer/phpmailer
Wait a few moments for the installation to finish and PHPMailer will appear in a newly created vendor directory.

Step 3 — Understanding PHPMailer

To understand PHPMailer and how it works let’s investigate an example that uses SMTP for delivery.
  1. <?php
  2. use PHPMailer\PHPMailer\PHPMailer;
  3. require '../vendor/autoload.php';
  4. $mail = new PHPMailer;
  5. $mail->isSMTP();
  6. $mail->SMTPDebug = 2;
  7. $mail->Host = 'smtp.hostinger.com';
  8. $mail->Port = 587;
  9. $mail->SMTPAuth = true;
  10. $mail->Username = 'test@hostinger-tutorials.com';
  11. $mail->Password = 'EMAIL_ACCOUNT_PASSWORD';
  12. $mail->setFrom('test@hostinger-tutorials.com', 'Your Name');
  13. $mail->addReplyTo('reply-box@hostinger-tutorials.com', 'Your Name');
  14. $mail->addAddress('example@gmail.com', 'Receiver Name');
  15. $mail->Subject = 'PHPMailer SMTP message';
  16. $mail->msgHTML(file_get_contents('message.html'), __DIR__);
  17. $mail->AltBody = 'This is a plain text message body';
  18. $mail->addAttachment('test.txt');
  19. if (!$mail->send()) {
  20. echo 'Mailer Error: ' . $mail->ErrorInfo;
  21. } else {
  22. echo 'Message sent!';
  23. }
  24. ?>
Let’s see what each component does:
use PHPMailer\PHPMailer\PHPMailer;This line imports the PHPMailer class to the global namespace.
require ‘../vendor/autoload.php’;Includes various libraries that PHPMailer needs.
$mail->All these variables contain vital information, such as server details, headers, message, attachments and more. In short, they ensure that the sender is legit with SMTP authentication.
if (!$mail->send()) {Defines what happens when the scripts execute.
echo ‘Mailer Error: ‘ . $mail->ErrorInfo;If the script fails to send, you will see what went wrong.
elseDefines what happens if the script does execute.
echo ‘Message sent!’; This message will appear to the user if everything works.
Pro Tip: The line SMTPDebug = 2; is useful when testing the script and seeing how it works.
Set it to SMTPDebug = 0; in the final version to avoid the end user from seeing the SMTP delivery report.
If you checked the whole code, you will notice that we are doing something a little different than in the first example. We are sending an HTML message. Its content will be taken from the message.html file located in the same directory. This lets you format the text and gives greater functionality compared to plain text messages.

Step 4 — Running the PHPMailer script

Lets create a testphpmailer.php file and fill in all the fields with the SMTP details we retrieved earlier. Execute the script by entering YourDomain.com/testphpmailer.php in the browser and you will see a similar message:
PHPMailer test SMTP message successHere’s an example of the received email message:
Receiver view of PHPMailer SMTP messageNotice how the text is formatted this time, as we used HTML instead of plain-text. Furthermore, we were able to add a file attachment.

Step 5 — PHPMailer contact form example

You can use PHPMailer for much more than just sending out simple messages. One way you can utilize it is to create a contact form where your visitors or users can get in touch with you. Here’s a basic example of such script:
  1. <?php
  2. use PHPMailer\PHPMailer\PHPMailer;
  3. require '../vendor/autoload.php';
  4. $mail = new PHPMailer;
  5. $mail->isSMTP();
  6. $mail->Host = 'smtp.hostinger.com';
  7. $mail->Port = 587;
  8. $mail->SMTPAuth = true;
  9. $mail->Username = 'test@hostinger-tutorials.com';
  10. $mail->Password = 'EMAIL_ACCOUNT_PASSWORD';
  11. $mail->setFrom('test@hostinger-tutorials.com', 'Mr. Drago');
  12. $mail->addAddress('example@gmail.com', 'Receiver Name');
  13. if ($mail->addReplyTo($_POST['email'], $_POST['name'])) {
  14. $mail->Subject = 'PHPMailer contact form';
  15. $mail->isHTML(false);
  16. $mail->Body = <<<EOT
  17. Email: {$_POST['email']}
  18. Name: {$_POST['name']}
  19. Message: {$_POST['message']}
  20. EOT;
  21. if (!$mail->send()) {
  22. $msg = 'Sorry, something went wrong. Please try again later.';
  23. } else {
  24. $msg = 'Message sent! Thanks for contacting us.';
  25. }
  26. } else {
  27. $msg = 'Invalid email address, message ignored.';
  28. }
  29. ?>
  30. <!DOCTYPE html>
  31. <html lang="en">
  32. <head>
  33. <meta charset="UTF-8">
  34. <title>Contact form</title>
  35. </head>
  36. <body>
  37. <h1>Let's get in touch!</h1>
  38. <?php if (!empty($msg)) {
  39. echo "<h2>$msg</h2>";
  40. } ?>
  41. <form method="POST">
  42. <label for="name">Name: <input type="text" name="name" id="name"></label><br><br>
  43. <label for="email">Email: <input type="email" name="email" id="email"></label><br><br>
  44. <label for="message">Message: <textarea name="message" id="message" rows="8" cols="20"></textarea></label><br><br>
  45. <input type="submit" value="Send">
  46. </form>
  47. </body>
  48. </html>
And the end result is:
Basic contact form created with PHPMailerOnce the user submit his message, he will get a confirmation and the contents will arrive at the e-mail box entered in the addAddress field.
Pro Tip: In case the PHPMailer contact form does not work, add the following line to see what causes the issue: $mail->SMTPDebug = 2; 
Don’t forget to remove it or set to zero once done!
PHPMailer offers extra examples that you can try in their official GitHub repository. Also, if you are using WordPress, you can easily create a contact form with the help of plugins.

Troubleshooting common PHP mail and PHPMailer errors

PHPMailer is quite an easy tool to master. But errors can occur from time to time. Let’s see the list of most common errors while sending PHP mail and how we can fix them.

Sender address rejected: not owned by the user

The sender address rejected: now owned by user error means that the server was unable to authenticate using the provided details. To fix it, check the from headers and make sure they correspond to an existing e-mail box. If not, make sure to create or change it and the script will start executing. Lastly, make sure that your SPF record is enabled.

Gmail couldn’t verify that example.com sent this message

If you see this warning when testing a PHP mail script, it could mean one of the following:
  • Your SPF record is not enabled. You may find the steps on how to create it here.
  • The from header uses an e-mail address that does not exist or is not owned by you. Make sure to use valid SMTP authentication details.

Mail goes to the spam folder

There can be various reasons why a message can turn up in the spam box. Let’s see a few common ones:
  • Misleading or spammy subject. A few examples would be “Test“; “Hello“; “Testing“; “Urgent” or similar. Make sure that you set a clear intent in your message subject.
  • Incorrect from headers often cause this. It’s a security measure to prevent e-mail spoofing and scams.
  • You used spam trigger words. This category would include phrases as “great offer“; “click here“; “special promotion“; “this is not spam” and similar. Try changing up your message content to see if that’s the case.
  • Your mailing list does not have an unsubscribe button. If enough people report your mails as spammy, then this is bound to happen. Having an unsubscribe button is a great way to avoid this.

0 comments:

Post a Comment