Saturday, March 16, 2013

PHP: Sending Email (Text/HTML/Attachments)


PHP: Sending Email (Text/HTML/Attachments)

Print

Email is the most popular Internet service today. A plenty of emails are sent and delivered each day. The goal of this tutorial is to demonstrate how to generate and send emails in PHP.
So, you want to send automated email messages from your PHP application. This can be in direct response to a user's action, such as signing up for your site, or a recurring event at a set time, such as a monthly newsletter. Sometimes email contains file attachments, both plain text and HTML portions, and so on. To understand how to send each variation that may exist on an email, we will start with the simple example and move to the more complicated.
Note that to send email with PHP you need a working email server that you have permission to use: for Unix machines, this is often Sendmail; for Windows machines, you must set the SMTP directive in your php.ini file to point to your email server.
Sending a Simple Text Email
At first let's consider how to send a simple text email messages. PHP includes the mail() function for sending email, which takes three basic and two optional parameters. These parameters are, in order, the email address to send to, the subject of the email, the message to be sent, additional headers you want to include and finally an additional parameter to the Sendmail program. The mail() function returns True if the message is sent successfully and False otherwise. Have a look at the example:
<?php
//define the receiver of the email
$to = 'youraddress@example.com';
//define the subject of the email
$subject = 'Test email';
//define the message to be sent. Each line should be separated with \n
$message = "Hello World!\n\nThis is my first mail.";
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//send the email$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
As you can see, it very easy to send an email. You can add more receivers by either adding their addresses, comma separated, to the $to variable, or by adding cc: or bcc: headers. If you don't receive the test mail, you have probably installed PHP incorrectly, or may not have permission to send emails.
Sending HTML Email
The next step is to examine how to send HTML email. However, some mail clients cannot understand HTML emails. Therefore it is best to send any HTML email using a multipart construction, where one part contains a plain-text version of the email and the other part is HTML. If your customers have HTML email turned off, they will still get a nice email, even if they don't get all of the HTML markup. Have a look at the example:
<?php
//define the receiver of the email
$to = 'youraddress@example.com';
//define the subject of the email
$subject = 'Test HTML email';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/alternative; boundary=\"PHP-alt-".$random_hash."\"";
//define the body of the message.ob_start(); //Turn on output buffering
?>
--PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

--PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>

--PHP-alt-<?php echo $random_hash; ?>--
<?
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
In the preceding example we add one additional header of Content-type:multipart/alternative and boundary string that marks the different areas of the email. Note that the content type of the message itself is sent as a mail header, while the content types of the individual parts of the message are embedded in the message itself. This way, mail clients can decide which part of the message they want to display.
Sending Email with Attachment
The last variation that we will consider is email with attachments. To send an email with attachment we need to use the multipart/mixed MIME type that specifies that mixed types will be included in the email. Moreover, we want to use multipart/alternative MIME type to send both plain-text and HTML version of the email. Have a look at the example:
<?php
//define the receiver of the email
$to = 'youraddress@example.com';
//define the subject of the email
$subject = 'Test email with attachment';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash

$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks

$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?> 
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"

--PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

--PHP-alt-<?php echo $random_hash; ?> 
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>

--PHP-alt-<?php echo $random_hash; ?>--

--PHP-mixed-<?php echo $random_hash; ?> 
Content-Type: application/zip; name="attachment.zip" 
Content-Transfer-Encoding: base64 
Content-Disposition: attachment 

<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--

<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
As you can see, sending an email with attachment is easy to accomplish. In the preceding example we have multipart/mixed MIME type, and inside it we have multipart/alternative MIME type that specifies two versions of the email. To include an attachment to our message, we read the data from the specified file into a string, encode it with base64,  split it in smaller chunks to make sure that it matches the MIME specifications and then include it as an attachment.
Related Articles
For more information about the PHP mail() function, visit PHP Mail Reference.
 

How to install and configure PHP 5 on Windows box


How to install and configure PHP 5 on Windows box


Print

