Scroll to top
© 2022, Empty Code | All Rights Reserved

Sending Emails in PHP using PHP Mailer Library without Composer


Rahul Kumar Sharma - May 15, 2020 - 0 comments

To send emails in PHP, It’s always recommended to use a popular library called PHP Mailer Library which enables SMTP Support with Authentication protects against header injection attacks, and much more which is far better than mail() function.

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. This Package 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 the Project Folder.
  • Create a new file in the 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 to send mails from PHP then PHP Mailer is the best-rated library on GitHub else there are many third-party services for sending emails like Sendgrid, Mandrill etc which help to send emails directly. The Alternatives to PHP Mailer are Zend Mail, Swiftmailer, etc.

Related posts

Post a Comment

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