How to use PHPmailer in a function in WordPress

I have a function in the WordPress functions.php file that searches for a condition in user meta and sends an email to a user based on what it finds. I currently use wp_mail() to send the email, and that works. However, I want to use the included PHPMailer class to do this so that I can send the messages via SMTP.

I thought I had a solution here: https://codex.wordpress.org/Plugin_API/Action_Reference/phpmailer_init, however, this seems to only apply to system generated messages, not for custom messages.

At this point I’m just guessing, but I tried this, with no luck (WP stops loading right at this point, no error message):

function my_function() {
    //if things are found send an email
    global $phpmailer;
    $phpmailer->IsSMTP();
    $phpmailer->Host="smtp.google.com";
    $phpmailer->Port="587";
    $phpmailer->SMTPSecure="tls";
    $phpmailer->SMTPAuth = true;
    $phpmailer->Username="something@gmail.com";
    $phpmailer->Password = '11111111';

    $phpmailer->addAddress('joe@example.com', 'Joe User');
    $phpmailer->setFrom('from@example.com', 'Mailer');
    $phpmailer->addReplyTo('info@example.com', 'Information');
    $phpmailer->isHTML(true);
    $phpmailer->Subject="Here is the subject";
    $phpmailer->Body    = 'This is the HTML message body <b>in bold!</b>';              
    $phpmailer->send();
    // Email sent; function over
}

FYI, I call this function in the header. I’m not adding it as an action because I want to control where it is used.

Is there a way to access the PHPMailer class directly from my function? I suppose i could load PHPMailer separately, but that seems silly.

2 Answers
2

require ‘wp-includes/class-phpmailer.php’; fixed my problem, but I used a code to create a pdf and then send it in the same way.

Leave a Comment