Recipe 2: Sending Email from a command prompt in PHP
Introduction
This article shows how to send a single email in PHP. We will build on this script in another article to expand its functionality to send bulk emails.
Prerequisites
Here are the prerequisites before you can run the script
- Make sure you have PHP installed on your system
- Download & Install composer
(e.g. https://getcomposer.org/download/) - Go to command prompt
- Create a new folder where you want to store the email script
- Go to the newly created folder
- Install PHPMailer PHP module by running the following command:
composer require phpmailer/phpmailer
The Script
Next, create the following script in your favourite text editor. Call the file “sendemail.php”.
<?php require("./vendor/phpmailer/src/PHPMailer.php"); require("./vendor/phpmailer/src/Exception.php"); require("./vendor/phpmailer/src/SMTP.php"); $mail = new PHPMailer\PHPMailer\PHPMailer(); $subject = "Test"; $body = "Email body text"; try { $mail->isSMTP(); $mail->Host = "somehost.com"; $mail->SMTPAuth = true; $mail->Username = "myemailaddress@someproviderdomain.com"; //Password to use for SMTP authentication $mail->Password = "YOUR PASSWORD"; $mail->SMTPSecure = 'tls'; $mail->Port = 587; //smtp port $mail->SMTPDebug = 2; $mail->setFrom('myemailaddress@someproviderdomain.com', 'Your Name'); $mail->addAddress('toemailaddress@someootherdomain.com', 'Recepient Name'); $mail->isHTML(true); $mail->Subject = $subject; $mail->Body = $body; $mail->send(); echo 'Message has been sent'; } catch (Exception $e) { echo 'Message could not be sent. Mailer Error: '. $mail->ErrorInfo; } ?>
Note that you will need to change the following entries to match your own provider (or you can use one of the major email services such as Outlook.com, Hotmail.com, and/or Gmail.com.
- $mail->Host = “somehost.com”;
- $mail->Port = 587;
- $mail->setFrom(‘fromemailaddress@somedomain.com’, ‘Your Name’);
- $mail->addAddress(‘toemailaddress@someootherdomain.com’, ‘Recepient Name’);
- $mail->Username = “myusername@someproviderdomain.com”;
- $mail->Password = “YOUR PASSWORD”;
For example. to make the script work with your outlook.com or hotmail.com email address simply use the smtp.live.com as your host and update the username and password properties. Furthermore, you will want to change the content of $subject and $body variables to your liking.
Running the Script
Once you are done with those changes, to send an email run the script as follows:
php sendemail.php
There you have it! If you are on a Mac, the script should work with little or no adjustments. If you get errors and you are using one of the big email providers you may need to enable special programmatic access to get it to work.
Happy programming.