Sending email in php using phpmailer class with and without attachment

0 82

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'); // include your phpmailer class 
$mailObj = new PHPMailer();
$msg = "<div>";
$msg .= " Hello PHP Mailer";
$msg .= "Please find attached images</p>";
$msg .= "Regards,";
$msg .= "Rohit ";
$msg .= "</div>" ;
 
//  Required configurations for sending HTML with attachement
$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();                                      // Set mailer to use SMTP
$mailObj->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
$mailObj->SMTPAuth = true;                               // Enable SMTP authentication
$mailObj->Username = '[email protected]';                 // SMTP username
$mailObj->Password = 'secret';                           // SMTP password
$mailObj->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$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.

Leave A Reply

Your email address will not be published.