How to set SMTP programmatically

Assume we have blank WP site and we want to setup SMTP settings programmatically in our plugin or theme. What’s the easiest way to do it without changing core files?

3

First of all, if we take a look at implementation of wp_mail function, we will see that this function uses PHPMailer class to send emails. Also we could notice that there is hard coded function call $phpmailer->IsMail();, which sets to use PHP’s mail() function. It means that we can’t use SMTP settings with it. We need to call isSMTP function of PHPMailer class. And also we need to set our SMTP settings as well.

To achieve it we need to get access to $phpmailer variable. And here we come to phpmailer_init action which is called before sending an email. So we can do what we need by writing our action handler:

add_action( 'phpmailer_init', 'wpse8170_phpmailer_init' );
function wpse8170_phpmailer_init( PHPMailer $phpmailer ) {
    $phpmailer->Host="your.smtp.server.here";
    $phpmailer->Port = 25; // could be different
    $phpmailer->Username="your_username@example.com"; // if required
    $phpmailer->Password = 'yourpassword'; // if required
    $phpmailer->SMTPAuth = true; // if required
    // $phpmailer->SMTPSecure="ssl"; // enable if required, 'tls' is another possible value

    $phpmailer->IsSMTP();
}

And that’s all.

Leave a Comment