Do It Yourself Email Autoresponder

In this blog post I am going to try to show you how to build your own Email Autoresponder, sort of like Mailchimp or Aweber but very simple.

By the end of this post we will build something that will allow a user to sign up to a newsletter. The user will then get a follow up email every so often (an amount of time that we specify) until they have received a certain amount of emails (that we specify) or the user has unsubscribed (which they can do with one click). We will put every security feature into the code that I know of to keep out any would be hackers.

**Disclaimer**
Before we go any further I would like to really stress one very important point. The security that we put into the code is only half of the battle, the other half is the emails that you send out and their content. Email is very complex and should be taken very seriously. So many things that you might not even realize can get your email marked as spam and you can get blacklisted without warning, and if this happens, all of the email you send will go into junk folders and never get opened. Any business that you hoped to get through email will be lost, and it will be very hard to get it back.

I strongly recommend Aweber for you email needs. Besides doing the autoresponder thing, they also allow you to create and A/B test forms, they have very informative and comprehensive stats, very robust email editors, and most importantly they tell you how safe your email is, keeping you off of any blacklists and the mail you send goes to the recipients main mailbox (not the spam folder, or the promotions tab,etc.).

I would only use the code that we are going to go over here for learning reasons, or because you really, really know what you are doing when it comes to sending email (especially large amounts of email) and are confident that you will not get blacklisted.

If I didn’t scare you off yet then I think we can finally get started!


The Sign Up or Opt In Form

The first thing that you will need to do is go read and follow my blog post called “Forms pt1”, this is an introductions to forms but will give us everything we need to get started. When finished a user will be able to sign up (called opt-in) to our newsletter and their name and email address will be stored in a database that we create.

Forms pt1

PHPMailer

Once we are finished with Forms pt1 we should have a working form and database. It is time to start working on the email part of the problem. Because email is so complex we are going to go third party and use something called PHPMail instead of using the PHP mail() function to make sure that our email is properly formatted and will not look like spam to Google, Yahoo, etc.

PHPMail does take a bit of a set-up, you will thank me for after you hate me.

Please read my step by step guide to install PHPMailer to your shared host: Install PHPMailer

Once you have done that you will have been able to send a email using PHPMailer and the next step is easy.

Thank You Message and New Subscriber Alert

We will use PHPMailer to automatically send a Thank You message when someone signs up, and we will also send ourselves a message to let us know that someone has signed up.

We are going to create a file called “mail-function.php“. Simply make a copy of the “mailtest.php” file and rename the new file “mail-function.php“.

We will need to change a few lines of code in the “mail-function.php” file.

We will change the part where it says:
$mail->addAddress('to@example.com', 'Joe User');
to say:
$mail->addAddress($toemail, $toname);

We will change the part where it says:
$mail->Subject = 'Here is the subject';
to say:
$mail->Subject = $subject;

We will change the part where it says:
$mail->Body = 'This is the HTML message body in bold!';
to say:
$mail->Body = $body;

We will change the part where it says:
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
to say:
$mail->AltBody = $altbody;

Save that and load it to your host.

You can get the code here: Mail Function

mail-function.php” is now our basic template for sending email and all we need to do to implement it is use this code and change the values to suit your needs:

$toemail = $email; //email you are sending to
$toname = $name; // name of the person you are sending to
$subject = 'Welcome'; // subject of your email
$body = 'Thank you for signing up.'; // html body of your email
$altbody = 'Thank you for signing up.'; //text body of your email
require 'mail-function.php';

The rest of the values in the “mail-function.php” file will usually stay the same once we have them set. Of course, if you need to change the other values (you want to add attachments or an information email etc.) you would have to make another file (mail-function2.php) and change the value that you need to a variable that you can set elsewhere just like we did with these other values.

OK, We went to send a Thank You message when someone signs up.

To do this we will have to once again open up our “formhandler1.php” file that we created in the Forms pt1 post.

We will change the part where it says:

echo "New records created successfully";

to say:


$toemail = $email; //we set it to send the email to the email the user submitted
$toname = $name; // this is what the user submitted as their name
$subject = 'Welcome'; // for a subject we welcome them to our club
$body = 'Thank you for signing up.'; // this is the thank you message in html
$altbody = 'Thank you for signing up.'; //same message for people with html turned off
require 'mail-function.php';

Save that and load it to your host.

This will automatically send a Thank You email to the email a user submits immediately after entering them into the database

