MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

PHP Code for Godaddy VPS Server SMTP Email Relay

This page shows how to send email from a GoDaddy VPS through GoDaddy's SMTP relay on port 25 with plain PHP sockets and no extra libraries. Below the original script you will find what each SMTP step does, a corrected and safer version, how to test port 25, a PHPMailer alternative for production, and fixes for the errors people hit most often.


How the example script talks to the relay

The gist above opens a raw TCP connection with fsockopen() and has a full SMTP conversation by hand. GoDaddy's VPS relay does not ask for a username or password. It accepts mail based on the IP address the connection comes from, so the script never sends AUTH. Each command must get the expected reply code before the next one is sent:

StepClient sendsExpected replyMeaning
Greeting(nothing, just connect)220Server is ready
EHLOEHLO your-hostname250 (multi-line)Server lists the extensions it supports
Envelope senderMAIL FROM:<sender>250Sender accepted
Envelope recipientRCPT TO:<recipient>250 or 251Recipient accepted for relay
DATADATA354Send headers and body, then end with a line holding a single dot
End of message<CRLF>.<CRLF>250Message queued for delivery
QUITQUIT221Connection closed

The smtp_read_all() function handles multi-line replies. A line such as 250-SIZE has a hyphen in the fourth position, which means more lines are coming. The last line has a space there, for example 250 HELP.

Before you run it: find the relay host and check port 25

  1. Open the GoDaddy help article linked above and copy the relay hostname it gives for your VPS plan and data centre. The hostname in the gist is one example. Do not assume it matches your server.
  2. Check that your VPS can reach that host on port 25. If this times out, nothing in PHP will work.
  3. On cPanel/WHM servers, check WHM > Security Center > SMTP Restrictions. When it is on, ordinary users cannot make outbound SMTP connections, and PHP scripts running as a cPanel user are one of them.
  4. If CSF firewall is installed, check SMTP_BLOCK and SMTP_ALLOWUSER in /etc/csf/csf.conf. Also check any iptables/firewalld rules that block outbound port 25.
# Replace RELAY_HOST with the hostname from GoDaddy's article
nc -vz RELAY_HOST 25

# Or talk to it interactively (type QUIT to exit)
telnet RELAY_HOST 25
# Expected first line: 220 ... ESMTP ...Code language: PHP (php)

Corrected and hardened version of the script

This version keeps the same approach but fixes the problems listed in the corrections. Server output is escaped so it shows correctly in a browser. Reads time out instead of hanging. The message gets the required Date and Message-ID headers, the body is dot-stuffed, and the script stops with an error code at the first failed step.

<?php
// smtp-test.php  - run with: php smtp-test.php
$host = getenv('SMTP_RELAY_HOST') ?: 'n1smtpout.europe.secureserver.net'; // use the host from GoDaddy's article
$port = 25;
$from = 'sender@yourdomain.com';
$to   = 'you@yourdomain.com';
$heloName = gethostname() ?: 'localhost';

function out(string $s): void {
    echo PHP_SAPI === 'cli' ? $s : htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}

function smtp_read($fp): array {
    $response = '';
    $code = null;
    while (($line = fgets($fp, 1024)) !== false) {
        out("<< $line");
        $response .= $line;
        if (strlen($line) < 4 || !ctype_digit(substr($line, 0, 3))) {
            break;
        }
        $code = (int) substr($line, 0, 3);
        if ($line[3] === ' ') {
            break; // last line of a (possibly multi-line) reply
        }
    }
    if (stream_get_meta_data($fp)['timed_out']) {
        out("!! Timed out waiting for the server\n");
    }
    return [$code, $response];
}

function smtp_cmd($fp, string $cmd): array {
    out(">> $cmd\n");
    fwrite($fp, $cmd . "\r\n");
    return smtp_read($fp);
}

function expect($fp, ?int $code, array $ok, string $step): void {
    if (!in_array($code, $ok, true)) {
        out("$step failed, reply code: " . var_export($code, true) . "\n");
        fwrite($fp, "QUIT\r\n");
        fclose($fp);
        exit(1);
    }
}

