Sending email in php using phpmailer class with and without attachment

In this tutorial I am going to discuss about sending email in php using one of most popular library called phpmailer.

We can also send mail using default php mail() function then why we need to use phpmailer, the answer is it is well organised opps based library specially written to handle any type of mail features in php like normal html email, email with attachments.


First download latest phpmailer class.
https://github.com/PHPMailer/PHPMailer

Sending html email

<?php
require_once('class.phpmailer.php'); 
$mailObj = new PHPMailer(true);  
$to = "[email protected]"; 
$subject = "Test mail"; 
$msg = "This is simple test mail sending by phpmailer class"; 
$mailObj->AddAddress($to, 'Rohit');
$mailObj->SetFrom('[email protected]', 'Example');
$mailObj->AddReplyTo('[email protected]', 'Reply-Example');
$mailObj->Subject = $subject;
$mailObj->AltBody = 'To view the message, please use an HTML compatible email viewer!'; 
$mailObj->MsgHTML($msg);
$mailObj->Send();
if(!$mailObj->Send()) {
echo "There was an error sending the e-mail";
} else {
echo "E-Mail has been sent successfully";
}
?>

Sending email with attachments

<?php 
require_once('class.phpmailer.php'); 
$mailObj = new PHPMailer();
$msg = "<div>";
$msg .= " Hello PHP Mailer";
$msg .= "Please find attached images</p>";
$msg .= "Regards,";
$msg .= "Rohit ";
$msg .= "</div>" ;
 

$mailObj->AddAddress("[email protected]", "My Public Notebook");
$mailObj->Subject = "Test mail with attachement";
$mailObj->MsgHTML($msg);
$mailObj->AddAttachment("image-1.jpg");
$mailObj->AddAttachment(("image-2.jpg");
if(!$mailObj->Send()) {
echo "There was an error sending the e-mail";
} else {
echo "E-Mail has been sent successfully";
}
?>

Configure SMTP settings

You can also configure SMTP settings, You just need to add below lines in above codes.

$mailObj->isSMTP();                                      
$mailObj->Host = 'smtp1.example.com;smtp2.example.com';  
$mailObj->SMTPAuth = true;                               
$mailObj->Username = '[email protected]';                 
$mailObj->Password = 'secret';                           
$mailObj->SMTPSecure = 'tls';                            
$mailObj->Port = 587;

Hope this tutorial will help you to send email in php with or without attachments.

If you like this post please don’t forget to subscribe My Public Notebook for more useful stuff.