This article discusses several methods for sending e-mail messages from PHP scripts.
The easiest way to send an e-mail message in a PHP script is to use the built-in PHP mail() function. The PHP mail() function has several required parameters:
Additionally, there are two optional parameters that you should use to set the “From” e-mail address. It is important to set the “From” address correctly so replies, bounce notifications, and other messages return to the appropriate address. If the “From” address is not set, messages sent from your web site display a return address of [email protected], where example.com represents the A2 Hosting server where your web site is hosted.
The following sample code demonstrates how to send an e-mail message with the “From” address set correctly. It also demonstrates how to set the Content-Type header so international (Unicode) characters are displayed correctly. In your own code, replace [email protected] with the intended message recipient, and [email protected] with the return e-mail address:
<?php mail("[email protected]", "This is the message subject", "This is the message body", "From: [email protected]" . "\r\n" . "Content-Type: text/plain; charset=utf-8", "-f[email protected]"); ?>
Although the PEAR Mail class requires more configuration than the PHP mail() function, it is also much more powerful. With the PEAR Mail class, you can send e-mail messages using SMTP authentication, and specify many other e-mail settings. To do this, follow these steps:
<?php require 'Mail.php'; // Define basic e-mail parameters: $recipient = '[email protected]'; $headers['From'] = '[email protected]'; $headers['Reply-to'] = '[email protected]'; $headers['To'] = '[email protected]'; $headers['Subject'] = 'This is the message subject'; $headers['Date'] = date('r'); $headers['Message-Id'] = '<' . uniqid() . '@example.com>'; $headers['Content-Type'] = 'text/plain; charset=utf-8'; $body = 'This is the message body'; // Define SMTP authentication parameters: $smtp_params['host'] = 'server_name'; $smtp_params['auth'] = true; $smtp_params['username'] = 'username'; $smtp_params['password'] = 'password'; // Create a Mail class instance with the above parameters, and then send the message: $message = Mail::factory('smtp', $smtp_params); $message->send($recipient, $headers, $body); ?>
PHPMailer is a popular e-mail implementation that provides another way to send messages from PHP scripts. It supports many features, including SMTP authentication, and makes formatting e-mail messages correctly much easier.
To learn to install PHPMailer with this article.
Subscribe to receive weekly cutting edge tips, strategies, and news you need to grow your web business.
No charge. Unsubscribe anytime.