Monday, September 26, 2011

Send emails via SMTP servers in PHP

The standard PHP mail() function is simple to use, but it doesn't support SMTP authentication on Linux. Therefore, I use Pear::Mail() instead. Before start, please make sure you have following packages installed on your computer/server: php-pear, php-mail. If not, install them by:
$ sudo aptitude install php-pear php-mail
After installation use following codes to send email:
require_once "Mail.php";
$recipients = "";
$headers["From"] = "";
$headers["To"] = "";
$headers["Subject"] = "Test message";
$mailmsg = "Hello, this is a test message";

/* SMTP server name, port, user/passwd */
$smtpinfo["host"] = "";
$smtpinfo["port"] = "25";
$smtpinfo["auth"] = true;
$smtpinfo["username"] = "username";
$smtpinfo["password"] = "password";

/* Create the mail object using the Mail::factory method */
$smtp = Mail::factory("smtp", $smtpinfo);
$mail = $smtp->send($recipients, $headers, $mailmsg);
Notes: replace "example" with the real domains, and put in your username and password. If you get an error message like this: Fatal error: Cannot instantiate non-existent class: net_smtp in
/usr/share/php/Mail/smtp.php on line 159
, please install Net_SMTP package by:
$ sudo pear install Net_SMTP

No comments:

Post a Comment