Categories: PHP & Frameworks

How to send emails using PHPmailer and GMAIL SMTP

Here I have tried how to send PHPMailer with attachment using SMTP configuration. For SMTP Configuration we here used GMAIL Auth. You can be used any Auth like SMTP2GO, SendGrid.

Download PHPMailer library.

PHPMailer Sample Code

Copy paste the following code in your editor and save with any filename with extension “.php” and try in your live server or local server. But Make sure you have to connect with internet with proper Auth details

<?php
 
require_once('phpmailer/PHPMailerAutoload.php');
 
$mail = new PHPMailer();
$mail->CharSet =  "utf-8";
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->SMTPDebug = 1;  // Enable verbose debug output
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = "xxx@example.com"; //Your Auth Email ID
$mail->Password = "xxxxxx"; //Your Password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Host = "smtp.gmail.com"; // SMTP 
$mail->Port = "587"; // TCP port to connect to
 
$mail->setFrom('xxx@example.com', 'From Name');
$mail->AddAddress("abc@gmail.com" , "Recipient name"); // Add a recipient
 
$mail->addAttachment('path/file.png');         // Add attachments
 
$mail->Subject = "Subject Line";
$mail->Body = "<div style="font-weight: bold">Your Message or Content</div>";
$mail->ContentType = "text/html";
 
if($mail->Send()){
 $str = "OK"; 
}else{
 $str = "ERR"; 
}
 
//End PHPMailer Code Here
?>

 

Developer Diary

Share
Published by
Developer Diary

Recent Posts

Git Tag Cheat Sheet

Introduction Git tags are an essential feature of version control systems, offering a simple way…

2 months ago

Understanding Web Storage: Cookies, Local Storage

Introduction The methods that browsers employ to store data on a user's device are referred…

3 months ago

Setting up OpenVPN Access Server in Amazon VPC – AWS

Introduction A well-known open-source VPN technology, OpenVPN provides strong protection for both people and businesses.…

3 months ago

Enhance Error Tracking & Monitoring: Integrate Sentry with Node.js & Express.js

Introduction Integrating Sentry into a Node.js, Express.js, and MongoDB backend project significantly enhances error tracking…

3 months ago

Comparing Callbacks, Promises, and Async/Await in JavaScript

Introduction In the world of JavaScript development, efficiently managing asynchronous operations is essential. Asynchronous programming…

5 months ago

How To Secure Nginx with Let’s Encrypt on Ubuntu EC2 Instance

Introduction Let's Encrypt is a Certificate Authority (CA) that makes it simple to obtain and…

7 months ago