How to send an email via SMTP Server in PHP using PHPMailer


Jun 23, 2021

PHPMailer is a open source library and used to send emails via PHP code from a web server. The easiest way to send email in PHP with SMTP.

Basically, PHP mail() function is used to send email from the PHP script. but there are many other cases where the mail() function may cause issues on sending an email and fails to deliver mail to the recipient. PHPMailer simplifies the process of sending emails and it is very easy to use. Various configuration options of the PHPMailer library allow you to configure and customize the email sending functionality as per your requirement. You can send a text message or HTML email with single or multiple attachments using PHPMailer library.

Download PHPmailer library

SMTP Server Configuration:
Specify main SMTP server host ($mail->Host)
SMTP username ($mail->Username)
SMTP password ($mail->Password)
and TCP port to connect to ($mail->Port) as per your SMTP server credentials.


require_once('./phpmailer/class.phpmailer.php');
  
try {   

	$mail = new PHPMailer();
	$mail->IsSMTP();
	$mail->SMTPDebug = 2;
	$mail->SMTPAuth = true;
	$mail->SMTPSecure = 'ssl';
	$mail->Host = "HOST";
	$mail->Port = 465;
	$mail->IsHTML(true);
	$mail->Username = "abc@abc.com";
	$mail->Password = "123";
	$mail->setfrom("YOUR-EMAIL");
	$mail->Subject = 'Test subject';
	$mail->FromName = 'FROM NAME';
   
	$mail->Body = '

Its Works Now!

'; $mail->AddAddress('TO-EMAIL'); if($mail->send()) echo "Mail has been sent successfully!"; else echo "Mail not sent"; } catch (Exception $e) { echo "Message could not be sent. Error: ".$mail->ErrorInfo; }

Copyright 2018. All rights are reserved