if (PHP_SAPI !== 'cli') { echo '<pre>'; }
out("Connecting to $host:$port...\n");

$fp = @fsockopen($host, $port, $errno, $errstr, 20); // 20 s connect timeout
if (!$fp) {
    out("Connection failed: $errno - $errstr\n");
    exit(1);
}
stream_set_timeout($fp, 30); // read timeout for every reply

[$code] = smtp_read($fp);                       expect($fp, $code, [220], 'Greeting');
[$code] = smtp_cmd($fp, "EHLO $heloName");      expect($fp, $code, [250], 'EHLO');
[$code] = smtp_cmd($fp, "MAIL FROM:<$from>");   expect($fp, $code, [250], 'MAIL FROM');
[$code] = smtp_cmd($fp, "RCPT TO:<$to>");       expect($fp, $code, [250, 251], 'RCPT TO');
[$code] = smtp_cmd($fp, 'DATA');                expect($fp, $code, [354], 'DATA');

$domain = substr(strrchr($from, '@'), 1);
$headers = [
    'Date: ' . date('r'),
    'From: ' . $from,
    'To: ' . $to,
    'Subject: GoDaddy SMTP relay test',
    'Message-ID: <' . bin2hex(random_bytes(12)) . '@' . $domain . '>',
    'MIME-Version: 1.0',
    'Content-Type: text/plain; charset=UTF-8',
];
$body = "This is a test email sent through the GoDaddy relay on port 25.\n"
      . "If it reaches your inbox, SMTP works from this server.\n";

$data = implode("\r\n", $headers) . "\r\n\r\n" . $body;
$data = preg_replace("/\r\n|\r|\n/", "\r\n", $data); // SMTP requires CRLF line endings
$data = preg_replace('/^\./m', '..', $data);        // dot-stuffing (RFC 5321)

out(">> [message headers and body]\n");
fwrite($fp, rtrim($data, "\r\n") . "\r\n.\r\n");
[$code] = smtp_read($fp);                       expect($fp, $code, [250], 'Message');

smtp_cmd($fp, 'QUIT');
fclose($fp);
out("\nDone: message accepted by the relay.\n");
if (PHP_SAPI !== 'cli') { echo '</pre>'; }Code language: PHP (php)

Note: The short array destructuring [$code] = ... and the typed parameters need PHP 7.1 or newer. Every supported PHP release meets this.

Running the test and reading the output

Run the script from the shell on the VPS rather than through a browser. You see the raw output, and nobody else can trigger it. Set the relay host with an environment variable so it stays out of the code:

SMTP_RELAY_HOST=RELAY_HOST php smtp-test.php

A successful run looks roughly like this. The server text after each code changes from server to server:

Connecting to RELAY_HOST:25...
<< 220 ... ESMTP ...
>> EHLO vps.yourdomain.com
<< 250-...
<< 250 ...
>> MAIL FROM:<sender@yourdomain.com>
<< 250 ...
>> RCPT TO:<you@yourdomain.com>
<< 250 ...
>> DATA
<< 354 ...
>> [message headers and body]
<< 250 ... queued ...
>> QUIT
<< 221 ...

Done: message accepted by the relay.Code language: CSS (css)

A final 250 only means the relay accepted the message. Whether it reaches the inbox depends on the recipient's spam filtering, so check the spam folder as well.

Use PHPMailer for real applications

A hand-written socket client is fine for testing. For application mail, use a maintained library. It handles encoding, attachments, HTML bodies, header injection protection and errors for you. Install PHPMailer with Composer (composer require phpmailer/phpmailer) and point it at the same relay without authentication:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require __DIR__ . '/vendor/autoload.php';

