Skip to content
Advertisement

How to include PHPmailer in functions.php properly (WordPress)

I’m trying to include PHPmailer in functions.php

my code:

add_action('wp_ajax_nopriv_test_mailer', 'test_mailer');

function test_mailer () {

try {

    require_once(get_template_directory('/includes/mail/PHPMailer.php'));
    require_once(get_template_directory('/includes/mail/Exception.php'));

    $mail = new PHPMailer(true);                              // Passing `true` enables exceptions

    //Server settings
    $mail->SMTPDebug = 4;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = 'test@gmail.com';                 // SMTP username
    $mail->Password = 'dummypassword!';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('test@gmail.com', 'Mailer Test');
    $mail->addAddress('john.doe@gmail.com', 'John User');     // Add a recipient
    $mail->addReplyTo('test@gmail.com');

    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Here is the subject testing';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $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;
}

wp_die();

}

I also tried to put require_once out of the try catch still the same error here is the snippet about the error

“PHP Fatal error: Uncaught Error: Class ‘PHPMailer’ not found”

I use betheme template and I stored the files PHPmailer in betheme/includes/mail.

Advertisement

Answer

As BA_Webimax pointed out, you should be using WordPress’ built-in email functions, though due to WP’s reliance on outdated PHP versions, you will end up using a very old version of PHPMailer with it.

Back to your current problem: It’s not your require_once statements that are failing, it’s that you have not imported the namespaced PHPMailer classes into your namespace. Add these at the top of your script:

use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
use PHPMailerPHPMailerSMTP;

Alternatively, use the FQCN when creating your instance:

$mail = new PHPMailerPHPMailerPHPMailer;

Note that this applies to the Exception class too, so you’d need to say:

catch (PHPMailerPHPMailerException $e) {
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement