Tuesday, March 18, 2014

How to send a mail using PHPMailer

It is really very easy to use PHPMailer rather than use of PHP default mail() function.
  • Ease of use.
  • Much flexible.
  • Can have user authentication which php mail() doesn't have.

Before start, you need to download PHPMailer zip source files. You can download that freely fromthe internet (https://github.com/PHPMailer/PHPMailer).

Then you will require files  class.phpmailer.php and class.smtp.php from the downloaded source files.

In class.phpmailer.php modify required fields like;
username, password, etc.. 

In class.smtp.php modify required fields like;
port

Sample mail code :
IsSMTP();  // telling the class to use SMTP
$mail->Host     = "mail.xxx.com"; // SMTP server

$mail->From     = "chathuryad@xxxx.com";
$mail->AddAddress("chathuryad@xxxx.com");

$mail->Subject  = "First PHPMailer Message";
$mail->Body     = "Hi! \n\n This is my first e-mail sent through PHPMailer.";


if(!$mail->Send()) {
  echo 'Message was not sent.';
  echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
  echo 'Message has been sent.';
}
?>

If you try to send mail in a loop sometimes it will send the mail for everyone. So after sending the mail it would be a good practice to remove the address from the php mail list.

$mail->ClearAllRecipients( );




No comments:

Post a Comment