php

Send mail in PHP using PHPMailer

Code and description to send mail in PHP using the PHPMailer package.

<?php
    //SEND EMAIL VIA PHPMAILER PACKAGE
    // INSTALLATION - composer require phpmailer/phpmailer

    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\SMTP;
    use PHPMailer\PHPMailer\Exception;
    
    // Load Composer's autoloader
    require 'vendor/autoload.php';
    
    // CREATE MAILER INSTANT and PASS `true` TO ENABLE EXCEPTIONS
    $mail = new PHPMailer(true);
    
    try {
        //SERVER SETTINGS
        $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      // ENABLE DEBUG
        $mail->isSMTP();                                            // SEND MAIL USING SMTP
        $mail->Host       = 'smtp.server.com';                      // SMTP HOST NAME
        $mail->SMTPAuth   = true;                                   // ENABLE SMTP AUTHENTICATION
        $mail->Username   = '[email protected]';                      // SMTP USERNAME
        $mail->Password   = 'password';                             // SMTP PASSOWRD
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // ENABLE TLS encryption;
        $mail->Port       = 587;                                    // TCP PORT
    
        //RECIPIENTS
        $mail->setFrom('[email protected]');
        $mail->addAddress('[email protected]', "name");               //NAME IS OPTIONAL
        $mail->addReplyTo('[email protected]', 'Information');
        $mail->addCC('[email protected]');
        $mail->addBCC('[email protected]');
    
        // ATTACHMENT
        $mail->addAttachment('path/to/file.zip');                   // Add attachments
        $mail->addAttachment('path/to/file.zip', 'file_name.jpg');  // file_name is optional
    
        // MAIL CONTENT
        $mail->isHTML(true);                                        // Set email format to HTML
        $mail->Subject = 'Here is the subject';
        $mail->Body    = '<div>Your HTML message <b>body</b> will be here</div>';
        $mail->AltBody = 'Place here plain text for no-HTML support mail clients';
    
        $mail->send();
        echo 'Mail sent successfully';
    } catch (Exception $e) {
        echo "Error while sending mail: {$mail->ErrorInfo}";
    }
?>

Here we are using PHPMailer composer package to send mail in PHP. You can install PHPMailer package in your package by

Adding below line in composer.json file

"phpmailer/phpmailer": "~6.1"

or Running below command

composer require phpmailer/phpmailer
Was this helpful?