It is assumed that you have already successfully setup IIS or installed Apache on your machine and configured it. So, to configure PHP and secure its correct operation you need to go through a couple of steps.
Download and unzip the latest version of PHP
Download the latest zipped distribution of PHP from http://php.net. Unzip it. The recommendation is to put all the PHP stuff in a folder just off of the root drive (avoid whitespace), like C:\PHP.
Rename/copy php.ini-recommended to php.ini
In your PHP directory, you'll find a couple of php.ini-* files. They are pre-configured settings for a PHP install that you can use as an initial setup. The php.ini-recommended is the most secure, hence, the recommended one; just rename it to php.ini and copy to your Windows directory.
Create a session state directory and point the session.save_path variable in php.ini to it
This is optional, but recommended step. PHP does not need sessions, but it's something that will most likely be useful.
Create a session directory somewhere on the server. I created C:\PHP\sessionFolder. This directory will hold many small files with session variable information for PHP.
Now change the value of the session.save_path variable in php.ini to be the full path to that directory (session.save_path=C:\PHP\sessionFolder).
Setup the PHP extensions
You need to point PHP to the directory that holds the extension libraries and you need to uncomment the desired extensions.
  • Point PHP to the correct directory:
    Set extension_dir in php.ini to "C:\PHP\ext" (extension_dir = "C:\PHP\ext")
  • Uncomment the ones you want to use.
    It’s important to be sure that php_mysql.dll extension is uncommented (for PHP 5 or newer).
Make sure that PHP folder is in the system path
You should add "C:\PHP" to the server's PATH environment variable:
  • Right-click on My Computer, choose Properties
  • Flip to the Advanced tab
  • Click the Environment Variables button
  • Double-click the Path variable in the list of System variables.
  • Either add "C:\PHP;" to the beginning or ";C:\PHP" to the end (sans quotes, not both).
  • Restart IIS for it to take effect.
(To restart IIS you should right-click the local computer in the left pane of IIS Manager, click on All Tasks -> Restart IIS... -> OK)
Instead, you can copy all non-php dll files from C:\PHP to C:\Windows\System32 (or somewhere else in the server's PATH), but the first is the preferred method since it keeps the installation in one place, making upgrading or uninstalling easier.
 Configure IIS
For these steps, open IIS Manager
(Start -> Control Panel -> Administrative Tools -> Internet Information Services (IIS)  Manager).
Then add new extension (.php)
  • Expand the local computer in the left pane
  • Right-click on "Web Sites" in the left pane, then click "Properties" in the menu that pops up
  • Flip top the Home Directory tab
  • Click "Configuration"
  • Flip to the Mappings tab
  • Click Add...
  • Enter the full path to php5isapi.dll in the "Executable" textbox (Browse... to find it more easily if you need to)
  • Enter ".php" in the Extension textbox
  • Select radial button Limit to, enter "GET,POST,HEAD"
  • Click OK all the way out
This will apply to every website.
This sets up IIS to actually respond to requests for php files. Until now, IIS hadn't known what to do with php files, you just told it to pass them through php5isapi.dll.
Configure Apache Web Server
If you want PHP to work with your Apache server, you will need to modify your Apache configuration file to load it. There are two ways to configure Apache to use PHP: one is to configure it to load the PHP interpreter as an Apache module. The other is to configure it to run the PHP interpreter as a CGI binary. Unless you have a particular reason for running PHP as a CGI binary, you will probably want to load PHP as a module in Apache, since it runs more efficiently that way.
To configure Apache to load PHP as a module to parse your PHP scripts you should make some changes in the Apache configuration file, "httpd.conf", typically found in "c:\Program Files\Apache Group\Apache\conf\". It also can be accessed from your program files menu.
  • Search for the section that has a series of commented out "LoadModule" statements. Add the following line after all the LoadModule statements:
    LoadModule php5_module "c:/php/php5apache2.dll"
  • Search for "AddType" and add the following line after the last "AddType" statement:
    AddType application/x-httpd-php .php
If you need to support other file types, like ".php3" and ".phtml", simply add them to the list, like this:
AddType application/x-httpd-php .php3
AddType application/x-httpd-php .phtml
Test your setup
Create a new file named test.php in one of the websites. Expand the Web Sites folder in the left pane of IIS Manager to see a list of existing websites. Right-click on a website -> Properties -> Home Directory -> Local Path will show you where the website root directory is.
Create test.php file with the following line: <?php phpinfo(); ?>
With your browser go to http://localhost/test.php
After loading test.php, you should see some information about your PHP installation. Be sure to scroll all the way down to the bottom to see that there were no errors. Pay attention to "Configuration File (php.ini) Path" field. Field's value is current location of php.ini file and you should make appropriate changes in it.
Date Settings (for PHP 5.1 or newer)
It is strongly recommended to configure date settings in php.ini. It is not safe to rely on the system's time zone settings.
Set date.timezone in php.ini to your time zone (in my example it's Europe/Moscow).
Complete list of Timezones you can see at http://php.net/manual/en/timezones.php
Location of libmysql.dll
Lastly, we need to be sure that copy of libmysql.dll is located in PHP folder (for PHP 5.0 or newer).

Installing IIS 7 on Windows Vista and Windows 7 10/26/2007 3 minutes to read Contributors     by IIS Team Introduction Adv...