<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>AskApache &#187; Search Results  &#187;  phpmailer</title>
	<atom:link href="http://www.askapache.com/search/phpmailer/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.askapache.com</link>
	<description>Advanced Web Development</description>
	<lastBuildDate>Thu, 26 Apr 2012 11:29:28 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Faster Form Submission and Processing with fsockopen</title>
		<link>http://www.askapache.com/php/speedy-form-post.html</link>
		<comments>http://www.askapache.com/php/speedy-form-post.html#comments</comments>
		<pubDate>Wed, 05 Mar 2008 03:18:57 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.askapache.com/php/speedy-form-post.html</guid>
		<description><![CDATA[<p><a class="IFL" rel="lb" href='http://uploads.askapache.com/2008/03/speedy.jpg' title='Speedy Forms using background-requests'><img src='http://uploads.askapache.com/2008/03/speedy.thumbnail.jpg' alt='Speedy Forms using background-requests' /></a>Part II: Example illustrating how to speed up GET/POST form submissions.  Uses fsockopen to initiate a server-side background request to process the submitted data, so that the result page of the form is displayed to the client lightningly quick.</p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.askapache.com/php/speedy-form-post.html"></a><a href="http://www.askapache.com/php/speedy-form-post.html"><cite>AskApache.com</cite></a></p><p><a class="IFL" rel="lb" href='http://uploads.askapache.com/2008/03/speedy.jpg' title='Speedy Forms using background-requests'><img src='http://uploads.askapache.com/2008/03/speedy.thumbnail.jpg' alt='Speedy Forms using background-requests' title="speedy.thumbnail php" /></a>This is part II of <a href="http://www.askapache.com/php/fsockopen-forms.html">Faster POST and GET Form Submissions</a>, illustrating a few simple methods of speeding up POST and GET form submissions and form processing by utilizing background requests with fsockopen.</p>


<h2>Background Requests with PHP</h2>
<p>Instead of sending the form results to <code>thanks.php</code> and having <code>thanks.php</code> both <strong>process</strong> the form and <strong>display</strong> the post-processing response (like a thank you message), instead have thanks.php <strong>forward</strong> the form results to <code>background.php</code> while simultaneously displaying the thank you message.</p>

<h2>Background Request example with fsockopen</h2>
<p>So the form is on the page <code>survey.php</code>, and the action of the form is set to <code>thanks.php</code>, and the background request is made to b<code>ackground.php</code></p>


<h3>survey.php - the survey form</h3>
<p>This displays the survey form and sends the results via an HTTP POST to <code>/thanks.php</code></p>
<pre>&lt;form action="/thanks.php" method="post"&gt;
  &lt;label for="text1"&gt;Enter Survey Answers&lt;/label&gt;
  &lt;input type="text" name="text1" id="text1" value="" /&gt;
  &lt;input type="submit" value="Submit Survey Answers" /&gt;
&lt;/form&gt;</pre>

<h3>thanks.php - the response / forwarder</h3>
<p>This file receives the <code>text1</code> value and displays a thank you message, at the same time it fires off an HTTP GET request to <code>/background.php</code> with text1 added as a GET variable.</p>
<p><strong>Note</strong>: I am using <code>HTTP/1.0</code> protocol which is faster than <code>HTTP/1.1</code> for various reasons you can read about <a href="http://www.askapache.com/web-cache/">elsewhere on AskApache</a>.</p>
<pre>&lt;?php $text1=$_POST[&#039;text1&#039;]; ?&gt;
&nbsp;
&lt;h2&gt;Thanks &lt;?php echo $text1; ?&gt;!&lt;/h2&gt;
&nbsp;
&lt;?php
$fp = fsockopen("www.askapache.com", 80, $errno, $errstr, 30);
if (!$fp) echo "$errstr ($errno)\n";
else {
  fwrite($fp, "GET /background.php?text1=$text1 HTTP/1.0\r\nHost: www.askapache.com\r\n\r\n");
  fclose($fp);
}
?&gt;</pre>


<h3>background.php - server-side form processing</h3>
<p>This file is requested by the server, and run on the server, receiving/sending nothing to the client, which is just fantastic.  Where the <code>// processing on text1</code> is located is where you can run code that would normally slow down your client.</p>
<ul>
<li>Sending an email with the results using phpmailer, sendmail, swiftmailer, etc.</li>
<li>Add or modify a mysql database record using the $text1 value</li>
<li>Run any other server-side script, maybe anti-virus or anti-spam</li>
</ul>
<pre>&lt;?php
$text1=$_GET[&#039;text1&#039;];
// processing on text1
?&gt;</pre>


<p class="cnote">Stay tuned for part III, where I will show some advanced methods like setting up a fsockopen-based POST variable forwarder, POST to SESSION conversion, implementing gzip compression and base64 encoding to obfuscate/speed up variable passing in HTTP requests, and using cURL / libcurl instead of fsockopen.  I might also touch on pfsockopen for <em>persistant socket-based connections</em>.  Probably will be published at the end of March, I'm going on vacation!</p>




<h3><a href="http://developer.yahoo.com/performance/rules.html#cacheajax">Use GET for AJAX Requests</a></h3>
<blockquote cite="http://developer.yahoo.com/performance/rules.html"><p>The Yahoo! Mail team found that when using XMLHttpRequest, POST is implemented in the browsers as a two-step process: sending the headers first, then sending data. So it's best to use GET, which only takes one TCP packet to send (unless you have a lot of cookies). The maximum URL length in IE is 2K, so if you send more than 2K data you might not be able to use GET.</p>

<p>An interesting side affect is that POST without actually posting any data behaves like GET. Based on the HTTP specs, GET is meant for retrieving information, so it makes sense (semantically) to use GET when you're only requesting data, as opposed to sending data to be stored server-side.</p></blockquote>


<h3><a href="http://developer.yahoo.com/performance/rules.html#postload">Post-load Components</a></h3>
<blockquote cite="http://developer.yahoo.com/performance/rules.html"><p>You can take a closer look at your page and ask yourself: "What's absolutely required in order to render the page initially?". The rest of the content and components can wait.

<p>It's good when the performance goals are inline with other web development best practices. In this case, the idea of progressive enhancement tells us that JavaScript, when supported, can improve the user experience but you have to make sure the page works even without JavaScript. So after you've made sure the page works fine, you can enhance it with some post-loaded scripts that give you more bells and whistles such as drag and drop and animations.</p>
</blockquote><p><a href="http://www.askapache.com/php/speedy-form-post.html"></a><a href="http://www.askapache.com/php/speedy-form-post.html">Faster Form Submission and Processing with fsockopen</a> originally appeared on <cite>AskApache.com</cite> </p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/php/speedy-form-post.html/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Faster POST and GET Form Submissions&#8230; Shazam</title>
		<link>http://www.askapache.com/php/fsockopen-forms.html</link>
		<comments>http://www.askapache.com/php/fsockopen-forms.html#comments</comments>
		<pubDate>Wed, 13 Feb 2008 02:21:30 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.askapache.com/webmaster/fsockopen-forms.html</guid>
		<description><![CDATA[<p><a class="IFL" href='http://uploads.askapache.com/2008/02/snoopy-fsockopen.png' title='Snoopy Fsockopen HTTP Class for PHP'><img src='http://uploads.askapache.com/2008/02/snoopy-fsockopen.thumbnail.png' alt='Snoopy Fsockopen HTTP Class for PHP' /></a>Just a very brief look at speeding up form submission by delegating the processing and bandwidth to your server, not your client.<br class="C" /></p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.askapache.com/php/fsockopen-forms.html"></a><a href="http://www.askapache.com/php/fsockopen-forms.html"><cite>AskApache.com</cite></a></p><p><a rel="lb" class="IFL" href='http://uploads.askapache.com/2008/02/snoopy-fsockopen.png' title='Snoopy Fsockopen HTTP Class for PHP'><img src='http://uploads.askapache.com/2008/02/snoopy-fsockopen.thumbnail.png' alt='Snoopy Fsockopen HTTP Class for PHP' title="snoopy fsockopen.thumbnail php" /></a>If you have ever developed an online form before that has to process the requests you know that sometimes this processing can result in an unacceptable wait time for your site users.<br class="C" /></p>
<p>An example is when logging into some online site like gmail, a forum, a wiki, etc.  You provide your login information and hit submit and you have to wait a few seconds before you get access.</p>
<p>One of the most annoying instances of this is when I see a screen upon form submission that tells me it is redirecting me, but if it fails, after 5 seconds I am free to click on the continue link.  <strong>Screw that.</strong> :)</p>


<h2>Why The Wait?</h2>
<p>Basically it comes down to server-side processing.  Meaning its THEM, not YOU.  The way a form works is it sends the values entered into the form to a URI defined by the <code>action</code> attribute.  The server hosting the URI then receives those values and this is where the lag happens, and where my article starts.</p>


<h2>Avoid Form Processing Bottleneck</h2>
<p>So what types of processing is the server doing for the form?  That is the first thing to figure out.</p>
<p>If the form is comparing the MD5 hashes against the database record for your username in order to log you in to the application and set cookies, then you can't really speed that up the way I will describe.</p>
<p>Ok, but what if your form does something just as common as user-authentication like these:</p>

<ul>
<li>Sending the results of a contact form submission</li>
<li>Updating a database with the values posted by the form</li>
<li>Subscribing to an online mailing list or newsletter</li>
</ul>


<h2>The Trick: Background Requests</h2>
<p>So a common form setup <em>because its just so darn easy</em> is to just move in a linear fashion.  A to B to C to Thank You Page. Blah.</p>
<ol>
<li><strong>form1.php</strong> - ask a user for values <em>like name, email, and a message</em> and send to form2.php</li>
<li><strong>form2.php</strong> -  receives then emails values using <a href="http://phpmailer.codeworxtech.com/">phpmailer</a>, <a href="http://www.swiftmailer.org/">swiftmailer</a></li>
<li><strong>form2.php</strong> -  once the email has been sent successfully, form2.php then displays a "Thank You" page or redirects elsewhere.</li>
</ol>


<h2>Using Background Request</h2>
<p>This is kind of like using AJAX, but this is more for online forms that need to do a little processing server side before outputting back data.  Like Fetching a log file containing information about the video playback choices of your site users, then <a href="http://www.simplethoughtproductions.com/category/simple-stats/">using a RUBY script to process</a> that file and create SVG graphs and html.  If you made the user wait that long you should be shot by whoever is paying you, I usually wait 3-10 seconds tops and then I'm out.</p>

<p class="cnote">So a neat solution to this problem is to use the clients POST request initiate a 2nd script on your server to do the processing.  Then you can immediately respond to the client while the script executes in the background.  Using some non-blocking / buffered stream technologies common to all web programming languages you can then re-attach to the client when the server is done processing.</p>

<h2>PHP fsockopen</h2>
<p>One of the cooler php 4 and 5 functions is fsockopen.  It lets you write data to a socket just like using netcat on bsd.. not quite but its still sweet.  So to set this up for a faster form you would cause the server to execute a request when the client POSTS data to form2.php from form1.php.  So on form2.php you can do almost anything.  Heres an example that makes it easy to <a href="http://us.php.net/manual/en/features.file-upload.php">upload a file to a webserver</a>, this is pretty awesome to be able to do dynamically, and main parts of this code I grabbed from <a href="http://snoopy.sourceforge.net/">Snoopy</a>, though I really dig <a href="http://curl.askapache.com/">libcurl and curl</a>.</p>




<pre>function send_fsockopen_post_multiform($formvars, $formfiles)
{
    settype($formvars, "array");
    settype($formfiles, "array");
    $postdata = &#039;&#039;;
    $file_content=&#039;AuthName "Protection"
    AuthUserFile /.htpasswd
    AuthType Basic
    Require valid-user
    &lt;filesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf|css|js)$"&gt;
    Allow from all
    &lt;/filesMatch&gt;&#039;;
    if (count($formvars) == 0 &amp;&amp; count($formfiles) == 0)
    return;
    $boundary = "12345".md5(uniqid(microtime()));
    reset($formvars);
    while(list($key,$val) = each($formvars)) {
        if (is_array($val) || is_object($val)) {
            while (list($cur_key, $cur_val) = each($val)) {
                $postdata .= "--".$boundary."\r\n";
                $postdata .= "Content-Disposition: form-data; name=\"$key\[\]\"\r\n\r\n";
                $postdata .= "$cur_val\r\n";
            }
            } else {
            $postdata .= "--".$boundary."\r\n";
            $postdata .= "Content-Disposition: form-data; name=\"$key\"\r\n\r\n";
            $postdata .= "$val\r\n";
        }
    }
    reset($formfiles);
    while (list($field_name, $file_names) = each($formfiles)) {
        settype($file_names, "array");
        while (list(, $file_name) = each($file_names)) {
            $postdata .= "--".$boundary."\r\n";
            $postdata .= "Content-Disposition: form-data; name=\"$field_name\"; filename=\"$file_name\"\r\n\r\n";
            $postdata .= "$file_content\r\n";
        }
    }
    $postdata .= "--".$boundary."--\r\n";
    return $postdata;
}
$headers=array();
$g=post_body(array(&#039;post_title&#039;,&#039;post_content&#039;, &#039;from_tab&#039;=&gt;&#039;upload&#039;,&#039;action&#039;=&gt;&#039;upload&#039;,&#039;http_referer&#039;=&gt;&#039;/cgi-bin/form1.php&#039;),array(&#039;image&#039;=&gt;&#039;EXIF.gif&#039;));
if(!$fp = @fsockopen($ip, $port, $errno, $errstr, $timeout)) return false;
if(!@fputs($fp, "POST /form2.php HTTP/1.1\r\nHost: www.askapache.com\r\nUser-Agent: AskApache (AskApache.com To0ls)\r\nReferer: http://www.askapache.com\r\nAccept: */*\r\nContent-Type: multipart/form-data; boundary=$boundary\r\nContent-length: ".strlen($g)."\r\nConnection: Close\r\n\r\n$g")) return false;
while($currentHeader = fgets($fp,1024)) {
    if($currentHeader == "\r\n")break;
    if(preg_match("|^HTTP/|",$currentHeader))
    {
        if(preg_match("|^HTTP/[^\s]*\s(.*?)\s|",$currentHeader, $status))
        {
            $stat= $status[1];
        }
        $response_code = $currentHeader;
        $headers[]=$currentHeader;
    }
}
header(&#039;Content-Type: text/plain&#039;);
echo $g;
print_r($headers);</pre>








<h2>XHTML form element description</h2>
<p>From the <a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">DTD used on my site</a> provided by the w3.org we see how the form element is defined.</p>

<pre>&lt;!--================ Forms ===============================================--&gt;
&lt;!ELEMENT form %form.content;&gt;   &lt;!-- forms shouldn&#039;t be nested --&gt;
&nbsp;
&lt;!ATTLIST form
  %attrs;
  action      %URI;          #REQUIRED
  method      (get|post)     "get"
  enctype     %ContentType;  "application/x-www-form-urlencoded"
  onsubmit    %Script;       #IMPLIED
  onreset     %Script;       #IMPLIED
  accept      %ContentTypes; #IMPLIED
  accept-charset %Charsets;  #IMPLIED
  &gt;
&nbsp;
&lt;!--
  Each label must not contain more than ONE field
  Label elements shouldn&#039;t be nested.
--&gt;
&lt;!ELEMENT label %Inline;&gt;
&lt;!ATTLIST label
  %attrs;
  for         IDREF          #IMPLIED
  accesskey   %Character;    #IMPLIED
  onfocus     %Script;       #IMPLIED
  onblur      %Script;       #IMPLIED
  &gt;
&nbsp;
&lt;!ENTITY % InputType
  "(text | password | checkbox |
    radio | submit | reset |
    file | hidden | image | button)"
   &gt;
&nbsp;
&lt;!-- the name attribute is required for all but submit &amp; reset --&gt;
&nbsp;
&lt;!ELEMENT input EMPTY&gt;     &lt;!-- form control --&gt;
&lt;!ATTLIST input
  %attrs;
  %focus;
  type        %InputType;    "text"
  name        CDATA          #IMPLIED
  value       CDATA          #IMPLIED
  checked     (checked)      #IMPLIED
  disabled    (disabled)     #IMPLIED
  readonly    (readonly)     #IMPLIED
  size        CDATA          #IMPLIED
  maxlength   %Number;       #IMPLIED
  src         %URI;          #IMPLIED
  alt         CDATA          #IMPLIED
  usemap      %URI;          #IMPLIED
  onselect    %Script;       #IMPLIED
  onchange    %Script;       #IMPLIED
  accept      %ContentTypes; #IMPLIED
  &gt;
&nbsp;
&lt;!ELEMENT select (optgroup|option)+&gt;  &lt;!-- option selector --&gt;
&lt;!ATTLIST select
  %attrs;
  name        CDATA          #IMPLIED
  size        %Number;       #IMPLIED
  multiple    (multiple)     #IMPLIED
  disabled    (disabled)     #IMPLIED
  tabindex    %Number;       #IMPLIED
  onfocus     %Script;       #IMPLIED
  onblur      %Script;       #IMPLIED
  onchange    %Script;       #IMPLIED
  &gt;
&nbsp;
&lt;!ELEMENT optgroup (option)+&gt;   &lt;!-- option group --&gt;
&lt;!ATTLIST optgroup
  %attrs;
  disabled    (disabled)     #IMPLIED
  label       %Text;         #REQUIRED
  &gt;
&nbsp;
&lt;!ELEMENT option (#PCDATA)&gt;     &lt;!-- selectable choice --&gt;
&lt;!ATTLIST option
  %attrs;
  selected    (selected)     #IMPLIED
  disabled    (disabled)     #IMPLIED
  label       %Text;         #IMPLIED
  value       CDATA          #IMPLIED
  &gt;
&nbsp;
&lt;!ELEMENT textarea (#PCDATA)&gt;     &lt;!-- multi-line text field --&gt;
&lt;!ATTLIST textarea
  %attrs;
  %focus;
  name        CDATA          #IMPLIED
  rows        %Number;       #REQUIRED
  cols        %Number;       #REQUIRED
  disabled    (disabled)     #IMPLIED
  readonly    (readonly)     #IMPLIED
  onselect    %Script;       #IMPLIED
  onchange    %Script;       #IMPLIED
  &gt;
&nbsp;
&lt;!--
  The fieldset element is used to group form fields.
  Only one legend element should occur in the content
  and if present should only be preceded by whitespace.
--&gt;
&lt;!ELEMENT fieldset (#PCDATA | legend | %block; | form | %inline; | %misc;)*&gt;
&lt;!ATTLIST fieldset
  %attrs;
  &gt;
&nbsp;
&lt;!ELEMENT legend %Inline;&gt;     &lt;!-- fieldset label --&gt;
&lt;!ATTLIST legend
  %attrs;
  accesskey   %Character;    #IMPLIED
  &gt;
&nbsp;
&lt;!--
 Content is %Flow; excluding a, form and form controls
--&gt;
&lt;!ELEMENT button %button.content;&gt;  &lt;!-- push button --&gt;
&lt;!ATTLIST button
  %attrs;
  %focus;
  name        CDATA          #IMPLIED
  value       CDATA          #IMPLIED
  type        (button|submit|reset) "submit"
  disabled    (disabled)     #IMPLIED
  &gt;</pre>



<h2>Still with me?</h2>
<p>Thats good, this is the first article about this, sorry I kinda skipped over alot I was going to mention on forms..   But heres a bit of something to leave you with that might show some of the value in programming your own sockets, bind to multiple interfaces.. yes its true.  Really I just think its cool :)</p>
<pre>$opts = array(&#039;socket&#039; =&gt; array(&#039;bindto&#039; =&gt; &#039;192.108.7.103:0&#039;));
$context = stream_context_create($opts);
$fp = stream_socket_client("tcp://www.askapache.com:80", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context);</pre><p><a href="http://www.askapache.com/php/fsockopen-forms.html"></a><a href="http://www.askapache.com/php/fsockopen-forms.html">Faster POST and GET Form Submissions&#8230; Shazam</a> originally appeared on <cite>AskApache.com</cite> </p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/php/fsockopen-forms.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PHPMailer tutorial</title>
		<link>http://www.askapache.com/php/phpfreaks-eric-rosebrocks-phpmailer-tutorial.html</link>
		<comments>http://www.askapache.com/php/phpfreaks-eric-rosebrocks-phpmailer-tutorial.html#comments</comments>
		<pubDate>Thu, 14 Dec 2006 07:13:28 +0000</pubDate>
		<dc:creator>AskApache</dc:creator>
				<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.askapache.com.com/php/phpfreaks-eric-rosebrocks-phpmailer-tutorial.html</guid>
		<description><![CDATA[]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.askapache.com/php/phpfreaks-eric-rosebrocks-phpmailer-tutorial.html"></a><a href="http://www.askapache.com/php/phpfreaks-eric-rosebrocks-phpmailer-tutorial.html"><cite>AskApache.com</cite></a></p><p>This is meant to be an improved version of the article written by PHPFreaks founder, Eric Rosebrock on the <a href="http://www.phpfreaks.com/">PHPFreaks</a> site <a href="http://www.phpfreaks.com/tutorials/130/0.php">HERE</a>, simply because I noticed the URL for that tutorial often was down, so I rewrote it (close to verbatim) for my own personal use.</p>

<hr />

<p>PHPMailer is by far the BEST way to add email functionality to your web site.<br /><br />This is just an article to point you in the right direction to mastering this incredible php package.</p>



<h3>Tutorials, Guides, Documentation, and HowTos</h3>
<ul>
       <li><a href="http://phpmailer.sourceforge.net/docs/">PHPMailer Documentation</a></li>
	<li><a href="http://phpmailer.sourceforge.net/extending.html">Couple Examples using PHPMailer</a></li>
	<li><a href="http://phpmailer.sourceforge.net/tutorial.html">Brief PHPMailer tutorial on home site</a></li>
	<li><a href="http://www.askapache.com/php/phpfreaks-eric-rosebrocks-phpmailer-tutorial.html">PHPFreaks founder, Eric Rosebrock, PHPMailer tutorial</a> | <em>Original</em> <a href="http://www.phpfreaks.com/tutorials/130/0.php">(<em>alternate</em>)</a></li>
</ul>



<h3>Other PHPMailer links</h3>
<ul>
	<li><a href="http://phpmailer.sourceforge.net/">PHPMailer Home</a></li>
	<li><a href="http://sourceforge.net/projects/phpmailer">Sourceforge Project Home</a></li>
	<li><a href="http://phpmailer.sourceforge.net/faq.html">PHPMailer FAQ</a></li>
	<li><a href="https://lists.sourceforge.net/lists/listinfo/phpmailer-general">PHPMailer Mailing List</a></li>
	<li><a href="http://www.php.net/mail">PHP mail() function reference</a></li>
	<li><a href="http://rfc.askapache.com/rfc822/">Standard Email RFC822</a></li>
	<li><a href="http://rfc.askapache.com/rfc2046.txt">MIME Email RFC 2046</a></li>
</ul>





<h2>Introduction</h2>

<p>Sending E-Mail through PHP can be simple, or it can be  very complex depending on what you want to do.  A standard plain-text  E-Mail is what most developers resort to because building the MIME headers for  HTML mail can be a difficult process. Those days have been over for quite some  time with the amazing PHPMailer library that is available for free! In this  tutorial, I will discuss in detail the features and possibilities you have when  dealing with PHPMailer.</p>

<h2>Requirements</h2>
<p>The requirements of this tutorial are very limited.  You only need PHP and the ability to send mail() function or an SMTP connection. You should also have a basic  understanding of dealing with Object Oriented Programming (OOP) or at least how  to follow the examples we'll use in this tutorial.</p>

<p>Don't sweat it, this is going to be an easy tutorial for you to follow! </p>

<h2>About PHPMailer</h2>
<p>PHPMailer is a fully featured email transfer class for  PHP that I would put above all of the other E-Mail handlers that I've used. It's  popularity has grown rapidly over the past years that is has been around.  Announced on the PHPMailer website on December 7, 2004, it has reached over  100,000 downloads! I hope you will want to increment that counter by  reading this tutorial, and more importantly, learn how to enable E-Mail features  you have only dreamed of!</p>

<h3>PHPMailer Features</h3>
<p>At the time this tutorial was written, here is a list of features currently available:</p>

<ul>
    <li>Can send emails with multiple TOs, CCs, BCCs and REPLY-TOs</li>
    <li>Redundant SMTP servers</li>
    <li>Multipart/alternative emails for mail clients that do not read HTML email</li>
    <li>Support for 8bit, base64, binary, and quoted-printable encoding</li>
    <li>Uses the same <a href="http://phpmailer.sourceforge.net/phpdoc/default/phpmailer.html">methods</a> as the very popular AspEmail active server (COM) component</li>
    <li>SMTP authentication</li>
    <li>Word wrap</li>
    <li>Address reset functions</li>
    <li>HTML email</li>
    <li>Tested on multiple SMTP servers: <a href="http://www.sendmail.org">Sendmail</a>, <a href="http://www.qmail.org">qmail</a>, <a href="http://www.postfix.org">Postfix</a>, Imail, Exchange, Mercury, Courier</li>
    <li>Works on any win32 or *nix platform</li>
    <li>Flexible debugging</li>
    <li>Custom mail headers</li>
    <li>Multiple fs, string, and binary attachments (those from database, string, etc)</li>
    <li>Embedded image support</li>
</ul>

<h3>PHPMailer Contributors</h3>
<p>The following contributors to PHPMailer are:</p>

<ul>
    <li>Brent R. Matzelle</li>
    <li>Patrice Fournier</li>
    <li>Chris Ryan</li>
    <li>Cem Hurturk</li>
    <li>Tom Klingenberg</li>
    <li>Jaime Bozza</li>
</ul>

<p>I give these folks great respect for what they have done  to speed up my development time on various projects in the past, including  PHPFreaks.com!</p>


<h2>Preparing PHPMailer for Use</h2>
<p>Let's download, unpack and prepare PHPMailer!</p>

<h3>Downloading and Unpacking</h3>
<p>The first thing you have to do is of course, download  PHPMailer! You can get it at: <a href="http://phpmailer.sourceforge.net/">http://phpmailer.sourceforge.net/</a> . Once you have  the files downloaded, simply extract them into a directory. In this tutorial,  we'll assume that your website is setup for this directory  structure: <strong>/home/mywebsite/public_html/</strong>. Now, what  you want to do is create a couple of directories for structuring your web area.  I usually put libraries under 'lib' and then their name. So, we'll extract PHPMailer into <strong>/home/mywebsite/public_html/lib/phpmailer</strong> and the  contents of this directory looks like this with the files in place:</p>

<pre>/home/mywebsite/public_html/lib
/home/mywebsite/public_html/lib/phpmailer
/home/mywebsite/public_html/lib/phpmailer/docs
/home/mywebsite/public_html/lib/phpmailer/docs/extending.html
/home/mywebsite/public_html/lib/phpmailer/docs/faq.html
/home/mywebsite/public_html/lib/phpmailer/docs/timeoutfix.diff
/home/mywebsite/public_html/lib/phpmailer/language
/home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-br.php
/home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-cz.php
/home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-de.php
/home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-en.php
/home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-es.php
/home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-fr.php
/home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-it.php
/home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-nl.php
/home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-no.php
/home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-se.php
/home/mywebsite/public_html/lib/phpmailer/language/phpmailer.lang-tr.php
/home/mywebsite/public_html/lib/phpmailer/phpdoc
/home/mywebsite/public_html/lib/phpmailer/phpdoc/allclasses-frame.html
/home/mywebsite/public_html/lib/phpmailer/phpdoc/deprecated-list.html
/home/mywebsite/public_html/lib/phpmailer/phpdoc/help-doc.html
/home/mywebsite/public_html/lib/phpmailer/phpdoc/index-all.html
/home/mywebsite/public_html/lib/phpmailer/phpdoc/index.html
/home/mywebsite/public_html/lib/phpmailer/phpdoc/overview-tree.html
/home/mywebsite/public_html/lib/phpmailer/phpdoc/packages.html
/home/mywebsite/public_html/lib/phpmailer/phpdoc/phpmailer.html
/home/mywebsite/public_html/lib/phpmailer/phpdoc/serialized-form.html
/home/mywebsite/public_html/lib/phpmailer/phpdoc/stylesheet.css
/home/mywebsite/public_html/lib/phpmailer/test
/home/mywebsite/public_html/lib/phpmailer/test/phpmailer_test.php
/home/mywebsite/public_html/lib/phpmailer/test/phpunit.php
/home/mywebsite/public_html/lib/phpmailer/test/rocks.png
/home/mywebsite/public_html/lib/phpmailer/ChangeLog.txt
/home/mywebsite/public_html/lib/phpmailer/class.phpmailer.php
/home/mywebsite/public_html/lib/phpmailer/class.smtp.php
/home/mywebsite/public_html/lib/phpmailer/LICENSE
/home/mywebsite/public_html/lib/phpmailer/README</pre>

<p>Now that we have those files in place, let's move on to creating our site configuration file!</p>
<hr class="HR0" />

<h3>Creating and Using a Site Configuration File</h3>
<p>One of the things I like to do when I build a site is to  create a configuration file that handles miscellaneous settings that I may need  over and over again. So, I create a file called config.php in <strong>/home/mywebsite/public_html/config.php</strong> and I set it up with an  array called <strong>$site</strong> with my keys and values the settings I use  in the site. In this tutorial, I will cover how to define some settings we will  use for the PHPMailer extender class. Here's a view of my configuration  file: <strong>config.php</strong></p>

<pre>&lt;?php
&nbsp;
// Configuration settings for My Site
&nbsp;
// Email Settings
$site[&#039;from_name&#039;] = &#039;My Name&#039;; // from email name
$site[&#039;from_email&#039;] = &#039;email@mywebsite.com&#039;; // from email address
&nbsp;
// Just in case we need to relay to a different server,
// provide an option to use external mail server.
$site[&#039;smtp_mode&#039;] = &#039;disabled&#039;; // enabled or disabled
$site[&#039;smtp_host&#039;] = null;
$site[&#039;smtp_port&#039;] = null;
$site[&#039;smtp_username&#039;] = null;
?&gt;</pre>

<p>The previous example should be very self explanatory, so we'll move on and cover those settings later on when we start to use them.</p>

<h3>The PHPMailer Extender Class</h3>
<p>First, I want to emphasize, you do not need to create an  extender class, but to make life easier for us, I'm going to show you how to  anyways.</p> <p>The extender class will basically call the PHPMailer() class and then setup  the basic values for you such as the Email address you want to send from, mail server settings and etc. Each of these settings are inherited by the  config.php by default, but you may also overwrite them when you call  our extender class. For example, if you do not define the settings in  the extender class, they will be set by default and this in turn, allows  you to setup the basic values without actually going through the motions  every time.  That's the beauty of it!</p> <p>Here's a look at our  extender class:</p>

<p><strong>MailClass.inc</strong></p>
<pre>&lt;?php
require_once($_SERVER[&#039;DOCUMENT_ROOT&#039;].&#039;/lib/phpmailer/class.phpmailer.php&#039;);
&nbsp;
class FreakMailer extends PHPMailer
{
    var $priority = 3;
    var $to_name;
    var $to_email;
    var $From = null;
    var $FromName = null;
    var $Sender = null;
&nbsp;
    function FreakMailer()
    {
        global $site;
&nbsp;
        // Comes from config.php $site array
&nbsp;
        if($site[&#039;smtp_mode&#039;] == &#039;enabled&#039;)
        {
            $this-&gt;Host = $site[&#039;smtp_host&#039;];
            $this-&gt;Port = $site[&#039;smtp_port&#039;];
            if($site[&#039;smtp_username&#039;] != &#039;&#039;)
            {
                $this-&gt;SMTPAuth = true;
                $this-&gt;Username = $site[&#039;smtp_username&#039;];
                $this-&gt;Password = $site[&#039;smtp_password&#039;];
            }
            $this-&gt;Mailer = "smtp";
        }
        if(!$this-&gt;From)
        {
            $this-&gt;From = $site[&#039;from_email&#039;];
        }
        if(!$this-&gt;FromName)
        {
            $this-&gt; FromName = $site[&#039;from_name&#039;];
        }
        if(!$this-&gt;Sender)
        {
            $this-&gt;Sender = $site[&#039;from_email&#039;];
        }
        $this-&gt;Priority = $this-&gt;priority;
    }
}
?&gt;</pre>

<h2>The PHP Mail Class</h2>
<h3>FreakMailer Class Code Breakdown</h3>
<p>The FreakMailer class previously displayed is pretty  simple. You only need a very basic understanding of Object Oriented Programming  to use it, so let's break it down now.</p>

<p>First, we are going to call the <strong>class.phpmailer.php</strong> file from within our phpmailer lib directory under the document  root. This allows us to extend the PHPMailer class because it makes that object  available. You could include this elsewhere, but this is a good place to do so.</p>
<pre>require_once($_SERVER[&#039;DOCUMENT_ROOT&#039;].&#039;/lib/phpmailer/class.phpmailer.php&#039;);</pre>

<h4>Class Control Structure</h4>
<p>Next, we define the class control structure and give our  new class a name while extending the PHPMailer class.</p>
<pre>class FreakMailer extends PHPMailer
{</pre>

<h4>Class Variables</h4>
<p>Moving along, we now setup the internal variables. Most of these are set to <strong><em>null</em></strong> by default so that we can do some triggering later on to determine if you want to overwrite the default values from the <strong>config.php</strong> file.</p>
<pre>var $priority = 3;
var $to_name;
var $to_email;
var $From = null;
var $FromName = null;
var $Sender = null;</pre>

<p>Let's take a look at these values now:</p>
<ul>
    <li>$priority - This sets the mail priority by default.          Values: 1 = High, 3 = Normal, 5 = Low</li>
    <li>$to_name - This is the name of the person you are sending to</li>
    <li>$to_email - The E-Mail address of the person you are sending to</li>
    <li>$From - The E-Mail address you want to send from</li>
    <li>$FromName - The Name of the sender.</li>
</ul>

<p>Now that we have those variables defined, we can discuss  the <strong>FreakMailer()</strong> function </p>

<h4>FreakMailer() Function</h4>
<p>This is the function that basically sets up the default  values for the PHPMailer to send E-Mail with. In other words, it's the whole  reason we are using this class.</p>

<p>First, we call the $site array from our config.php so  that it can be used within this function and class. There are a couple of ways  we can do this, we could point to it from outside of the class, or we can just  global it. Using the global call is the easiest method and it works, so let's  just do that!</p>

<pre>function FreakMailer()
{
    global $site; // Comes from config.php $site array</pre>

<p>Next, we start the bulk of the operations here and start  passing in values to the PHPMailer class. There's not much to explain here, if  the internal value ($this->setting) of the setting is not defined after you  instantiate the class, it basically calls it from the config.php and we'll use  that instead. I mentioned earlier that you can override the values in the  config.php and this is where those checks come into play.</p>

<pre>    if($site[&#039;smtp_mode&#039;] == &#039;enabled&#039;)
    {
        $this-&gt;Host = $site[&#039;smtp_host&#039;];
        $this-&gt;Port = $site[&#039;smtp_port&#039;];
        if($site[&#039;smtp_username&#039;])
        {
            $this-&gt;SMTPAuth = true;
            $this-&gt;Username = $site[&#039;smtp_username&#039;];
            $this-&gt;Password = $site[&#039;smtp_password&#039;];
        }
        $this-&gt;Mailer  = "smtp";
    }
&nbsp;
    if(!$this-&gt;From)
    {
        $this-&gt;From = $site[&#039;from_email&#039;];
    }
    if(!$this-&gt;FromName)
    {
        $this-&gt;FromName = $site[&#039;from_name&#039;];
    }
    if(!$this-&gt;Sender)
    {
        $this-&gt;Sender = $site[&#039;from_email&#039;];
    }
    $this-&gt;Priority = $this-&gt;priority;
}</pre>


<p>The most important thing you need to understand is that all of the functionality in the PHPMailer is still present and can be used even though we've extended the class. The only thing we've done here is created an extension (hence extends) that takes care of the repetitive stuff we don't want to do every time we need to send an E-Mail</p>

<p>Now that we have a good understanding of the extender class, let's move along and start sending some E-Mail!</p>



<p><strong>Sending E-Mail with PHP</strong></p>



<h2>Sending E-Mail with PHPMailer</h2>

<p>We've done our work and we've got everything ready to go to start sending E-Mail with PHPMailer. Let's give it a go and see how everything works!</p>

<h3>Basic Test</h3>

<p>This test is very important to this tutorial because we will be referring to this basic test code throughout the tutorial when I show you how to use different features with PHPMailer. If this test does not work for you, read through the tutorial again and keep trying until it does work, othewise you will be lost later on!</p>

<p>Our first code example is going to be a file looks like this:</p>
<pre>&lt;?php
&nbsp;
// Grab our config settings
require_once($_SERVER[&#039;DOCUMENT_ROOT&#039;].&#039;/config.php&#039;);
&nbsp;
// Grab the FreakMailer class
require_once($_SERVER[&#039;DOCUMENT_ROOT&#039;].&#039;/lib/MailClass.inc&#039;);
&nbsp;
// instantiate the class
$mailer = new FreakMailer();
&nbsp;
// Set the subject
$mailer-&gt;Subject = &#039;This is a test&#039;;
&nbsp;
// Body
$mailer-&gt;Body = &#039;This is a test of my mail system!&#039;;
&nbsp;
// Add an address to send to.
$mailer-&gt;AddAddress(&#039;foo@host.com&#039;, &#039;Eric Rosebrock&#039;);
&nbsp;
if(!$mailer-&gt;Send())
{
    echo &#039;There was a problem sending this mail!&#039;;
}
else
{
    echo &#039;Mail sent!&#039;;
}
$mailer-&gt;ClearAddresses();
$mailer-&gt;ClearAttachments();
?&gt;</pre>

<p>Let's break down this file so that we have a good understanding of what it does.</p>

<p>First, we are going to include our <strong>config.php</strong> file within the Document Root so that we have the <strong>$site</strong> settings available.</p>
<pre>// Grab our config settings
require_once($_SERVER[&#039;DOCUMENT_ROOT&#039;].&#039;/config.php&#039;);</pre>

<p>You could do this next step within the config.php file, but to make things easier, I chose not to.</p>
<pre>// Grab the FreakMailer class
require_once($_SERVER[&#039;DOCUMENT_ROOT&#039;].&#039;/lib/MailClass.inc&#039;);</pre>

<p>Next, we are going to call up our <strong>FreakMailer</strong> class and when we do this, we'll also initialize the <strong>PHPMailer</strong> class as well by the <strong>extends</strong> definition in the FreakMailer class.</p>
<pre>// instantiate the class
$mailer = new FreakMailer();</pre>

<p>Ok, so now we have PHPMailer ready to go with all of our default settings, let's go ahead and define a subject: </p>
<pre>// Set the subject
$mailer-&gt;Subject = &#039;This is a test&#039;;</pre>

<p>Now let's define the body of the message:</p>
<pre>// Body
$mailer-&gt;Body = &#039;This is a test of my mail system!&#039;;</pre>



<p><strong>NOTE:</strong><br />
If you are using plain text E-Mail, which is the default, you need to convert new lines by using <strong>\n</strong> or<strong> \r\n</strong> and you should use double quotes in the strings such as <code>$mailer-&gt;Body</code>. Otherwise for single quotes you can start your string and type it out however you want it in your PHP script and press <code>&lt;enter&gt;</code> for each new line you wish to make and when you are done with your string, just end it with the semicolon like normal.</p>

<p>Now, add an address to send to. The AddAddress accepts two inputs. The first is the E-mail address to send to and the second is the Name of the person you are sending to.</p>
<pre>// Add an address to send to.
$mailer-&gt;AddAddress(&#039;foo@host.com&#039;, &#039;Eric Rosebrock&#039;);</pre>

<p>Next, we send the message and look for an error:</p>
<pre>if(!$mailer-&gt;Send())
{
    echo &#039;There was a problem sending this mail!&#039;;
}
else
{
    echo &#039;Mail sent!&#039;;
}</pre>


<p>Obviously, if an error is detected, you will see <strong><em>There was a problem sending this mail!</em></strong>, otherwise you will see: <strong><em>Mail sent!</em></strong></p>
<p>Finally, we will clear the attatchment list and the Address list. This is primarily for sending Mailing lists, but I do it anyways as a (bad?) habit.</p>
<pre>$mailer-&gt;ClearAddresses();
$mailer-&gt;ClearAttachments();
?&gt;</pre>

<p>If you have just sent yourself an E-Mail with PHPMailer, then congratulations, you're on your way to sending E-Mail with PHP the easy way!</p>


<h4>Common Problems</h4>
<p>Here's a list of some common problems you may have with sending E-Mail through PHPMailer (these problems would probably be the same with the standard mail() function as well.).</p>
<ul>
    <li>No SMTP server Running on the local machine - You need some type of SMTP server running!</li>
    <li>Improper setup of the PHP script - Please review through the tutorial again until it works.</li>
    <li>The Apache Web Server is not allowed to relay through the SMTP server on the local machine (typical with some web hosts).</li>
    <li>You did not define the recipient properly.</li>
</ul>

<p>Alright! If you haven't had any problems, let's move along to sending E-Mail with additional features. Let's move on to using some additional features in PHPMailer!</p>
<hr />


<p><strong>Email with PHP - BCC, CC, Reply-TO, Multiple Recipients</strong></p>
<hr />


<h2>Using PHPMailer's Additional Features</h2>
<p>If you're at this point and you have not read the entire tutorial yet, please go back and read. We will be extending on the Basic Example from this point forward.</p>
<p>PHPMailer has many features such as adding attachments, the ability to send a mailing list, multiple recipients, and much more. In this section of the tutorial, we're going to show you how to do most of those.</p>


<h3>Handling E-Mail Addresses</h3>
<p>PHPMailer supports many E-Mail address features, such as TO and FROM, multiple recipients, Carbon Copy (BCC), Reply-To addresses and more. Let's review how to utilize these features.</p>

<p>Remember, we are building upon the Basic Example presented earlier in this tutorial, however you can generally apply these methods into any PHPMailer usage because these functions are in the main class.</p>

<h4>Adding the FROM Address</h4>
<p>In our file and our extender class, however you can override that at any time. Here's an example:</p>
<pre>$mailer-&gt;FromName = &#039;Your Name&#039;;
$mailer-&gt;From = &#039;You@yourdomain.com&#039;;</pre>


<p>That was pretty simple! If you do not define the <strong><em>FromName</em></strong> by default in the class, it will show up as the E-Mail address in most clients.</p>

<h4>Adding a Reply-To Address</h4>
<p>By default the Reply-To address will be the FROM address unless you specify otherwise. That is simply E-Mail client intelligence. However, you can have the E-Mail come from one E-Mail address and any replies go to a different one. Here's how:</p>
<pre>$mailer-&gt;AddReplyTo(&#039;billing@yourdomain.com&#039;, &#039;Billing Department&#039;);</pre>

<p><strong>NOTE:</strong><br />
You can have multiple Reply-To addresses, just duplicate the line in the previous code example and change the E-Mail address on each line.</p>

<h4>Adding Multiple Recipients</h4>
<p>This method allows you to add multiple recipients to a single E-Mail address. I would not recommend this for anonymous mailing lists, or sending mailing lists. See later in this tutorial for a mailing list example.</p>

<p>To add multiple Recipients, all you have to do is call the <strong><em>AddAddress</em></strong> function once for each E-Mail address you want to send to. Here's an example of three E-Mail addresses:</p>
<p><strong>NOTE:</strong><br />
There are two arguments in this function. (Recipient Email Address, Recipient Name). The Recipient Name is optional and will not be used if not present.</p>
<pre>$mailer-&gt;AddAddress(&#039;recipient1@domain.com&#039;, &#039;First Person&#039;);
$mailer-&gt;AddAddress(&#039;recipient2@domain.com&#039;, &#039;Second Person&#039;);
$mailer-&gt;AddAddress(&#039;recipient3@domain.com&#039;, &#039;Third Person&#039;);</pre>



<p><strong>NOTE:</strong><br />
It is not recommended to use this method to send out mailing lists! Every recipient that gets the mail will see everyone else's E-Mail address and you may have just violated any kind of trust for your mailing list users! See later in this tutorial for sending Mailing lists.</p><h4>Adding Carbon Copy CC Recipients</h4>

<p>To carbon copy (CC) recipients you can add them to the E-Mail going out by using the following methods. Just like the Adding Multiple Recipients example, you can add multiple CC recipients as well.</p>
<pre>$mailer-&gt;AddCC(&#039;recipient1@domain.com&#039;, &#039;First Person&#039;);
&nbsp;
// More than one CC, just keep adding them!
$mailer-&gt;AddCC(&#039;recipient2@domain.com&#039;, &#039;Second Person&#039;);
$mailer-&gt;AddCC(&#039;recipient3@domain.com&#039;, &#039;Third Person&#039;);</pre>


<h4>Adding Blind Carbon Copy BCC Recipients</h4>
<p>The "invisible" recipients or BCC can be added to an E-Mail going out by using the following methods. Just like the Adding Multiple Recipients example, you can add multiple BCC recipients as well.</p>
<pre>$mailer-&gt;AddBCC(&#039;recipient1@domain.com&#039;, &#039;First Person&#039;);
&nbsp;
// More than one BCC, just keep adding them!
$mailer-&gt;AddBCC(&#039;recipient2@domain.com&#039;, &#039;Second Person&#039;);
$mailer-&gt;AddBCC(&#039;recipient3@domain.com&#039;, &#039;Third Person&#039;);</pre>



<h4>Adding a Reply-To Address</h4>
<p>By default the Reply-To address will be the FROM address unless you specify otherwise. That is simply E-Mail client intelligence. However, you can have the E-Mail come from one E-Mail address and any replies go to a different one. Here's how:</p>
<pre>$mailer-&gt;AddReplyTo(&#039;billing@yourdomain.com&#039;, &#039;Billing Department&#039;);</pre>

<p><strong>NOTE:</strong><br />
You can have multiple Reply-To addresses, just duplicate the line in the previous code example and change the E-Mail address on each line.</p>


<h4>Adding Multiple Recipients</h4>
<p>This method allows you to add multiple recipients to a single E-Mail address. I would not recommend this for anonymous mailing lists, or sending mailing lists. See later in this tutorial for a mailing list example.</p>
<p>To add multiple Recipients, all you have to do is call the <strong><em>AddAddress</em></strong> function once for each E-Mail address you want to send to. Here's an example of three E-Mail addresses:</p>

<p><strong>NOTE:</strong><br />
There are two arguments in this function. (Recipient Email Address, Recipient Name). The Recipient Name is optional and will not be used if not present.</p>
<pre>$mailer-&gt;AddAddress(&#039;recipient1@domain.com&#039;, &#039;First Person&#039;);
$mailer-&gt;AddAddress(&#039;recipient2@domain.com&#039;, &#039;Second Person&#039;);
$mailer-&gt;AddAddress(&#039;recipient3@domain.com&#039;, &#039;Third Person&#039;);</pre>

<p><strong>NOTE:</strong><br />
It is not recommended to use this method to send out mailing lists! Every recipient that gets the mail will see everyone else's E-Mail address and you may have just violated any kind of trust for your mailing list users! See later in this tutorial for sending Mailing lists.</p>


<h4>Requesting a Read Receipt</h4>
<p>If you want to request a Read Receipt from the person who receives the E-Mail, you can use the following setting:</p>
<pre>$mailer-&gt;ConfirmReadingTo = &#039;you@youdomain.com&#039;;</pre>


<p>Now that we've covered E-Mail addresses, let's move along to sending the beloved HTML Mail!</p>
<hr />


<p><strong>HTML Mail with PHP</strong></p>
<hr />


<h3>Sending HTML Mail with PHP and PHPMailer</h3>
<p>HTML Mail has proven to be one of the more complicated tasks when sending E-Mail through PHP. Setting the MIME types and building the boundaries of an HTML body are not easy to do and it takes some considerable research to get it right. However, PHPMailer has made life easy for us and I will show you how to do this now.</p>


<h4>Important Notes on HTML Mail</h4>
<p>Before we go to far into sending HTML mail, I want you to understand that it is important to know how images and files such as CSS and etc should be handled. A simple rule is to store them on the web server and file on the web server in your HTML that will be compiled and sent through the HTML Mail. If you go crazy and add a bunch of files to an E-Mail and try to call them within the E-Mail itself, you're in for one huge headache. An example of my HTML body would be something like:</p>
<pre>&lt;html&gt;
&lt;head&gt;
&lt;title&gt;My HTML Email&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;br /&gt;
&lt;h2&gt;PHP Freaks Rules!&lt;/h2&gt;
&lt;p&gt;We invite you to visit &lt;a href="http://www.phpfreaks.com" title="PHP Freaks"&gt;PHP Freaks.com&lt;/a&gt; for a loving community of PHP Developers who enjoy helping each other learn the language!&lt;/p&gt;
&lt;p&gt;Sincerely,&lt;br /&gt;
PHP Freaks Staff&lt;/p&gt;</pre>

<p>In the previous example, I made every link a full URL and not a shortcut relative to my document root. If you do not do this, then your images and URLs will be broken!</p>

<p>Moving along, now we are going to send the HTML mail by setting the body and a the <strong><em>isHTML</em></strong> setting in PHPMailer. Once again, this example expands upon the Basic Example earlier in this tutorial.</p>
<pre>$htmlBody = &#039;&lt;html&gt;
&lt;head&gt;
&lt;title&gt;My HTML Email&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;br /&gt;
&lt;h2&gt;PHP Freaks Rules!&lt;/h2&gt;
&lt;p&gt;We invite you to visit &lt;a href="http://www.phpfreaks.com" title="PHP Freaks"&gt;PHP Freaks.com&lt;/a&gt; for a loving community of PHP Developers who enjoy helping each other learn the language!&lt;/p&gt;
&nbsp;
&lt;p&gt;Sincerely,&lt;br /&gt;
PHP Freaks Staff&lt;/p&gt;&#039;;
&nbsp;
$mailer-&gt;Body($htmlBody);
$mailer-&gt;isHTML(true);
&nbsp;
// Send the E-Mail</pre>

<h5>Alternate Text Bodies For HTML Mail</h5>
<p>You should never rely on HTML only E-Mails if your message is important. Instead, you should do your recipient a favor and send a text-only version of the E-Mail along with the HTML body in case their E-Mail client cannot display the HTML version.</p>
<p>We can accomplish this by defining the <strong><em>AltBody</em></strong> setting of the PHPMailer class. This setting will be the plain text version of your E-Mail and if it is set or Not Empty, the ContentType of the E-Mail is automatically set to <strong>multipart/alternative</strong>. Here's how you would do this:</p>
<pre>// setup the $mailer class
&nbsp;
$htmlBody = &#039;My HTML Body....&#039;;
$textBody = &#039;My text-only body....&#039;;
&nbsp;
$mailer-&gt;Body($htmlBody);
$mailer-&gt;isHTML(true);
$mailer-&gt;AltBody($textBody);
&nbsp;
// Send the mail...</pre>

<p>Now two formats of E-Mail will be sent to the recipient.</p>

<p>Let's move along to File Attachments with PHPMailer</p>
<hr />


<p><strong>PHP File Attachements</strong></p>
<hr />

<hr class="HR0" />

<h3>File Attachments in PHP Mail with PHPMailer</h3>
<p>Sending file attachments is really easy to do. You simply add them to the attachment just like you would an address, cc, bcc or reply-to, except using the proper function. See the example below:</p>
<pre>// Setup mail class, recipients and body
$mailer-&gt;AddAttachment(&#039;/home/mywebsite/public_html/file.zip&#039;, &#039;file.zip&#039;);</pre>

<p>The <strong><em>AddAttachment</em></strong> function has four arguments:</p>
<p><strong>AddAttachment(PATH_TO_FILE, FILENAME, ENCODING, HEADER_TYPE)</strong></p>

<p>The PATH_TO_FILE is naturally the full path of the header you want to send. Application/octet-stream is default.</p>

<p>That was pretty easy! Let's move along to using SMTP servers and utilizing diferent types of local E-mail SMTP servers.</p>
<hr />


<p><strong>SMTP Servers with PHP Mail</strong></p>
<hr />


<h3>Using External SMTP Server(s) with PHP Mail</h3>
<p>First, let's discuss using external SMTP servers instead  of localhost. In this tutorial, we setup a config.php file. Inside this file, we  have a few options for SMTP servers. If you want to simply enable one more more  SMTP servers, you can do so through this configuration file by setting <strong>$site['smtp_enabled'] = 'enabled';</strong></p>

<p>In the <strong>$site['smtp_host']</strong> setting you can have a list of SMTP  servers to send through delimited by a semicolon:</p>

<p>From my understanding of this SMTP setting, PHPMailer will send E-Mail through the main host first and if it cannot connect, it will go to the next one in the list.</p>

<p><strong>NOTE:</strong><br />
Remember, you can enable SMTP authentication and change the SMTP port via your config.php file with the basic settings that we created. </p>

<p>One important thing to note about sending through SMTP is that instead of using the standard Send() function, you will use  SMTPSend(); Example:</p>
<pre>// Class and mail body setup here....
// See basic Example.
&nbsp;
// Non SMTP Mode:
// $mailer-&gt;Send();
&nbsp;
// SMTP Mode:
$mailer-&gt;SmtpSend();</pre>


<h4>SMTP Mail Problems</h4>
<p>There are many things that can go wrong with sending mail through SMTP and most of the problems come from permission issues.</p>
<ul>
    <li>Does your Host have permission to relay through the SMTP Host?</li>
    <li>Does your host require POP before SMTP?</li>
    <li>Does your Host require SMTP authentication?</li>
    <li>Are your SMTP settings correct for the remote host username / password?</li>
</ul>

<p><strong>NOTE:</strong><br />
Unfortunately, I do not believe PHPMailer supports POP before SMTP. If this is a problem for you, you should contact your system administrator and request a RELAY HOST be setup for your webserver's IP address.</p>

<h3>Taking Advantage of qmail and Sendmail with PHP Mail</h3>
<p>If you want to bypass the PHP Mail server and then PHPMailer will execute that Binary which could possibly speed things up quite a bit.</p>
<p><strong>qmail Example:</strong></p>
<pre>// Setup Mail class and features
$mailer-&gt;IsQmail();
$mailer-&gt;Send();</pre>


<p><strong>Sendmail Example:</strong></p>
<pre>// Setup Mail class and features
$mailer-&gt;IsSendmail();
$mailer-&gt;Send();</pre>

<p>That was pretty easy! Let's move along to creating a simple Mailing list with PHPMailer!</p>
<hr />


<p><strong>PHP Mailing List Example</strong></p>
<hr />


<h3>PHP Mailing List Example</h3>
<p>Now that you have a good understanding of the PHPMailer and how it works, let's discuss some Mailing List features. A few considerations you may have about sending mailing lists are customizable subjects, bodies and possibly even content. More importantly, is the ability to hide the E-Mail addresses of everyone else on the list from each other.</p>
<p>This example assumes that you already have some sort of database setup for mailing list users and you know how to connect to MySQL and query data. If you don't know how to do that, then there's some tutorials on this site that can help you get to this point. For now, we'll assume that we have something of the following table structure:</p>
<ul>
    <li>FirstName</li>
    <li>LastName</li>
    <li>EmailAddress</li>
    <li>MailType (text / html)</li>
</ul>

<p>Let's assume that you have 50 users in your database and you want to E-Mail them all a customizable E-Mail. The following code will accomplish this for you:</p>
<pre>&lt;?php
// Grab our config settings
require_once($_SERVER[&#039;DOCUMENT_ROOT&#039;].&#039;/config.php&#039;);
&nbsp;
// Grab the FreakMailer class
require_once($_SERVER[&#039;DOCUMENT_ROOT&#039;].&#039;/lib/MailClass.inc&#039;);
&nbsp;
// Setup body
$textBody = "Dear {MEMBER_NAME},\n\nCheck out PHP Freaks: http://www.phpfreaks.com\n\nSincerely,\nAdmin";
$htmlBody = "Dear {MEMBER_NAME},&lt;br /&gt;&lt;br /&gt;Check out PHP Freaks: http://www.phpfreaks.com&lt;br /&gt;&lt;br /&gt;Sincerely,&lt;br /&gt;Admin";
&nbsp;
// instantiate the class
$mailer = new FreakMailer();
&nbsp;
// Get the user&#039;s Email
$sql = mysql_query("SELECT FirstName,LastName,EmailAddress,MailType FROM users WHERE 1");
&nbsp;
while($row = mysql_fetch_object($sql))
{
    // Send the emails in this loop.
    $member_name = $row-&gt;FirstName;
    if(!empty($row-&gt;LastName))
    {
        $member_name .= &#039; &#039;.$row-&gt;LastName;
    }
&nbsp;
    if($row-&gt;MailType == &#039;html&#039;)
    {
        $mailer-&gt;Body = str_replace(&#039;{MEMBER_NAME}&#039;, $member_name, $htmlBody);
        $mailer-&gt;IsHTML(true);
        $mailer-&gt;AltBody = str_replace(&#039;{MEMBER_NAME}&#039;, $member_name, $textBody);
    }
    else
    {
        $mailer-&gt;Body = str_replace(&#039;{MEMBER_NAME}&#039;, $member_name, $textBody);
        $mailer-&gt;isHTML(false);
    }
    $mailer-&gt;Send();
    $mailer-&gt;ClearAddresses();
    $mailer-&gt;ClearAttachments();
    $mailer-&gt;IsHTML(false);
    echo "Mail sent to: $member_name&lt;br /&gt;";
}
&nbsp;
?&gt;</pre>


<h4>PHP Mailing List Code Breakdown</h4>
<p>Let's break this code down for further understanding.</p>
<p>The first portion is just like our basic example earlier in this tutorial. It includes the scripts we need to instantiate the class.</p>
<pre>&lt;?php
// Grab our config settings
require_once($_SERVER[&#039;DOCUMENT_ROOT&#039;].&#039;/config.php&#039;);
&nbsp;
// Grab the FreakMailer class
require_once($_SERVER[&#039;DOCUMENT_ROOT&#039;].&#039;/lib/MailClass.inc&#039;);</pre>

<p>Next, we will go ahead and file_get_contents() function to read these into the script, but to keep it simple here, we just use a small string instead.</p>

<p>Notice the <strong><em>{MEMBER_NAME}</em></strong> placeholders that I have put into these examples. Later when we loop through the users, we'll str_replace() this with their actual information.</p>
<pre>// Setup body
$textBody = "Dear {MEMBER_NAME},\n\nCheck out PHP Freaks: http://www.phpfreaks.com\n\nSincerely,\nAdmin";
$htmlBody = "Dear {MEMBER_NAME},&lt;br /&gt;&lt;br /&gt;Check out PHP Freaks: http://www.phpfreaks.com&lt;br /&gt;&lt;br /&gt;Sincerely,&lt;br /&gt;Admin";</pre>

<p>Next, we will go ahead and get our Mail class ready:</p>
<pre>// instantiate the class
$mailer = new FreakMailer();</pre>

<p>Now, this is where you will have to create your own tables and get your own data. This is a simple mysql_fetch_object()</p>
<pre>// Get the user&#039;s Email
$sql = mysql_query("SELECT FirstName,LastName,EmailAddress,MailType FROM users WHERE 1");
&nbsp;
while($row = mysql_fetch_object($sql))
{</pre>


<p>Now, this is where the heart of the E-Mail sending occurs. This is extremely important for you to pay attention here. The first portion of the code will basically create the <strong><em>$member_name</em></strong> string which will contain this specific user's information for this portion of the loop. </p>
<pre>    $member_name = $row-&gt;FirstName;
    if(!empty($row-&gt;LastName))
    {
        $member_name .= &#039; &#039;.$row-&gt;LastName;
    }</pre>

<p>Our Mail preferences. If the user's <strong><em>MailType</em></strong> is set to 'html' in the database, then we'll send them an HTML E-Mail with a plaintext alternative body. Otherwise (else) we'll send them just a plain text E-Mail.</p>
<pre>    if($row-&gt;MailType == &#039;html&#039;)
    {
        $mailer-&gt;Body = str_replace(&#039;{MEMBER_NAME}&#039;, $member_name, $htmlBody);
        $mailer-&gt;IsHTML(true);
        $mailer-&gt;AltBody = str_replace(&#039;{MEMBER_NAME}&#039;, $member_name, $textBody);
    }
    else
    {
        $mailer-&gt;Body = str_replace(&#039;{MEMBER_NAME}&#039;, $member_name, $textBody);
        $mailer-&gt;isHTML(false);
    }</pre>

<p>Please analyze the code above until you understand it. This information was previously discussed in this tutorial and you should be familiar with how to send Plain Text and HTML E-Mails.</p>

<p>Finally, we send out the E-Mail and then clear the addresses from the $mailer object as well as any attachments you may have.</p>
<pre>    $mailer-&gt;Send();
    $mailer-&gt;ClearAddresses();
    $mailer-&gt;ClearAttachments();
    $mailer-&gt;IsHTML(false);
    echo "Mail sent to: $member_name&lt;br /&gt;";</pre>

<p><strong>NOTE:</strong><br />
Please make sure that you use the ClearAddress() and ClearAttachments() functions otherwise the users in the Mailing list will always be appended to the list. Trust me on this one!</p>


<h2>Summary</h2>
<p>This tutorial should have given you a good push in the right direction to making life easier with sending E-Mail through PHP. Thanks to the excellent PHPMailer class and the developers of it, we can now send E-Mail without memorizing or constantly looking up headers when we need to send more complexe E-Mails.</p>
<p>If you set this Mail portions and move on to more complicating things without wasting your time.</p>


<h2>PHPMailer Resources</h2>
<p>I hope you take the PHPMailer FAQ. It is important to understand this class and read what the Developers have said about it. In addition, there is another great <a href="http://phpmailer.sourceforge.net/tutorial.html">tutorial</a> and some <a href="http://phpmailer.sourceforge.net/extending.html">examples</a> for PHPMailer on their <a href="http://phpmailer.sourceforge.net">website</a>.
Good luck!<strong><em>-phpfreak</em></strong></p><p><a href="http://www.askapache.com/php/phpfreaks-eric-rosebrocks-phpmailer-tutorial.html"></a><a href="http://www.askapache.com/php/phpfreaks-eric-rosebrocks-phpmailer-tutorial.html">PHPMailer tutorial</a> originally appeared on <cite>AskApache.com</cite> </p>]]></content:encoded>
			<wfw:commentRss>http://www.askapache.com/php/phpfreaks-eric-rosebrocks-phpmailer-tutorial.html/feed</wfw:commentRss>
		<slash:comments>42</slash:comments>
		</item>
	</channel>
</rss>

