Rating: 8.1/10 (7 votes cast)
PHP Email With Attachment
Sending email with attachment from your website is really a great add on. Usually this is required if you have a contact us page where you need your users to attach any further information or a web page where users can attach files and send etc.,
This is a simple example, All you need is to create a HTML form with all the required entries as below. Let us name the file as mail.html
Next step is to create a PHP file to process the information from the HTML page.
Before we proceed some information regarding the functions and code used in the PHP script.
I have added 4 file types here. You are free to add any number of file types according to your convenience.
If($filetype=="application/octet-stream" or $filetype=="text/plain" or $filetype=="application/msword" or $filetype=="image/jpeg")
ucfirst() function in PHP returns a string with the first character of str capitalized
To avoid email landing in SPAM folder of your mail client include these headers (Not always helpful 🙁). There might be other reasons as well on why your emails land in SPAM . Make sure you modify the emails accordingly.
$headers .= "Reply-To: The Sender < >\r\n"; $headers .= "Return-Path: The Sender < >\r\n"; $headers = "From: Mistonline Demo< >\r\n"; $headers .= "MIME-Version: 1.0\r\n";
Let us name it as success.php and the entire code look like the one below
\r\n"; // Make sure to add your VALID EMAIL ID HERE $headers .= "Return-Path: The Sender < >\r\n"; // Make sure to add your VALID EMAIL ID HERE $headers = "From: Mistonline Demo< >\r\n"; // Make sure to add your VALID EMAIL ID HERE $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: multipart/mixed; "; $headers .= "boundary=".$num."\r\n"; $headers .= "--$num\r\n"; // This two steps to help avoid spam $headers .= "Message-ID: ".$_SERVER["SERVER_NAME"].">\r\n"; $headers .= "X-Mailer: PHP v".phpversion()."\r\n"; // With message $headers .= "Content-Type: text/html; charset=iso-8859-1\r\n"; $headers .= "Content-Transfer-Encoding: 8bit\r\n"; $headers .= "".$message."\n"; $headers .= "--".$num."\n"; // Attachment headers $headers .= "Content-Type:".$filetype." "; $headers .= "name=\"".$filename."\"r\n"; $headers .= "Content-Transfer-Encoding: base64\r\n"; $headers .= "Content-Disposition: attachment; "; $headers .= "filename=\"".$filename."\"\r\n\n"; $headers .= "".$file."\r\n"; $headers .= "--".$num."--"; // SEND MAIL $from = ""; //Include your FROM EMAIL ID HERE mail($to, $subject, $message, $headers); fclose($fp); echo " Attachment has been sent Successfully."; } else {echo "Wrong file format. Mail was not sent."; } ?>
Note: This tutorial has been updated and all issues fixed. Previous submitted Sep 16, 2008. Bugs fixed on May 9, 2016
VN:F
Rating: 8.1/10 (7 votes cast)
PHP Email with attachment , 8.1 out of 10 based on 7 ratingsRecently while working on a free-lance project, a Marriage Website for one of my friend, I happened to create a Guestbook for that website. After which, I decided to write a tutorial on how to create a guestbook in case someone might need it. If you do not know what a guestbook is, in real life a guestbook is basically a diary kept at various places and for various occasions where people can leave their wishes or feedback for any event. In a similar way, an online guestbook is a service, which enables you to allow your visitors to leave comments and feedback for any event or any product, which is visible to the public.
Well, developing a Guestbook is not a difficult task. It is pretty simple if you know what you are required to do! (Basically, for any problem, if you know what you are supposed to do, it’s pretty easy!). Let me “pen down” the basic steps involved in development of a guestbook.
- A user is displayed a form, which he or she must fill out.
- A confirmation message is displayed to the user when the comment is saved in the database.
- A user can browse through all the comments posted till now on the website.
To solve this simple problem, we will make use of PHP and as always, I would be using my favorite text editor, Notepad++. If you don’t use Notepad++, I highly advise you to use it. Read more about it here. Also, we will be required to use a database to store the comments and information about the user. We will use a MySQL Database.
Guestbook in PHP
Let’s get started with the process of building our very own guestbook.
Guestbook Form
In this code, we basically redirect the form to a PHP page on our server named “addcomment.php ” and then we do the main programming part there.
- Create a new HTML page, and in the body tag of the page, add the following code.
- Now, if you want to add a validation check for the name and email fields, add the following JavaScript code to your head tag.
- Then add the following attribute to the form tag. onsubmit="return Validate();"
- The complete Form Tag will now look somewhat like this.
The SQL Part
We now need to create a MySQL table in a database to save our data entered by the user. To do this, we need to run the following query on our MySQL Server. On our server, we had to use phpMyAdmin to create a table in our database.
CREATE TABLE guestbook(id int(5) NOT NULL auto_increment, name varchar(60) NOT NULL default " ", email varchar(60) NOT NULL default " ", message text NOT NULL, Primary key(id));
The PHP Files
Now let’s get creating our PHP files. We need one file which will add the comment to the user and then display a confirmation or error message and one file which will display all the comments stored in our database. First let’s make the addcomment.php file.
- Create a new PHP file and paste the following code in there. Failed to connect to MySQL: " . mysqli_connect_error() .""; } $name=$_POST["name"]; $email=$_POST["email"]; $message=$_POST["message"]; $sql="INSERT INTO guestbook(name,email,message) VALUES("$name","$email","$message")"; if (!mysqli_query($con,$sql)) { die("Error: " . mysqli_error($con)); } else echo "Values Stored in our Database!"; mysqli_close($con); ?>
- Save this file as addcomment.php in the same folder as the above created HTML file.
- Now, again create a new PHP file, which will display the comments and the names of the people to the public. Name this file “guestbook.php “.
- Add the following code to the file.
- Be sure to change the variables (host, username, password, database, and table) in both the above created PHP files.
Well, that’s it. You are ready to fire it up with some CSS and set it live on your website. This was a quick and easy tutorial for beginners. I hope I enabled you to create a Guestbook for your website. Keep subscribed to Slash Coding for more such updates. You can subscribe via RSS Feeds, Liking our Facebook Page or by Following us on Twitter. It’s your pick! 😉
Did you enjoy this article?
PHP guestbook tutorial. Today I prepared new interesting tutorial – I will tell how you can create ajax PHP guestbook with own unique design. Our records will be saved into SQL database. This table will contain next info: name of sender, email, guestbook record, date-time of record and IP of sender. Of course, we will use jQuery too (to make it Ajax). One of important features will spam protection (we can post no more than one record every 10 minutes)!
Now – download the source files and lets start coding !
Step 1. SQL
We need to add one table to our database (to store our records):
CREATE TABLE IF NOT EXISTS `s178_guestbook` (`id` int(10) unsigned NOT NULL auto_increment, `name` varchar(255) default "", `email` varchar(255) default "", `description` varchar(255) default "", `when` int(11) NOT NULL default "0", `ip` varchar(20) default NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Step 2. PHP
Here are source code of our main file:
guestbook.php
=") == 1) error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED); else error_reporting(E_ALL & ~E_NOTICE); require_once("classes/CMySQL.php"); // including service class to work with database // get visitor IP function getVisitorIP() { $ip = "0.0.0.0"; if((isset($_SERVER["HTTP_X_FORWARDED_FOR"])) && (!empty($_SERVER["HTTP_X_FORWARDED_FOR"]))) { $ip = $_SERVER["HTTP_X_FORWARDED_FOR"]; } elseif((isset($_SERVER["HTTP_CLIENT_IP"])) && (!empty($_SERVER["HTTP_CLIENT_IP"]))) { $ip = explode(".",$_SERVER["HTTP_CLIENT_IP"]); $ip = $ip.".".$ip.".".$ip.".".$ip; } elseif((!isset($_SERVER["HTTP_X_FORWARDED_FOR"])) || (empty($_SERVER["HTTP_X_FORWARDED_FOR"]))) { if ((!isset($_SERVER["HTTP_CLIENT_IP"])) && (empty($_SERVER["HTTP_CLIENT_IP"]))) { $ip = $_SERVER["REMOTE_ADDR"]; } } return $ip; } // get last guestbook records function getLastRecords($iLimit = 3) { $sRecords = ""; $aRecords = $GLOBALS["MySQL"]->getAll("SELECT * FROM `s178_guestbook` ORDER BY `id` DESC LIMIT {$iLimit}"); foreach ($aRecords as $i => $aInfo) { $sWhen = date("F j, Y H:i", $aInfo["when"]); $sRecords .= <<Record from {$aInfo["name"]} ({$sWhen}):
{$aInfo["description"]}