2012年12月3日 星期一

Set SMTP example for PHPMailer


The example is how to send mail via Gmail smtp server.

1. You need has Gmail account and set POP enable in mail setting.
2. You need to enable openssl function in php.ini or server is support openssl.
    extension=php_openssl.dll
3. Use the example in phpmailer.php and modify your mail information as below.

<?php
require_once('../class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded

$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch

$mail->IsSMTP(); // telling the class to use SMTP

try {
  $mail->Host       = "smtp.gmail.com"; // SMTP server
  $mail->SMTPDebug  = 2;                     // enables SMTP debug information (for testing)
  $mail->SMTPAuth   = true;                  // enable SMTP authentication
  $mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
  $mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
  $mail->Port       = 465;                   // set the SMTP port for the GMAIL server
  $mail->Username   = "your@gmail.com";  // GMAIL username
  $mail->Password   = "xxxxx";            // GMAIL password
  $mail->AddReplyTo('you@gmail.com', 'First Last');
  $mail->AddAddress('to@com.tw', 'John Doe');
  $mail->SetFrom('you@gmail.com', 'First Last');
  $mail->AddReplyTo('you@gmail.com', 'First Last');
  $mail->Subject = 'PHPMailer Test Subject via mail(), advanced';
  $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
  $mail->MsgHTML(file_get_contents('contents.html'));
  $mail->AddAttachment('images/phpmailer.gif');      // attachment
  $mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
  $mail->Send();
  echo "Message Sent OK</p>\n";
} catch (phpmailerException $e) {
  echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
  echo $e->getMessage(); //Boring error messages from anything else!
}
?>

Also can use Microsoft Exchange server as SMTP.


<?php

ini_set('display_errors', 1);   # enable PHP error reporting
error_reporting(E_ALL);

require_once('../class.phpmailer.php');
$mail = new PHPMailer();

$mail->IsSMTP();  // telling the class to use SMTP
$mail->Host     = "Exchange server name"; // SMTP server
$mail->SMTPAuth = true;
$mail->Username = "Domain\account";
$mail->Password = "xxxx";

//$mail->SetLanguage("en", DIR_3RDPARTY."/phpmailer/language/");

$mail->From     = "From@com.tw";
$mail->FromName = "your name";
$mail->AddAddress("To@com.tw");

$mail->Subject  = "SMTP Test";
$mail->Body = "Hello World";

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

沒有留言:

張貼留言