How to Use SMTP to Send Emails in WordPress

Publish: 2014-11-10 | Modify: 2019-10-30

Some hosting providers have disabled the mail() function, which prevents users from receiving emails for registration or password retrieval. Even if the mail() function is enabled, the chances of the sent emails ending up in the spam folder are very high. To solve this problem, using SMTP to send emails is a great solution.

Previously, I introduced how to use the WP SMTP plugin in the article "WP SMTP Plugin, Solving the Problem of WordPress Not Receiving Emails". I recommend beginners to use this method. If you want to improve the efficiency of WordPress, I recommend using the code method. Add the following code to the functions.php file in the theme directory.

// Use SMTP to send emails. Xiao Z uses QQ Mail as an example. You can refer to your specific SMTP settings for the email you use.
add_action('phpmailer_init', 'mail_smtp');
function mail_smtp( $phpmailer ) {
    $phpmailer->FromName = 'Xiao Z Blog'; // Sender
    $phpmailer->Host = 'smtp.exmail.qq.com'; // Modify to your SMTP server
    $phpmailer->Port = 465; // SMTP port with SSL encryption
    $phpmailer->Username = '[email protected]'; // Email account
    $phpmailer->Password = '******'; // Enter your corresponding email password, using * instead here
    $phpmailer->From = '[email protected]'; // Your email
    $phpmailer->SMTPAuth = true;
    $phpmailer->SMTPSecure = 'ssl'; // tls or ssl (leave empty for port=25, use 465 for ssl)
    $phpmailer->IsSMTP();
}

I previously found a piece of code online and added it to functions.php, but it caused an error. The code above has been tested by Xiao Z and is effective. Below is a list of commonly used SMTP servers and ports for different email providers.

Email Provider SMTP Server Address Non-SSL Port SSL Port
163.com smtp.163.com 25 465 or 994
126.com smtp.126.com 25 465 or 994
qq.com smtp.qq.com 25 465 or 587
NetEase Enterprise smtp.qiye.163.com 25 994
Tencent Enterprise smtp.exmail.qq.com 25 465

Comments