6
Posted January 29, 2013 by Hunter in PHP Programming
 
 

How to Create a Script to Send Automated Emails via PHP

emailRound
emailRound

 

So you have a ukulele site where you post sheet music and music lesson videos.  You want to encourage a little more interaction with your users, so you whip up a PHP script that allows visitors to upload audio files of themselves, to demonstrate what they’ve learned and how they’ve improved.  But you’re a busy guy / gal, with lots to do, and you can’t go checking your server files all the time only to see that there hasn’t been a new upload.  So you decide to add to your PHP script and have it send you an automated e-mail every time someone uploads to your site.

Let’s jump into the code, looking first at the HTML:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Test Subject X</title>
</head>

<body>
<h2>Submit</h2>
<p style="text-align:justify">Oh, cool!  You want to submit your own recording(s)?  That'd be awesome!  I'd love that.</br></br>
Use the form below to submit a small audio file - you can submit a large file, but that would take a while to upload, and hey, you're an important guy or gal with important things to do. OGG files only, as I like the barbarous sound of the extension.  I myself use <a href="http://media.io">media.io</a> to convert files.  Please also leave a comment to accompany the music, let me know what it's all about.</br></br>

<form name="submitform" action="submitform.php" method="post" enctype="multipart/form-data"> </br>
  Name:</br>
  <input type="text" name="theirname" maxlength="1000" /> </br>
  Quest:</br>
  <input type="text" name="quest" maxlength="1000" /> </br>
  Favorite Color:</br>
  <input type="text" name="favcolor" maxlength="1000"/> </br>
  E-mail:</br>
  <input type="text" name="email" maxlength="1000"/> </br>
  Recording Title:</br>
  <input type="text" name="audioname" maxlength="1000"/> </br>
  Recording</br>
  <input type="file" name="file1" id="file1"/> </br>
  Comments:</br>
  <textarea name="comments" maxlength="10000" cols="35" rows="10"></textarea></br></br>
  <input type="submit" name="sendit" value="Submit" />
</form>
</body>
</html>

I show this so you can see the form, with the various text inputs.  Notice that ‘name’ is an attribute of the input.  This name is what we’ll use in the PHP script to reference the value of that specific input.

Now to the important stuff, the PHP:

<?php

// Stores in variables the e-mail address and the e-mail subject
$email_to = "youremailaddress@yomail.com";
$email_subject = "Submission from Uke Site";

// Called if there is an error, kills the script
function died($error) {
  echo "We require more minerals.  See below.<br /><br />";
  echo $error;
  die();
}

// Checks to see if all the inputs have been put in
if(!isset($_POST['theirname']) ||
  !isset($_POST['favcolor']) ||
  !isset($_POST['email']) ||
  !isset($_POST['audioname'])) {
  died('I need more than that, man.  Fill in all the forms with astricks next to them.');
}

// Re-assigns the inputs' values to new variables, just to make the code read easier later on
$theirname = $_POST['theirname'];
$quest = $_POST['quest'];
$favcolor = $_POST['favcolor'];
$email = $_POST['email'];
$audioname = $_POST['audioname'];
$comments = $_POST['comments'];

$error_message = "";
// This is a regular expression, written in such a way as to represent a valid e-mail
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';

// Checks to see if the email entered by the user is not a valid e-mail
if(!preg_match($email_exp,$email)) {
  $error_message .= 'Ew!  Some of those characters you put in the e-mail input are a little too weird.  Be a little more normal, if you please.<br />';
}

// Regular expression to represent valid entries for name, color, and title
$string_exp = "/^[A-Za-z .'-]+$/";
// Checks to see if the name entry isn't valid
if(!preg_match($string_exp,$theirname)) {
  $error_message .= 'You say your name is what?  Sorry, cannot read that.  Use normal characters.  This is Merica.<br />';
}

// Check to see if the color entry isn't valid
if(!preg_match($string_exp,$favcolor)) {
  $error_message .= 'That is not any color I ever heard of, friend.  Try another one.<br />';
}

// Check to see if the title entry isn't valid
if(!preg_match($string_exp,$audioname)) {
  $error_message .= 'Titles are hard, I know, but at least write legiably when you have them.  I cannot read some of those characters.  Try again.<br />';
}

