How to Send Emails via SMTP in WordPress
Some hosting providers disable the mail() function, preventing users from receiving registration or password recovery emails. Even when mail() is supported, the probability of emails landing in spam folders is very high. Therefore, using SMTP for email relay is an excellent solution.
Previously, I introduced how to use the WP SMTP plugin in the article WP SMTP Plugin, Solving WordPress Email Issues. New users are advised to use this plugin method. However, if you want to improve WordPress efficiency, it is recommended to use the code method. Add the following code to the functions.php file in your theme directory.
// Use SMTP to send emails. Xiao Z uses QQ Mail; you can refer to your specific email provider's SMTP settings.
add_action('phpmailer_init', 'mail_smtp');
function mail_smtp( $phpmailer ) {
$phpmailer->FromName = 'Xiao Z Blog'; // Sender name
$phpmailer->Host = 'smtp.exmail.qq.com'; // Modify to your SMTP server
$phpmailer->Port = 465; // SMTP port, SSL encryption enabled
$phpmailer->Username = 'service@xiaoz.me'; // Email account
$phpmailer->Password = '******'; // Enter your corresponding email password (masked here)
$phpmailer->From = 'service@xiaoz.me'; // Your email
$phpmailer->SMTPAuth = true;
$phpmailer->SMTPSecure = 'ssl'; // tls or ssl (leave port=25 empty, 465 is ssl)
$phpmailer->IsSMTP();
}
I previously found a snippet of code online to add to functions.php, but it caused errors. The code above has been personally tested and verified by Xiao Z. Below is a summary of SMTP servers and ports for common 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 Mail | smtp.qiye.163.com | 25 | 994 |
| Tencent Enterprise Mail | smtp.exmail.qq.com | 25 | 465 |