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 = "hi@iamrohit.in"; $subject = "Test mail"; $msg = "This is simple test mail sending by phpmailer class"; $mailObj->AddAddress($to, 'Rohit'); $mailObj->SetFrom('from@example.com', 'Example'); $mailObj->AddReplyTo('reply-to@example.com', '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("hi@iamrohit.in", "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 = 'user@example.com'; // 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.