// If anything was invalid, calls the function died
if(strlen($error_message) > 0) {
  died($error_message);
}

// This function is called below to remove any instances of the elements of the array $bad
function clean_string($string) {
  $bad = array("content-type","bbc:","to:","cc:","href");
  return str_replace($bad,"",$string);
}

// Writes what will be the contents of the e-mail into the variable $email_message
$email_message = "Well, well, well.  What do we have here?  A loyal user uploaded a file!\n\n";
$email_message .= "Name: ".clean_string($theirname)."\n";
$email_message .= "Quest: ".clean_string($quest)."\n";
$email_message .= "Favorite Color: ".clean_string($favcolor)."\n";
$email_message .= "Title: ".clean_string($audioname)."\n\n";
$email_message .= "Comments: ".clean_string($comments)."\n\n\n\n";

// Adds headers to be send in the e-mail.  Not necessary.
$headers = 'From: '.$email."\r\n";

// If there is an error with the file upload, then adds that error message to the e-mail
if ($_FILES["file1"]["error"] > 0) {
  $email_message .= "Return Code: " . $_FILES["file1"]["error"] . "\n";
}

// If there is no error with the file...
else
{
// Adds the file name, type, and size to the e-mail
$email_message .= "Upload: " . $_FILES["file1"]["name"] . "\n";
$email_message .= "Type: " . $_FILES["file1"]["type"] . "\n";
$email_message .= "Size: " . ($_FILES["file1"]["size"] / 1024) . " Kb\n";

  if ($_FILES["file1"]["type"] == "audio/ogg") {
  // If the file uploaded already exists, then add that information to the e-mail and do not save the file on the server
    if (file_exists("upload/" . $_FILES["file1"]["name"])) {
      $email_message .= $_FILES["file1"]["name"] . " already exists. ";
    }
    // If the file does not exist on the server, then save it and add the pathname to the e-mail
    else
    {
      move_uploaded_file($_FILES["file1"]["tmp_name"],
      "upload/" . $_FILES["file1"]["name"]);
      $email_message .= "Stored in: " . "upload/" . $_FILES["file1"]["name"];
    }
  }
  else
  {
    died("Unsupported file type.");
  }
}

// Actually SENDS the e-mail, finally
// The arguments, in order, are:
// Address to which the e-mail is sent, subject of the e-mail, message of the e-mail, and headers (from, reply-to, cc, bcc, that sort of thing)
@mail($email_to, $email_subject, $email_message, $headers);

// Redirect to this html page
header('Location: submited.html');

?>

Okiedokie now, here’s some cool stuff.  This whole big long annoyance is all about the one line,


@mail($email_to, $email_subject, $email_message, $headers);

This line is pretty much just what it seems to be.  It sends an e-mail to the address given as the first argument, with the subject given as the second, message as the third, and, optionally, headers as a fourth.  Since this example is one in which we are sending an e-mail to ourselves, we can just define $email_to in our PHP script as our own address.  The subject, $email_subject, is non-variable, too, so I’ve just defined that right below $email_to at the beginning of the script.  The message is contained in a single variable, which was added to throughout the script with the .= operand.

The body of the e-mail contains information entered by the user into the input boxes.  The PHP syntax for returning the value of an HTML input is $_POST['nameofinput'].  With this you’re able to get varaible e-mails, not just the same one every time that says, “You have an upload,” but rather relevant details to the specific upload.

Here’s an example e-mail sent by this script:

From: Calvin H
Subject: Submission from Uke Site
Well, well, well.  What do we have here?  A loyal user uploaded a file!
Name: Calvin
Quest: Grail
Favorite Color: Blue
Title: Godzilla in Paradise
Comments: This is an adaption of a song you play in one of your lessons.  It was inspired by my pet iguana.
Upload: gip.ogg
Type: audio/ogg
Size: 1627.4521484375 Kb
Stored in: upload/gip.ogg

You could certainly use this same information to send e-mails to other people.  You received the user’s e-mail via the input box, right?  So do this:


$email_to = $_POST['email']

and they’ll get an e-mail.  Perhaps you could include in this script an e-mail that they get that confirms that their submission went through.  We’ve all gotten those before, right?  Well, this is one way of how to make them.


Hunter