Showing posts with label phpmailer. Show all posts
Showing posts with label phpmailer. Show all posts

Saturday, July 20, 2013

Send HTML and TEXT emails with PHP, PHPMailer, Attachments

If you are developing applications using PHP and you need to send email you can use the PHPMailer() class in PHP. Using a publicly available SMTP server to send the email is much easier than trying to setup your own email server. The following code snippet shows the various settings for the mailer. The code assumes that you have PHP 5.x version and you have class.phpmailer.php file in the include directory. Google uses ssl for the smtp connection. In order for this example to work with google smtp server, you need to enable ssl in your php.ini file by adding a line that says extension=php_openssl.dll

If you are not sure of the exact location of the php.ini file and you are using xampp, you can find the location of the php.ini file by navigating to http://localhost/xampp/phpinfo.php on your browser and look for the text "Loaded Configuration File". Once you find the file, edit it and look for the text "extension=php_openssl.dll". If the text is not found in your file, add a new line at the end of the file with the above text.
 
<?php
require 'Mail/class.phpmailer.php'; 
$mail = new PHPMailer; 
$mail->IsSMTP(); // Set mailer to use SMTP 
$mail->Host       'smtp.gmail.com'// Specify main and backup server 
$mail->SMTPAuth   true// Enable SMTP authentication 
$mail->Username   'username@gmail.com'// SMTP username 
$mail->Password   'XXXXXX'// SMTP password 
$mail->SMTPSecure 'ssl'// Enable encryption, 'ssl', 'tls' etc...
$mail->Port       465// or 587 
$mail->Timeout    60// Message sent timeout 
$mail->From       'username@gmail.com'; 
$mail->FromName   'Pritom K Mondal';

// Add a recipient
$mail->AddAddress('username@gmail.com''Pritom GMAIL'); 
$mail->AddAddress('username@yahoo.com''Pritom YAHOO');
$mail->AddAddress("username@domain.com""Pritom Domain"); 

$mail->AddReplyTo('username@gmail.com''Reply To');
$mail->AddCC('username@gmail.com'); 
$mail->AddBCC('username@gmail.com'); 
$mail->WordWrap 50// Set word wrap to 50 characters 

// Add attachments
$mail->AddAttachment('C:\\pritom.zip'); 
$mail->AddAttachment('C:\\Contact List.csv''pritom.csv'); // Optional name 

$mail->IsHTML(true); // Set email format to HTML 
$mail->Subject 'Here is the subject'; 
$mail->Body    'This is the HTML message body <b>in bold!</b>';
$mail->AltBody 'This is the body in plain text for non-HTML mail clients';

if (!
$mail->Send()) {
    echo 
'Message could not be sent.';
    echo 
'Mailer Error: ' $mail->ErrorInfo;
    exit;
}

echo 'Message has been sent'; 
?>

Download PHPMailer from here
https://github.com/Synchro/PHPMailer