Home arrow PHP arrow Page 4 - Sending Email with PHP Networking

Code Examined - PHP

In this article we will look at the protocol that is involved in sending email messages. We will also examine the thorny issue of how to send an attachment with an email message. This article is the second of two parts.

TABLE OF CONTENTS:
  1. Sending Email with PHP Networking
  2. Sending mail with PHP
  3. Application Code
  4. Code Examined
  5. Sending Mail using the PEAR::Mail
By: David Web
Rating: starstarstarstarstar / 3
September 15, 2008

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Let's take a look at the code. First we check to see if the form was submitted:


<?

//is form submitted

if(isset($_POST['key'])){


 

Then we collect the form data and store it in shorter variables:


//collect the information

$from=$email;

$cc=$_POST['cc'];

$bcc=$_POST['bcc'];


 

The next step is to filter the data and set the error message for each of the required fields:


if(empty($_POST['tos'])){

$error=true;

}else{

$to=$_POST['tos'];

}

if(empty($_POST['sub'])){

$error=true;

}else{

$subject=$_POST['sub'];

}

if(empty($_POST['msg'])){

$error=true;

}else{

$msg=$_POST['msg'];

}



Finally we test to see if the user wants to send an attachment. The attachment is sent through the $_FILES[''] array. If the file is loaded, we set the headers for the mail function. Notice that the content-disposition and content-transfer-encoding has also been set:


//check if the an attachment is present

if(isset($_FILES['userfile']['name'])){

$attachment = $_FILES['userfile']['tmp_name'], $_FILES['userfile']['name'];

$headers ="Content-disposition: attachment;

$filename=.$attachment."n";

$headers=.Content-Transfer-Encoding: base64n";

}




If there are no errors, the code continues to send the email message with or without the headers:


if(!$error){

if($headers <> ""){

$res=mail($to,$subject,$msg,$headers);

}else{

$res=mail($to,$subject,$msg);

}

}



Finally, an error check is made to inform the user if any errors occurred.



if(!$res){

echo "Mail error occurred";

}

}


?>




 
 
>>> More PHP Articles          >>> More By David Web
 

blog comments powered by Disqus
   

PHP ARTICLES

- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...
- PHP: Building Concrete Validators
- Sanitizing Input with PHP
- Executing Shell Commands with PHP
- Handling File Data with PHP
- File Security and Resources with PHP
- ArrayObject PHP Class Examples
- ArrayObject PHP Class: An Introduction
- Getting File System Data with PHP
- PHP Tools for Working with the File and Oper...
- Working with the File and Operating System w...
- PHP Proxy Patterns: Completing a Blog


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 6 - Follow our Sitemap

Dev Shed Tutorial Topics: