Send mail via PHP script using PHPMailer Print

  • 2

You can send an email using PHPMailer from your PHP script using SMTP authentication. To use PHPMailer classes, you need to download PHPMailer 6.5.3 class files from the following URL:

https://github.com/PHPMailer/PHPMailer

Once you download the zip file, you have to upload it to your hosting file manager and extract it. We suggest you set the extracted folder’s name as “PHPMailer”.

Following is the sample code to send an email from your PHP script using SMTP authentication. Please note that you have to change the below script as per your requirement.


<?php
//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';

//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);

Try
 {
    //Server settings
    $mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output
    $mail->isSMTP(); //Send using SMTP
    $mail->Host = 'smtp.domain.com'; //Set the SMTP server to send through
    $mail->SMTPAuth = true; //Enable SMTP authentication
    $mail->Username = [email protected]'; //SMTP username
    $mail->Password = 'Password'; //SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; //Enable implicit TLS encryption
    $mail->Port = 465; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

    //Recipients
    $mail->setFrom('[email protected]', ‘Name’);
    $mail->addAddress('[email protected]', ‘Name’); //Add a recipient
    $mail->addAddress('[email protected]'); //Name is optional
    $mail->addReplyTo('[email protected]', ‘Your Name’);
    $mail->addCC('[email protected]');
    $mail->addBCC('[email protected]');

    //Attachments Optional
    $mail->addAttachment('/var/tmp/file.tar.gz'); //Add attachments
    $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); //Optional name

    //Content
    $mail->isHTML(true); //Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body = 'This is the HTML message body in bold!';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';

catch (Exception $e) 
{
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>


Note: You should always verify your email address before sending an email campaign.



Was this answer helpful?

« Back

chat