To send ourselves a New User email we just post the same exact code right after the code above and change the values:


$toemail = 'your email'; //we set it to send the email to us
$toname = 'your name'; // our own name
$subject = 'New User'; // subject line will say New User
$body = $email; // I have it set to give me the email of the new sign up
$altbody = $email; //same message
require 'mail-function.php';

Save that and load it to your host.

This will automatically send a New User message to me immediately after sending the Thank You message.

You can get the code for “formhandler1.php” here: Form Handler 1 just un-comment the above code.

This should take care of almost all of your inner-website needs EXCEPT we need to do one more thing.

Add an Unsubscribe Link to your Email.

Because there are many people who could use this information that are not following this tutorial I decided to make it its own post you can read it here and install one click unsubscribe. Simple One Click Unsubscribe

Now that you have completed that you should make sure you always put that unsubscribe link in every email that you send (along with your street address or P.O.box) and also make sure that when someone unsubscribes you never send them another email.


Part 2

Now that you are collecting emails and have thanked everyone for joining there are generally two things that you are going to want to do.

The first thing you might want to do is send an email to everyone (because there is a big sale, it’s a holiday, the site will be down, etc.). This is called an “Email Blast”.

The second thing we will want to do is to send pre-written messages automatically every so often (once a day, once a week, once a month etc.) until a specific end (a user signs up and gets a short story every week, a user signs up for 10 secrets to weight loss and gets one secret per day, etc). This is called an “Email Campaign”.

Email Blast

To create an Email Blast we will first need to create a new file called “countsubscribers.php“, and what this file will do is count how many subscribers there are in the database and then go “down the list” subscriber by subscriber printing out the name and email of each. The code will look like this: get it here Count Subscribers

require 'database.php'; //connection to database
//select subscribed users
$sql= "SELECT name, email FROM yourTable WHERE subscribe = 0";
$stmt = $db->prepare($sql);
$stmt->execute();
//count number of users
$total = $stmt->rowCount(); //total number of subscribers
echo '

Number of subscribers:'.$total.'

';
//for each subscriber echo their name and email
while ($row = $stmt->fetchObject()) {
$thisname = $row->name;
$thisemail = $row->email;
echo $thisname.' - ';
echo $thisemail.'
';
}

Now, we will create a file called “blast.php“, and that file will be the same as the “countsubscribers.php” file except that instead of printing out each name and email we will change it to send out an email to that name and email, and all we have to do is add the code we used in the “mail-function.php” file. The code will look like this: you can get it here: Blast

require 'database.php'; //connection to database

// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

//Load composer's autoloader
//This needs to be changed to your specific host
require '../../vendor/autoload.php';

//This needed to be changed on mine to what I have here
$mail = new \PHPMailer;

//select subscribed users
$sql= "SELECT name, email FROM yourTable WHERE subscribe = 0";
$stmt = $db->prepare($sql);
$stmt->execute();

//count number of users
$total = $stmt->rowCount(); //total number of subscribers
echo '

Number of subscribers:'.$total.'

';

