Wednesday, September 8, 2010

PHP Mail

• PHP Mail Introduction: One of the major uses of a server side scripting language is to provide a way of sending e-mail from the server and, in particular, to take form input and output it to an e-mail address. The mail() function allows you to send emails directly from a script.

• Requirements: For the mail functions to be available, PHP requires an installed and working email system i.e SMTP server that PHP can connect to.

Knowing SMTP server: SMTP is the acronym for Simple Mail Transfer Protocol, and an SMTP server is the machine that runs this protocol and sends out the mail. Running the protocol essentially means running a program such as Sendmail or Qmail if you're on a non-Windows machine. On Windows, the SMTP Service that is part of the Windows NT Service Pack or built in to the Windows 2000 operating system is typically the one running.

• "How can a server be available if it's not currently being run?" you might ask. Well, if that machine is connected to the Internet via a dial-up connection (or DSL or cable), you can use your ISP's outgoing mail server. For example, if your development machine is a Windows 98 box with a 56Kbps modem connected to the Internet via EarthLink, then you can use mail.earthlink.net as your SMTP server. Whatever e-mail client you use (Eudora, Outlook, Netscape Mail, and so on) as your outgoing mail server will also function within your PHP code as your SMTP server. The trick is making PHP aware of this little fact.

• The program to be used is defined by the configuration settings in the php.ini file.

Installation: The mail functions are part of the PHP core. There is no installation needed to use these functions.

• Runtime Configuration: The behavior of the mail functions is affected by settings in the php.ini file. In the php.ini master configuration file located in wamp icon, there are a few directives that need to be set up so that the mail() function works properly.

The options you want to check are:

• SMTP

• sendmail_from

• sendmail_path


• If you are not using Windows, the sendmail_path directive is all you need to worry about.

• If you're on Linux or a Unix variant, sendmail_path should be something like:

sendmail_path = /usr/sbin/sendmail.

• Or, if you're using Qmail:

sendmail_path = /var/qmail/bin/sendmail

• In this directive, you can also set configuration flags to specify queuing options or to explicitly set the Return-Path header, such as:

sendmail_path = /usr/sbin/sendmail -t -fyou@yourdomain.com

• As a non-Windows user, that's all you have to do. If you are using Windows, you have a little more work to do. You'll want to look at the values for SMTP and sendmail_from. Don't get confused by the use of sendmail in the name of the sendmail_from directive. Although you're not using the program called Sendmail on Windows, it's just the name of the directive. Don't sweat it.

• In your phpinfo() results, look at the default values for SMTP and sendmail_from--they should be either blank or contain dummy values. You'll want to change these to be meaningful for your system.

• If you are indeed running an SMTP server on that machine, your entry in php.ini will look like this:

SMTP = localhost

• However, if you are going to use the outgoing mail server of your ISP (in this example, EarthLink), the entry in php.ini would look like this:

SMTP = mail.earthlink.net

• You can also use an IP address instead of the name, since the machine cannot differentiate between these two entries.

• The second configuration directive is sendmail_from, and this is the e-mail address used in the From header. It can be overwritten in the mail script itself but normally operates as the default value. Here's what the configuration would look like with youraddress@yourdomain.com obviously standing in for your own address.

sendmail_from = youraddress@yourdomain.com

• After making these configuration changes, restart the Web server and use the phpinfo() function to verify that the changes have been made. When that's done, you're ready to send some e-mail using PHP.

Mail configuration options:

Name         Default         Description                 Changeable

SMTP        "localhost"      Windows only:               PHP_INI_ALL
                                        The DNS name or
                                        IP address of the
                                        SMTP server

smtp_port    "25"              Windows only: The        PHP_INI_ALL

                                        SMTP port number.
                                        Available since PHP
                                        4.3
sendmail_from  NULL     Windows                       PHP_INI_ALL
                                       only: Specifies the
                                      "from" address to be
                                       used in email sent
                                       from PHP
sendmail_path  NULL     Unix systems only:          PHP_INI_SYSTEM
                                       Specifies where the
                                       sendmail program can
                                       be found (usually /usr/
                                       sbin/sendmail or /usr/
                                       lib/sendmail)



Syntax: mail(to,subject,message,headers,parameters)

Parameter Description:

to: Required. Specifies the receiver / receivers of the email

subject: Required. Specifies the subject of the email. Note: This parameter cannot contain any newline characters

message: Required. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters

headers: Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)

parameters: Optional. Specifies an additional parameter to the sendmail program



PHP Simple E-Mail

• The simplest way to send an email with PHP is to send a text email.

• In the example below we first declare the variables ($to, $subject, $message, $from, $headers), then we use the variables in the mail() function to send an e-mail:

<?php

$to = "someone@example.com";

$subject = "Test mail";

$message = "Hello! This is a simple email message.";

$from = "someonelse@example.com";

$headers = "From: $from";

mail($to,$subject,$message,$headers);

echo "Mail Sent.";

?>

• Part of what makes the PHP mail() function is so simple is its lack of flexibility. Most importantly and frustratingly, the stock mail() does not usually allow you to use the SMTP server of your choice, and it does not support SMTP authentication, required by many a mail server today, at all.

• Fortunately, overcoming PHP's built-in shortcomings need not be difficult, complicated or painful either. For most email uses, the free PEAR Mail package offers all the power and flexibility needed, and it authenticates with your desired outgoing mail server, too. For enhanced security, secure SSL connections are supported.

• This does much the same as using mail(), with the exception that it has slightly smarter address and header handling - rather than taking a string of "header: value\r\nheader: value", it takes an array where the keys are the header names and the values are the header values. Similarly, you can send the same email to lots of people by passing an array of email addresses rather than just one.

Installing PEAR packages on WAMP

• The WAMP installation installs PHP, and at the same time installs the basic PEAR framework. There is a directory called PEAR inside whatever folder contains PHP – on my particular installation the structure is C:\wamp\bin\php\php5.2.9-2\PEAR. Taking a peek inside the PEAR folder will reveal it populated with the basic framework for PEAR. Most of this you can ignore – I’m not going to detail installing this here – that seems to be well covered. I just couldn’t find out how to actually enable the damn packages when I started, so I hope this is useful!

• Move to the directory where WAMP Server or PHP is installed using the command prompt. For example C:\wamp\bin\php\php5.2.9-2\>

• Then run "go-pear.bat" file for complete installation of PEAR.

• Reply to “Are you installing a system-wide PEAR or a local copy?” with “local”. When prompted, set each directory to the following scheme (note: the php version may differ):

1. Installation base ($prefix) : C:\wamp\bin\php\php5.3.0

2. Temporary directory for processing : C:\wamp\bin\php\php5.3.0\tmp

3. Temporary directory for downloads : C:\wamp\bin\php\php5.3.0\tmp

4. Binaries directory : C:\wamp\bin\php\php5.3.0

5. PHP code directory ($php_dir) : C:\wamp\bin\php\php5.3.0\pear

6. Documentation directory : C:\wamp\bin\php\php5.3.0\pear\docs

7. Data directory : C:\wamp\bin\php\php5.3.0\pear\data

8. User-modifiable configuration files directory : C:\wamp\bin\php\php5.3.0\pear\cfg

9. Public Web Files directory : C:\wamp\www

10. Tests directory : C:\wamp\bin\php\php5.3.0\pear\tests

11. Name of configuration file : C:\wamp\bin\php\php5.3.0\pear.ini

12. Path to CLI php.exe : C:\wamp\bin\php\php5.3.0\.

