3

I'm trying to set up an SMTP gmail server to send emails from my WordPress site. This is what I've got in my wp-config.php:

define( 'SMTP_USER',   '[email protected]' );    // Username to use for SMTP authentication
define( 'SMTP_PASS',   'password' );       // Password to use for SMTP authentication
define( 'SMTP_HOST',   'smtp.gmail.com' );    // The hostname of the mail server
define( 'SMTP_FROM',   '[email protected]' ); // SMTP From email address
define( 'SMTP_NAME',   'My Site Name' );    // SMTP From name
define( 'SMTP_PORT',   '465' );                  // SMTP port number - likely to be 25, 465 or 587
define( 'SMTP_SECURE', 'tls' );                 // Encryption system to use - ssl or tls
define( 'SMTP_AUTH',    true );                 // Use SMTP authentication (true|false)
define( 'SMTP_DEBUG',   1 );                    // for debugging purposes only set to 1 or 2

I put this in my theme's functions.php file:

add_action( 'phpmailer_init', 'send_smtp_email' );
function send_smtp_email( $phpmailer ) {
    $phpmailer->isSMTP();
    $phpmailer->Host       = SMTP_HOST;
    $phpmailer->SMTPAuth   = SMTP_AUTH;
    $phpmailer->Port       = SMTP_PORT;
    $phpmailer->Username   = SMTP_USER;
    $phpmailer->Password   = SMTP_PASS;
    $phpmailer->SMTPSecure = SMTP_SECURE;
    $phpmailer->From       = SMTP_FROM;
    $phpmailer->FromName   = SMTP_NAME;
}

I'm calling wp_mail() in a function like so:

 function invite_others() {
            $team_name = $_GET['team_name'];

            $user_id = get_current_user_id();
            $user = get_userdata($user_id);
            $site = get_site_url();

            $message = "blah blah blah";
            $subject = "blah";
            $admin_email = get_option('admin_email');

            foreach($_POST as $name => $email) {
                if($email != $_POST['invite_others']){ 
                    $headers = "From: ". $admin_email . "\r\n" .
                        "Reply-To: " . $email . "\r\n";
                    $sent = wp_mail($email, $subject, strip_tags($message), $headers);
                }
            }

 }

I get the following error from wp_mail():

SMTP Error: Could not connect to SMTP host

Any help would be appreciated! Thanks

1
  • Why not to use lightweight WP Mail SMTP plugin? Commented Oct 6, 2018 at 5:08

2 Answers 2

1

Quite likely you're using the wrong encryption/port combination. You are using port 465 for tls.

Port 465 should be used for SSL

Port 587 should be used for TLS

0

Did you try to check in your Google account the option "access for less secure app"? Allow it and retry it, it is often that.

Also, you could try the port 587 instead of 465 for TLS.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.