Scroll to top
© 2020, Empty Code | All Rights Reserved
Share

Sending Emails In PHP Using PHP Mailer Library without Composer


Rahul Kumar Sharma - May 15, 2020 - 0 comments

PHP Mailer is the most popular library for sending emails from PHP. It is used by many open-source projects like WordPress, Drupal, Joomla and more. The Packages includes integrated SMTP Support which can send emails without a local mail server.

Features

  • Send emails with multiple To, CC, BCC, and Reply-to addresses
  • Add attachments, including inline
  • SMTP authentication with LOGIN, PLAIN, CRAM-MD5, and XOAUTH2 mechanisms over SSL and SMTP+STARTTLS transports
  • Validates email addresses automatically
  • DKIM and S/MIME signing support
  • Compatible with PHP 5.5 and later

How to Configure

  • Download PHPMailer from Github.
  • Extract the zip in Project Folder.
  • Create a new file in PHP Mailer folder as mailconfig.php and copy the below code
<?php
require $_SERVER['DOCUMENT_ROOT'].'/PHPMailer/src/Exception.php';
require $_SERVER['DOCUMENT_ROOT'].'/PHPMailer/src/PHPMailer.php';
require $_SERVER['DOCUMENT_ROOT'].'/PHPMailer/src/SMTP.php';

date_default_timezone_set('Asia/Kolkata');
$mail = new PHPMailer\PHPMailer\PHPMailer();;
$mail->isSMTP(); // Set PHPMailer to use SMTP.
$mail->SMTPAuth = true; // //Set this to true if SMTP host requires authentication to send email
$mail->SMTPSecure = 'tls'; ////If SMTP requires TLS encryption then set it
$mail->Host = 'YOUR HOST'; // //Set SMTP host name  
$mail->Port = 465; // //Set TCP port to connect to 

// Provide username and password  
$mail->Username = 'YOUR EMAIL/USERNAME';
$mail->Password = 'YOUR PASSOWORD';

$mail->setFrom('YOUR EMAIL', 'YOUR NAME');
?>
  • Include the mailconfig.php and call the sendMail() function.
include ('ProjectFolder/PHPMailer/mailconfig.php');
sendMail('Admin', 'admin@gmail.com');

function sendMail($name, $email){
    require "PHPMailer/mail-config.php";
  
    $mail->addAddress($email, $name); 
    $mail->isHTML(true); 
    $mail->Subject = 'Dummy Email | PHP Mailer';
    $mail->Body = 'This is dummy mail which is sent from PHP Mailer';
  	if($mail->send()){
    	echo "Message has been sent successfully";
	} 
	else{
    	echo "Mailer Error: " . $mail->ErrorInfo;
    }
}

Conclusion

If you are looking for sending mails from PHP then PHP Mailer is best rated library in GitHub else there are many third party services for sending emails like Sendgrid, Mandrill etc which helps to send emails directly. The Alternatives of PHP Mailer are Zend Mail, Swiftmailer, etc.

Related posts

Post a Comment

Your email address will not be published. Required fields are marked *