• Edit php.ini file and include the path to pear(include_path = “.;C:\wamp\bin\php\php5.2.9-2\includes;C:\wamp\bin\php\php5.2.9-2\PEAR;e:\wamp\bin\php\php5.2.9-2\PEAR\Mail") and also edit ini file extension and set extension=php_openssl.dll to enable openssl.

• Now – it is CRUCIAL that there are NO spaces after or before the semi-colons that separate paths in this string. If there are, quite simply, PEAR will not work. Simple as that – any include path after such a space will NOT be searched by PHP.

• To enable extension=php_openssl.dll, remove semicolon(;) from ;extension=php_openssl.dll in php.ini.

• Once you have modified the PHP.INI file, save it and restart your WAMP installation.

• Change the Windows PATH environment variable to include c:\wamp\bin\php\php5.2.9-2 (in Windows Vista: Start->Control Panel->System and Maintenance->System->Advanced System Settings->Environment Variable. Edit the PATH system variable and add c:\wamp\bin\php\php5.2.9-2). Now start a Windows command prompt and type pear. It will list all the pear commands. pear list will list all PEAR packages current installed. Use pear install -o <package> to install a package ( -o will install required dependencies).

• Then run following commands:

• php5.2.9-2\>pear list (this command will list all the installed pear packages)

• php5.2.9-2\>pear download Mail (A zip file will be downloaded)

• php5.2.9-2\>pear install Mail

• php5.2.9-2\>pear install -a Net_SMTP(-a switch for installing all dependencies)

• Then go to the mail.php file in C:\wamp\bin\php\php5.2.9-2\PEAR\Mail\mail.php and add this line require_once "C:\wamp\bin\php\php5.2.9-2\PEAR\Mail.php";(If not added it shows error that class Mail cannot be found )

• Then go to the smtp.php file in C:\wamp\bin\php\php5.2.9-2\PEAR\Mail\smtp.php and edit this line require_once “Net\SMTP.php”; to require_once "C:\wamp\bin\php\php5.2.9-2\PEAR\Net\SMTP.php ";(If not added it shows error that class Net\SMTP cannot be found ).

• Also to SMTP.php file in C:\wamp\bin\php\php5.2.9-2\PEAR\Net\SMTP.php and edit this line require_once “PEAR.php” to "C:\wamp\bin\php\php5.2.9-2\PEAR\PEAR.php";(If not added it shows error that class PEAR.php cannot be found )

• Then go to the Socket.php file in C:\wamp\bin\php\php5.2.9-2\PEAR\Net\Socket.php and edit this line require_once “PEAR.php” to require_once "C:\wamp\bin\php\php5.2.9-2\PEAR\PEAR.php";(If not added it shows error that class PEAR.php cannot be found ).

• A note: If you are using php 5.3 then you might get a problem when installing pear. It will say that the command cannot be found... To overcome this you have to download go-pear.phar file and save in with that name in the php5.3.0 directory.

• Once done installing you can go straight away with the program. Here is the simple mail program that sends mail from php using SMTP

<?php

include "C:\wamp\bin\php\php5.2.9-2\PEAR\Mail\mail.php";

$from="xxx@gmail.com"; //Sender Mail Address

$to= "yyy@yahoo.co.in";// Recepient mail address

$subject = "Hi!";

$body = "Hi,\n\nHow are you?";

$host = "ssl://smtp.gmail.com"; //smtp server

$port = "465";

$username = "xxx@gmail.com";

$password = "";// Type your Password Here

$headers = array ('From' => $from,'To' => $to,'Subject' => $subject);

$smtp = Mail::factory('smtp',array ('host' => $host,'port' => $port,'auth' => true,'username' => $username,'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {

echo( $mail->getMessage());

}

else {

echo("Message successfully sent!");

}

?>

• The Mail.php file is the PEAR::Mail script, so it needs to be included before any PEAR::Mail functions are used. Line two creates a default instance of PEAR::Mail - the parameter "mail" is passed in so that PEAR::Mail will use PHP's mail() function to send the email. If you pass in "sendmail", it will send direct via the sendmail program (Unix only). Mail::factory()

Mail::factory() – creates a mailer instance

Synopsis: require_once 'Mail.php';

object &factory ( string $backend , array $params = array() )

Description: Creates a instance of a backend-specific mailer class.

Parameter

string $backend - the name of the backend "smtp" , "sendmail"

array $params - a array of backend specific parameters.

List of parameter for the backends

 sendmail (for unix only)

 $params["sendmail_path"] - The location of the sendmail program on the filesystem. Default is /usr/bin/sendmail .

 $params["sendmail_args"] - Additional parameters to pass to the sendmail. Default is -i .

 smtp

 $params["host"] - The server to connect. Default is localhost .

 $params["port"] - The port to connect. Default is 25 .

 $params["auth"] - Whether or not to use SMTP authentication. Default is FALSE.

 $params["username"] - The username to use for SMTP authentication.

 $params["password"] - The password to use for SMTP authentication.

 Return value: object - a specific Mail instance or a PEAR_Error object on failure.

• from: the email address from which you want the message to be sent.

• to: the recipient's email address and name.

No comments:

Post a Comment