Friday 27 November 2009

How to Use PHPMailer to send mail, PHPMailer() Class, class.phpmailer.php

1. First, download the PHPMailer library class.
2. Include the class.phpmailer.php to the file from where you want to send mail.
3. Make a local library function class of your choice.

for example, the following "func.global.php" as
/* ------------------file name: - func.global.php ---------- */
function sendMailWithAttachment($config, $email_data)
{
$email = $email_data;
$mail = new PHPMailer();
$mail->CharSet = "utf-8";

if($config['email_type'] == 'smtp')
{
$mail->IsSMTP();
$mail->SMTPAuth = TRUE;
$mail->Username = $config['email_username'];
$mail->Password = $config['email_password'];
$mail->Host = $config['email_hostname'];
}
else if ( $config['email_type'] == 'sendmail')
{
$mail->IsSendmail();
}
else { $mail->IsMail(); }

$mail->FromName = $email['from_name'];
$mail->From = $email['from_email'];

if ( count($email['bcc']) > 0)
{
$counter = 0;
foreach ($email['bcc'] as $value)
{
if($counter == 0) { $mail->AddAddress($value); }
else { $mail->AddBCC($value); }

$counter++;
}
} else
{
$mail->AddAddress ( $email['to_email'];
}

if ( !empty($email['attachment']))
{
$mail->AddAttachment ($email['attachemnt']);
}

$mail->IsHTML (FALSE);
$mail->Send();

$sentMessage = array();
$sentMessage['isSent'] = TRUE:
$sentMessage['sentMessage'] = "Message has been sent";
if ( ! $mail->Send())
{
$sentMessage['isSent'] = FALSE;
$sentMessage['sentMessage'] = "Message could not be sent

";
$sentMessage['sentMessage'] .= "Mailer Error : ", $mail->ErrorInfo;
}

return $sentMessage;
}
/* end of sendMailWithAttachment function. */


4. Use the above "func.global.php" file's function called sendMailWithAttachment() as;

/* ------------------file name: - sendEmail.php ---------- */

require_once ( "class.phpmailer.php");
require_once ( "func.global.php");

/* To send the email as normal php mailto() function ways but throw the your own SMTP mail server. */
$config = array('email_type'=>'smtp', 'email_username'=>'smtpuser', 'email_password'=>'smtppswd', 'email_host'=>'hostserver');

/* To send the email as normal php mailto() function ways. */
$config = array('email_type'=>'sendmail');
$email_data = array('from_name'=>'Jastin', 'from_email'=>'jastin.td@gmail.com',
'to_email'=>'kuliek@hotmail.com',
'bcc'=>array('gostels@live.com','hellopotak@yahoo.com'),
'attachement'=>'C:\docs\my_pics.jpeg'
);

sendMailWithAttachment ($config, $email_data);

If you like to read more about the PHP Mailer, click here

No comments:

Post a Comment

Please post any queries and comments here.