//for each subscriber echo their name and email
while ($row = $stmt->fetchObject()) {

$toname = $row->name;
$toemail = $row->email;

echo $thisname.' - ';
echo $thisemail.'
';

try {
//Server settings
$mail->SMTPDebug = 2; // Enable verbose debug output - 0 for no output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com'; // Specify main and backup SMTP servers - get this information from your host
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user@example.com'; // SMTP username for the email that you are sending from
$mail->Password = 'secret'; // SMTP password for the email that you are sending from
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted - mine uses ssl
$mail->Port = 587; // TCP port to connect to - get this information from your host

//Recipients
$mail->setFrom('from@example.com', 'Mailer'); //from email and who is sending

$mail->addAddress($toemail, $toname); // Add a recipient

//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AltBody = $altbody;
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
}

Now when you save, upload, and navigate to the “blast.php” file (example: yourdomain.com/blast.php) you will send whatever message you have set to every one of your subscribed users. In practice you probably would set up another page, something like “sendblast.php“, and on that page you would put a form that lets you type in your message and calls “blast.php” when you press submit. I am not going to create that page in this blog post because I feel that you would need some kind of log-in feature so that you had to be logged in to type and send a message. We will create that system with Forms pt.2 that I will write soon but if you know what you are doing you can go ahead and do it. WordPress and other CMS have built in log in systems and you can put the “sendblast.php” on a private page in there and use it safely.

Autorespond

Now all that is left is the auto-send emails. We will create a modified “blast.php” file that will check to see what the last message a subscriber has received and send them the next one until they have them all and we use a Cron Job to run the file when it is time to run it.

First we will need to add a table to our database that we can store our emails in. It should have and id field(integer, primary), subject field(var char length 50), and body field(text). I manually entered 3 messages, the first message I gave an id of 0, the second an id of 1, and the third an id of 2. You can enter the messages into your database however you want and you can add as many as you need.

Now we will create a file called “autorespond.php“. This file will do three main things

First it will access our messages table and retrieve that information and store it in arrays.
Next it will go user by user and see which message they should get next and send it
Finally it will update the database to increase what number email each subscriber has received.

This is what the code looks like you can get it here: Autorespond:

require 'database.php'; //connection to database
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
//Load composer's autoloader
//This needs to be changed to your specific host
require 'autoload.php';
//This needed to be changed on mine to what I have here
$mail = new \PHPMailer;
//use arrays to store all of the subjects and body messages
$subject = array();
$body = array();
$altbody = array();
//get messages from database
$sql= "SELECT id, subject, body, altbody FROM messagesTablename";
$stmt = $db->prepare($sql);
$stmt->execute();
//add each message to the array
while ($row = $stmt->fetchObject()) {
$id = $row->id;
$subject[$id] = $row->subject;
$body[$id] = $row->body;
$altbody[$id] = $row->altbody;
}
//select subscribed users
$sql2= "SELECT name, email, followup FROM subscribersTablename WHERE subscribe = 0";
$stmt2 = $db->prepare($sql2);
$stmt2->execute();
//count number of users
$total = $stmt2->rowCount(); //total number of subscribers
echo '

Number of subscribers:'.$total.'

';
//for each subscriber echo their name and email
while ($row = $stmt2->fetchObject()) {
$toname = $row->name;
$toemail = $row->email;
$followup = $row->followup;
$messagenumber = sizeof($subject);
echo $toname.' - ';
echo $toemail.'
';
echo $messagenumber."
";

// check to see if this user already received the last message
if ($followup < $messagenumber){ // send the email try { //Server settings $mail->SMTPDebug = 2; // Enable verbose debug output - 0 for no output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com'; // Specify main and backup SMTP servers - get this information from your host
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user@example.com'; // SMTP username for the email that you are sending from
$mail->Password = 'secret'; // SMTP password for the email that you are sending from
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted - mine uses ssl
$mail->Port = 587; // TCP port to connect to - get this information from your host

$fromemail = '';
$fromname = '';

$subject = $subject[$followup];
$body = $body[$followup];
$altbody = $altbody[$followup];

//Recipients
$mail->setFrom($fromemail, $fromname); //from email and who is sending

$mail->addAddress($toemail, $toname); // Add a recipient

//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AltBody = $altbody;
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
//update the database followup number
$followup++;
$sql3 = "UPDATE subscribersTablename SET followup = :followup
WHERE email = :email";
$stmt3 = $db->prepare($sql3);

$stmt3->bindParam(':followup', $followup, PDO::PARAM_INT);
$stmt3->bindParam(':email', $toemail, PDO::PARAM_STR);
$stmt3->execute();
}

}

Once you have the “autorespond.php” created and uploaded to your server all that is left is to set a Cron Job to call that file at a specific interval that you set. For me, I just go into my control panel and select Cron Jobs under advanced settings, enter in when I want it to run (once a day, once a month, etc.), and I am FINISHED! I have a working Autoresponder, a person can sign up and will automatically get a new message every day until they get them all.

I ran into 2 problems when setting up my cron job. First, I had to move all of the files from the vendor folder (../../vendor/autoload.php) to the folder where the rest of the files for the autoresponder are. Second, I would have caught the error faster but my error messages were going to my spam folder and I didn’t see them at first. If you are having a problem check there.

Finished

There you have it, if you followed along then you have an Autoresponder. We covered a lot of things. You created two tables in your database, used many of the database commands (update, insert, delete,), created a pretty good form, learned and implemented PHP Mailer, composer, etc. You can use this knowledge to create many things.

Of course I would be happy to build this for you at a very reasonable rate. Send me a message ed@32hertz.com


Go back to Main Blog

twittertwitter
twittertwitter