PHP SMTP connection issues with Mailgun service

I’m working on building an email system for my website using PHP and Mailgun’s SMTP service. However, I keep getting an SMTP host connection error when trying to send emails.

Here’s the code I’m using:

<?php

require("../config/settings.php");
require("../vendor/mailgun/autoload.php");
require("../mailer/phpmailer.class.php");
use Mailgun\Mailgun;

if($_SERVER["REQUEST_METHOD"] === "GET")
{
    display("contact.php", ["page_title" => "Get in touch"]);
}

if($_SERVER["REQUEST_METHOD"] === "POST")
{     
    $emailer = new PHPMailer;

    $emailer->isSMTP();
    $emailer->Host = 'smtp.mailgun.org';
    $emailer->SMTPAuth = true;
    $emailer->Username = '[email protected]';
    $emailer->Password = '*my_smtp_password';
    $emailer->SMTPSecure = 'ssl';
    $emailer->Port = '465';

    $emailer->From = '[email protected]';
    $emailer->FromName = 'Contact Form';
    $emailer->addAddress('[email protected]');
    $emailer->isHTML(true);

    $emailer->Subject = 'New contact message';
    $emailer->Body = $_POST["user_message"];

    if(!$emailer->send())
    {  
        echo "Email delivery failed.";
        echo 'Error details: ' . $emailer->ErrorInfo . "\n";
    } 
    else 
    {
        header("Location: success.html");
    }
}
?>

This is for a school project so I’m using the free sandbox domain. Has anyone run into similar connection problems? Any suggestions would be helpful.

Had this exact problem last month with a client’s Mailgun setup. My hosting provider was blocking port 465 - switched to port 2525 and it worked perfectly. Mailgun supports it and most hosts don’t block it. Keep SMTPSecure as ‘tls’ though. Also verify your sandbox domain in Mailgun’s dashboard first, even for testing. Check if your host has curl and openssl extensions enabled - PHPMailer needs them for secure SMTP. The SMTPDebug error should tell you if it’s a timeout or auth issue.

Also check if your server can resolve smtp.mailgun.org properly. Local dev setups sometimes can’t reach external SMTP hosts. Quick test: add $emailer->SMTPOptions = ['ssl' => ['verify_peer' => false, 'verify_peer_name' => false]]; but don’t use this in production. And remember - Mailgun’s sandbox mode needs authorized recipients added first.

Had the same problem with Mailgun and PHPMailer. Try switching to port 587 and use ‘tls’ instead of ‘ssl’ for SMTPSecure - that’s what Mailgun recommends with STARTTLS. Double-check your SMTP credentials too, especially make sure you’re using the full postmaster email as username. Also worth checking if your host blocks outbound SMTP on those ports - lots of shared hosts do this. Add $emailer->SMTPDebug = 2; to see what’s actually going wrong.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.