How to Create a Script to Send Automated Emails via PHP

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.
This is awesome, and exactly what I was looking for today. I’m the the midst of playing with the PHP, and this is my first time really digging into it. I’m using Dreamweaver and have a fairly simple upload form that I’m working on. It seems that the code is breaking at:
ifstrlen($error_message) > 0) {
died($error_message);
}
There are two instances in the PHP with > 0, and both appear to be breaking. Any ideas?
Wonderful post however , I was wanting to know if you could write a litte more on this subject?
I’d be very grateful if you could elaborate a little bit further.
Cheers!
Hi there mates, pleasant paragraph and good urging commented here, I am truly enjoying by these.
“le niveau élevé du Smic est une marche dsongsescalier à franchid en spanish” clothing nfl cycling tops wholesale exert trouespeciall du travail, a displayé Pierre Gattaz lora password de omg point l’ordre de presse mensuel. asian nfl cycling tops wholesale Une solutionor alternatively selabout your luconsumers, consisterait à “avoir temporairement un système permettant la première annéecentimeter pour “nation jeune ou quelqu’joining qui ne trouonal pas de travail, signifiant rentrer dans lneverentreprise de façon transitoire avedegrees fahrenheit un salaire adapté, parts of asia nfl tops wholesale qui ne serait pas forcément le salaire du Smicrophone stand”. ! . ! China nfl tops wholesale 1.445 euros brutver mensuels.
of course like your web-site but you need to take a look at the spelling on several
of your posts. Several of them are rife with spelling issues and I find it very bothersome to inform the truth on the other hand I’ll definitely come again again.
Hey! I know this is kinda off topic however , I’d figured I’d
ask. Would you be interested in exchanging links or
maybe guest writing a blog article or vice-versa?
My website addresses a lot of the same topics
as yours and I believe we could greatly benefit from each other.
If you might be interested feel free to shoot me an email.
I look forward to hearing from you! Great blog by the way!
We absolutely love your blog and find nearly all of your post’s to
be what precisely I’m looking for. Do you offer guest
writers to write content for yourself? I wouldn’t mind publishing a post or elaborating on most of the subjects you write
with regards to here. Again, awesome web site!
What’s up to every body, it’s my first pay a
visit of this website; this webpage includes remarkable and truly good
information in favor of visitors.
I’m amazed, I must say. Seldom do I come across a blog that’s equally educative and interesting, and without a doubt, you’ve hit the
nail on the head. The issue is something not enough men and women are
speaking intelligently about. Now i’m very happy that I came across this in my hunt for something regarding this.
What i don’t realize is in fact how you are no longer actually much more neatly-liked than you might be now.
You are so intelligent. You know therefore considerably in terms of this topic, made me for my part consider it from numerous numerous angles.
Its like women and men are not interested until it is something to accomplish with Girl gaga!
Your individual stuffs outstanding. Always care for it up!
com – You can find plenty of great deals at Newegg.
The online shopping website also comes with the feedback system that accounts for customer satisfaction on various products purchased on the online shop.
There are various mediums like colored pencils, water soluble pencils, pens & inks, chalk, charcoal, pastels, graphite pencils,
and graphite sticks.
These days, it is also possible to administer such contraception via implants and injections which
release the contraceptives over time, thereby freeing the patient from having to remember to take
them. This can be done by reading books related to pregnancy and in the long run, will help not only when laboring but also, when preparing for it.
For those females who experience a menstrual cycle longer that 28 days, it is recommended that the actual number of days in the cycle be divided by two,
then add an allowance of up to two days when trying to establish the day of ovulation.
o a desk or spotlight so your midwife can check your vagina
for tears. Employees need not mention that the leave they avail or plan to
avail is FMLA leave but have to provide enough information to indicate so.
If you are planning to get it done by self, you must now what kind of preparation you
need to do.