$mail = new PHPMailer(true); // throw exceptions on errors
try {
    $mail->isSMTP();
    $mail->Host        = getenv('SMTP_RELAY_HOST'); // from GoDaddy's article
    $mail->Port        = 25;
    $mail->SMTPAuth    = false;  // relay authorises by server IP
    $mail->SMTPAutoTLS = false;  // set true if the relay offers STARTTLS with a valid certificate
    $mail->SMTPDebug   = SMTP::DEBUG_OFF; // use SMTP::DEBUG_SERVER while troubleshooting
    $mail->Timeout     = 30;

    $mail->setFrom('sender@yourdomain.com', 'Your App');
    $mail->addAddress('you@yourdomain.com');
    $mail->Subject = 'GoDaddy relay test via PHPMailer';
    $mail->Body    = "Hello from PHPMailer.\n";

    $mail->send();
    echo "Sent\n";
} catch (Exception $e) {
    echo "Mailer error: {$mail->ErrorInfo}\n";
}Code language: PHP (php)

Frameworks such as Laravel, Symfony and CodeIgniter have their own mail settings that take the same values: host, port 25, no username or password, no encryption.

Alternative: relay PHP mail() through Postfix

If existing code uses PHP's built-in mail(), you can leave it alone and have the local MTA forward everything to GoDaddy instead. With Postfix installed, set the relay host and reload:

sudo postconf -e 'relayhost = [RELAY_HOST]:25'
sudo systemctl reload postfix

# Send a test and watch the log
echo "Test body" | mail -s "Postfix relay test" you@yourdomain.com
sudo tail -f /var/log/mail.log   # /var/log/maillog on RHEL-family systemsCode language: PHP (php)

The square brackets tell Postfix to connect to that host directly and skip the MX lookup. In the log, look for status=sent with relay= showing the GoDaddy host.

Common errors and fixes

SymptomLikely causeFix
Connection timed out (110)Outbound port 25 blocked by WHM SMTP Restrictions, CSF SMTP_BLOCK or another firewall, or wrong hostTest with nc -vz; allow the PHP user or turn off the restriction; confirm the hostname
Connection refused (111)Wrong host or portUse the exact relay host and port from GoDaddy's article
getaddrinfo failedHostname typo or DNS problem on the VPSCheck spelling; test with dig RELAY_HOST
550 or 554 after MAIL FROM or RCPT TORelay refuses this server's IP or senderConfirm the VPS is a GoDaddy-hosted server allowed to use that relay; use a sender on your own domain
421 or 4xx repliesTemporary limit or service problemRetry later; queue mail instead of sending in bursts
Script hangs with no outputNo read timeout on the socketUse stream_set_timeout() as in the corrected script
Final 250 but mail never arrivesSpam filtering, SPF/DMARC failureCheck spam; publish SPF that authorises the relay; check message headers at the recipient

Security and deliverability notes

  • Do not leave a test mailer in the web root. Anyone who finds the URL can send mail as your domain. Run it from the CLI, or delete it after testing.
  • Never put user input straight into headers (To, Subject, From). A CR or LF in that input lets an attacker add headers or recipients. Validate addresses with filter_var($addr, FILTER_VALIDATE_EMAIL) or use PHPMailer.
  • Port 25 relay traffic to GoDaddy is usually unencrypted. Do not send passwords or sensitive data in the message body.
  • Publish an SPF record for your sending domain that includes GoDaddy's mail servers (GoDaddy commonly documents include:secureserver.net). Add DMARC to improve inbox placement.
  • Use a From address on a domain you control. Sending as Gmail or another provider's domain will fail their DMARC checks.

Frequently asked questions

What SMTP server should I use on a GoDaddy VPS?

Use the relay hostname in GoDaddy's help article for VPS hosting (linked at the top of this post). It can depend on your plan and data centre. The relay runs on port 25 and authorises your server by IP address, so no username or password is needed.

Why does fsockopen time out when connecting to the GoDaddy relay?

Usually something is blocking outbound port 25. Common causes are WHM's SMTP Restrictions, CSF's SMTP_BLOCK setting or a local firewall rule. Check with nc -vz RELAY_HOST 25 from the server. If that also times out, fix the network side before you debug PHP.

