Requirements
You need for this PHPMailer code example a PHP5 enabled web host (I did tests only on Linux), the port 465 need to be open and of course you need a GMail or Google Apps account.
PHPMailer tutorial for GMail and Google Apps
GMail account or setup your domain for Google applications.
Download a recent version of PHPMailer (I’m using the version 5.02)
Check with your web hosting provider that port 465 (TCP out) is open, if not ask him to open that port
Include the PHPMailer class file: require_once('phpmailer/class.phpmailer.php');
Create those two constant variables to store your GMail login and password. Use the login for your Google Apps mail account if you have one.
define('GUSER', 'you@gmail.com'); // GMail username
define('GPWD', 'password'); // GMail password
Use the following function to send the e-mail messages (add the function in one of your included files):
function smtpmailer($to, $from, $from_name, $subject, $body) {
global $error;
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->Username = GUSER;
$mail->Password = GPWD;
$mail->SetFrom($from, $from_name);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);
if(!$mail->Send()) {
$error = 'Mail error: '.$mail->ErrorInfo;
return false;
} else {
$error = 'Message sent!';
return true;
}
}
Call the function within your code:
smtpmailer('to@mail.com', '', 'from@mail.com', 'yourName', 'test mail message', 'Hello World!');
Use this more “advanced” usage inside your application:
if (smtpmailer('to@mail.com', 'from@mail.com', 'yourName', 'test mail message', 'Hello World!')) {
// do something
}
if (!empty($error)) echo $error;
No comments:
Post a Comment