How To Setup PEAR Mail On Linux

PEAR mail is a package that you can to install to set up a mailing system for your website or application. Its really easy to install. I work on a Linux PC. So, for all the Linux developers out there, I can give you out the commands which you need to execute on the command line or the terminal. This will install PEAR mail on your system.

1) sudo apt-get install php-pear

2) sudo pear install mail

3) sudo pear install Net_SMTP

4) sudo pear install Auth_SASL

5) sudo pear install mail_mime

You might find some errors reported during the installation. But don't worry about them. It will work fine.

Now, once you have got your packages installed, you would be itching to see how the mailing system works. As for PHP, its really simple. The code snippets given below explain you how it actually works. If you have a little knowledge in PHP, it will not be hard to understand as to what is happening.

<?php

// This is bundled with the mail package and comes with the above installation.
require_once "Mail.php";

// The sender email address needs to be here.
$from = "sender@example.com";
// The recipient email address needs to be here.
$to = "recipient@example.com";
// The subject of the email is given here.
$subject = "<Your Subject>";
// The body of the email message to be conveyed is written here.
$body = "<Body of the Email message>";

// The SMTP server that you will use to send the emails.
$host = "mail.example.com";
// The username for the SMTP server.
$username = "smtp_username";
// The password for the SMTP server.
$password = "smtp_password";

// The headers are formed as an array here.
$headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject);

// This creates an instance of the Mail Factory with the required login credentials for the SMTP server. 
// The first argument tells the factory that the server is an SMTP server.
$smtp = Mail::factory('smtp', array ('host' => $host, 'auth' => true, 'username' => $username, 'password' => $password));

// This sends the mail to the intended recipient with the required headers and the body of the message.
$mail = $smtp->send($to, $headers, $body);
// If an error is reported during the mailing, the appropriate error message will be displayed.
if (PEAR::isError($mail)) {
   echo("<p>" . $mail->getMessage() . "</p>");
}

// If the mail is successfully sent, the success message will be shown.
else {
   echo("<p>Message successfully sent!</p>");
}

?>

Please make sure to read the comments given in the lines to ensure that your mail service works absolutely fine. I have put up comments at every possible place to guide you through. Hope, this would help you acheive your task.

Comments

Popular Posts