Can I use smtpout.secureserver.net with a username and password instead?

That host is for authenticated mailboxes hosted with GoDaddy, not the IP-based VPS relay. If you have a GoDaddy mailbox, you can authenticate to it with PHPMailer by setting SMTPAuth to true and supplying the mailbox credentials and the port GoDaddy documents for it.

The script says the message was accepted but no email arrived. Why?

A 250 reply only means the relay queued the message. Check the spam folder, make sure the From address uses a domain you own, and publish SPF and DMARC records that authorise GoDaddy's servers.

Should I use raw sockets or PHPMailer?

Use raw sockets only to test connectivity and see the SMTP conversation. For application mail, use PHPMailer or your framework's mailer. They handle encoding, attachments and header safety for you.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

AWS IAM Policy to Protect SES SMTP

You can lock down Amazon SES SMTP credentials with an IAM policy on the IAM user that owns them. A Deny on aws:SourceIp limits which IP addresses…

Read More

How to see number of emails sent using smtp in laravel

Laravel does not count or log SMTP emails by default, so a grep will only return a real number once your application writes one log line for…

Read More

Email Authentication & Communication Infrastructure in Modern DevOps: The 2026 Definitive Guide

In the high-stakes world of modern DevOps, we spend our days (and sometimes our nights) obsessing over the “golden signals” of site reliability: latency, traffic, errors, and…

Read More

The 5 Most Popular Email APIs Among Developers In 2026

In the modern world, where everything is going digital, email is among the most important means of communication both in personal and business life. As a developer,…

Read More

Senior Exchange Administrator: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path

The Senior Exchange Administrator is accountable for the reliability, security, performance, and lifecycle management of the organizationโ€™s Microsoft messaging platform, typically spanning Exchange Online (Microsoft 365), Exchange Server (on-premises), or a hybrid configuration. This role ensures email and calendaring services are highly available, compliant, and aligned to business needs while proactively reducing operational risk and improving user experience.

Read More

Principal Exchange Administrator: Role Blueprint, Responsibilities, Skills, KPIs, and Career Path

The Principal Exchange Administrator is the senior technical authority responsible for the reliability, security, lifecycle, and operational excellence of the enterprise messaging platformโ€”typically Microsoft Exchange Online/Exchange Server in a hybrid Microsoft 365 environment. This role exists to ensure email and calendaring services remain highly available, performant, compliant, and aligned with enterprise security and governance requirements while enabling modern collaboration capabilities across the organization.

Read More
Subscribe
Notify of
guest
2 Comments
Newest
Oldest Most Voted
Skylar Bennett
Skylar Bennett
1 year ago

Great guide โ€” this article makes it very clear how to configure SMTPโ€‘relay for PHP on a GoDaddy VPS. The sample code and setup instructions show practical, realโ€‘world ways to ensure reliable email delivery โ€” something many developers struggle with due to blocked mail ports or default configuration issues. I especially appreciate the way the post highlights the importance of using a relay host (such as GoDaddyโ€™s SMTP relay) instead of relying on insecure or blocked default mail configurations. For anyone hosting on GoDaddy and building contactโ€‘forms, userโ€‘notifications, or transactionalโ€‘email features โ€” this tutorial is a solid mustโ€‘read. ๐Ÿ‘

Jason Mitchell
Jason Mitchell
1 year ago

This guide gives a very practical walkthrough for configuring SMTP email relay on a GoDaddy VPSโ€”something that often causes confusion for developers, especially when standard mail() functions fail or get blocked. The stepโ€‘byโ€‘step breakdown of PHP setup, SMTP host selection, relay configuration and handling of common GoDaddyโ€‘specific quirks (such as port restrictions or the need to use their relay service) is particularly valuable. It serves as a strong reference for anyone building contact forms, transactional email flows or automating alerts on a GoDaddy VPS, ensuring you move from โ€œitโ€™s not sendingโ€ to โ€œitโ€™s configured correctly and deliveringโ€.

2
0
Would love your thoughts, please comment.x
()
x