PHP Emails Not Sending On GoDaddy? Here’s How I Fixed It.
Troubleshooting PHP Email Sending Issues on Shared Hosting
If you’re running an e-commerce application on a shared host, you may encounter issues with sending emails. I recently faced this with my PHP web app on GoDaddy. The problem was there’s a limitation on the number of characters per line that caused the email to not be sent.
This issue happened with GoDaddy, but I assume it’s common across other shared web hosts.
The Problem
The code for generating the body of the email followed this format:
<?php
$totalCost = 0;
$emailHeader = "Cart information:";
$emailBody = "";
foreach ($arrOrders as $item) {
$emailBody .= "<p><strong>". $item['itemName'] . "</strong>";
$emailBody .= "<br>" . "Details: " . $item['itemDetails'];
$totalCost = $totalCost + $item['itemCost'];
}
$emailFooter = "<br>Total Cost: " . currencyFormat($totalCost);
$emailMessage = $emailHeader . $emailBody . $emailFooter;
?>
If there were several items in the order, the email wouldn’t send.
I even tried printing out if the email successfully sent:
<?php
$result = mail($to, $subject, $message, $headers);
if ($result) {
echo "Email sent successfully.";
} else {
echo "Email sending failed.";
}
?>
But it printed out the successful message every time, even when I didn’t get the email!
A quick search indicated that there’s no limit in the number of characters in the body content of a PHP email using the mail() function.
I found a Stack Overflow question that mentioned there was a limit of 990 characters per line.
The Solution
Inside the loop of generating the list of items, I forced in carriage return, adding in \r\n
// before
$emailBody .= "<p><strong>". $item['itemName'] . "</strong>";
// after
$emailBody .= "\r\n<p><strong>". $item['itemName'] . "</strong>";
And that fixed it!
The Takeaway
When sending emails with PHP on a shared host, be mindful of line lengths in your email body. Adding line breaks may prevent undelivered emails.