A newsletter is a printed or electronic report containing news concerning the activities of a business or an organization that is sent to its members, customers, employees or subscribers. Newsletters generally contain one main topic of interest to its recipients. In this article, we will discuss you how can send bulk emails using the PHP Mailer library.
Newsletter
Newsletters in websites are used in the form of E-mails and they are the most common type of emails in email marketing. They often contain news and updates, aiming to keep the audience engaged. At the same time, they are also designed to gently push users towards the conversion.
We are going to create a form that will help users to subscribe to the newsletter on your website and you will be able to send bulk emails to all those users. You can send promotional emails to promote your product or you can mail to them whenever you have a new post or news regarding your business, organization or website.
<form onsubmit="return doSubscribe();">
<input type="email" id="subscriberEmail" placeholder="Subscribe to newsletter" required>
<input type="submit" value="Subscribe">
<p id="subscribe-message"></p>
</form>
This will create a form with an input field to type email and a submit button which when clicked will submit the form. We are preventing the default behavior of form submission by attaching an event listener called “onsubmit”. This function will be called when the user hits the submit button. We need to prevent the form from submitting and call our AJAX function to save this email in the MySQL database using PHP. At the end we have a paragraph, it will be used to display a message when the email has successfully been stored in the database.
Send an ajax request
<script type="text/javascript">
function doSubscribe() {
var subscriberEmail = document.getElementById("subscriberEmail").value;
var ajax = new XMLHttpRequest();
ajax.open("POST", "subscribe-newsletter.php", true);
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("subscribe-message").innerHTML = "You have been subscribed to our newsletter.";
}
};
ajax.send("subscriberEmail=" + subscriberEmail);
return false;
}
</script>
Here first we have created a Javascript function and we are returning false from it, this will prevent the form from submitting. We are getting the input field value for email using the input field’s unique ID. Then we have created an AJAX object that can be used to send an asynchronous AJAX request. Next, we are calling open function and setting method to “POST”, the second parameter is the name of the file where data needs to be sent and the third parameter is whether the request is asynchronous.
Asynchronous
All modern browsers support asynchronous, so we are setting this to true. As the request is POST, so we also have to attach headers to this request. For application/x-www-form-urlencoded, the body of the HTTP message sent to the server is essentially one giant query string — name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=).
Before actually sending the request, we are attaching an event listener which will be called when a response is successfully been received from the server. The request is successful if the readyState is 4 and status has a value of 200. When the request is completed, we are simply displaying a message in the paragraph so the user can know that his email has been added in the subscriber’s list.
Save email in MySQL using PHP
Next, we need to create a PHP file that will store this email in MySQL database. First, create a table in your MySQL database and name it “subscribers”. It will have 1 column as auto-increment primary key whose value be unique for each subscriber and its data type should be an integer. It will also have another column for email whose value will be subscriber’s email and its data type should be text.
Save data in MySQL database
Create a new file named “subscribe-newsletter.php” and paste the following code in it. Make sure to change the database credentials as per your database.
<?php
$conn = mysqli_connect("localhost:8889", "root", "root", "tutorials");
$subscriberEmail = $_POST["subscriberEmail"];
mysqli_query($conn, "INSERT INTO subscribers (email) VALUES ('$subscriberEmail')");
?>
Send bulk emails using PHP Mailer
Many PHP developers need to send email from their code. The only PHP function that supports this is mail(). However, it does not provide any assistance for making use of popular features such as encryption, authentication, HTML messages, and attachments.
The PHP mail() function usually sends via a local mail server, typically fronted by a Sendmail binary on Linux, BSD, and macOS platforms, however, Windows usually doesn’t include a local mail server; PHPMailer’s integrated SMTP implementation allows email sending on Windows platforms without a local mail server.
Install PHPMailer
Open command prompt (Windows) or Terminal (Mac OS) in your project’s root folder and run the following command:
composer require phpmailer/phpmailer
It will install the PHPMailer library in your project. You will see a folder named “vendor” will be created at the root folder of your project. Open the file from where you want to send emails to all your subscribers. And paste the following code in it:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$conn = mysqli_connect("localhost:8889", "root", "root", "tutorials");
$result = mysqli_query($conn, "SELECT * FROM subscribers");
while ($row = mysqli_fetch_object($result))
{
$mail = new PHPMailer(true);
try {
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'adnan@gmail.com';
$mail->Password = '';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
$mail->setFrom('adnan@gmail.com', 'Adnan');
$mail->addAddress($row->email); // Add a recipient
$mail->addReplyTo('adnan@gmail.com', 'Adnan');
// Content
$mail->isHTML(true);
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();
echo '<p>Message has been sent to ' . $row->email . '</p>';
} catch (Exception $e) {
echo "<p>Message could not be sent. Mailer Error: {$mail->ErrorInfo}</p>";
}
}
Here first we are importing PHPMailer library files. Then we are including our “autoload.php” file, it should be automatically created when the composer command is executed. Then we are connecting with the database and fetching all the subscribers from the table. In each loop iteration, we are creating an object of PHPMailer class. Setting the host as Gmail and username and password as one of our Gmail account’s credentials. You need to enter the correct email and password of one of your Gmail account.
Enable google less secure apps
Make sure to enable “less secure apps” for your corresponding Gmail account. You can do that from this link or by tapping the screenshot below.
Set the port number to “587” it is the default for Gmail. Set your email address from where the email should be sent. And the recipient address which we will be receiving from the database. Then we are setting the subject and body of email, the body of the email can contain HTML content. But you can also specify non-HTML content in “AltBody” if the user switches to simple text format. Or if the user has a slow internet connection. Finally, we send the mail and display a confirmation message that an email has been sent. If there is any error, it will be handled in the catch block. We are also displaying an error message if there is any problem in sending en E-mail.
Apply CSS on form
Although your subscription form design will be different for everyone else as per your website’s existing design. But for the sake of simplicity, we are applying some CSS styles just to make it look a little bit good. First, change your form layout and enclose your input field and submit button inside div tag having class as “container”. We will apply styles based on this class.
<form onsubmit="return doSubscribe();">
<div class="container">
<h2>Subscribe to our Newsletter</h2>
<p>Lorem ipsum..</p>
</div>
<div class="container" style="background-color:white">
<input type="email" id="subscriberEmail" placeholder="Subscribe to newsletter" required>
</div>
<div class="container">
<input type="submit" value="Subscribe">
</div>
<p id="subscribe-message"></p>
</form>
Next we are going to use the CSS to apply styles on those divs and classes.
<style type="text/css">
/* Style the form element with a border around it */
form {
border: 4px solid #f1f1f1;
}
/* Add some padding and a grey background color to containers */
.container {
padding: 20px;
background-color: #f1f1f1;
}
/* Style the input elements and the submit button */
input[type=text], input[type=email], input[type=submit] {
width: 100%;
padding: 12px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
/* Add margins to the checkbox */
input[type=checkbox] {
margin-top: 16px;
}
/* Style the submit button */
input[type=submit] {
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
input[type=submit]:hover {
opacity: 0.8;
}
</style>
Now you have learned how you can send bulk emails using PHP Mailer library. You can also learn how to send email with attachments in PHP from here.