
Every website—from online stores sending order confirmations to corporate contact forms—needs a reliable email sending system. This guide covers everything from understanding why PHP mail() is problematic, to correctly configuring SMTP on WordPress, using PHPMailer in custom PHP apps, setting up Email Hosting on DirectAdmin, and configuring SPF/DKIM/DMARC so your emails actually reach the inbox.
What is PHP mail() and Why Is It Unreliable?
PHP mail() is a built-in PHP function that sends email directly through Sendmail or the MTA (Mail Transfer Agent) installed on the server, without requiring any SMTP configuration. While convenient, it has several issues that often prevent email from reaching recipients:
- Almost always goes to Spam — PHP mail() sends email directly from the server's IP without proper authentication. Email providers like Gmail, Outlook, and Yahoo apply strict spam filters and routinely classify PHP mail() messages as spam.
- No SPF/DKIM support — PHP mail() does not automatically sign DKIM headers or go through authentication processes. Emails have no "signature" that receiving servers can verify.
- Shared IP reputation — On shared hosting, hundreds of customers share the same server. If another customer sends spam, that IP gets blacklisted and affects every account on the same IP.
- Poor error handling — PHP mail() only returns true or false. You cannot see why an email was rejected or bounced, making debugging very difficult.
- Rate limiting — Many hosting providers, including AsiaGB, limit the number of emails that can be sent via PHP mail() per hour to prevent abuse.
Bottom line: PHP mail() is only suitable for testing in development environments. For production, always use SMTP with proper authentication.
PHP mail() vs SMTP vs Email API: What's the Difference?
There are three main methods for sending email from a website. Each has its own strengths and weaknesses:
| Method | Reliability | Setup | Best For |
|---|---|---|---|
| PHP mail() | Very Low | None needed | Testing only |
| Hosting SMTP | Good | Moderate | Low–medium volume |
| Gmail SMTP | Very Good | Moderate | Personal/SMB sites |
| Email API (Mailgun/SendGrid) | Best | More complex | High volume / Transactional |
SMTP (Simple Mail Transfer Protocol) is the standard protocol for sending email through an authenticated server. The client (your website) logs in with a username and password before every send, giving receiving servers confidence that the email comes from a legitimate sender.
Email APIs like Mailgun or SendGrid let you send email via HTTP API instead of SMTP. They are faster, provide analytics dashboards, handle automatic retries, and support sending millions of emails per month. They are ideal for large e-commerce sites or applications sending high volumes of transactional email.
Configuring SMTP on WordPress with WP Mail SMTP Plugin
WordPress uses PHP mail() by default, but switching to SMTP is straightforward using a plugin—no code changes required. The most recommended plugin is WP Mail SMTP, with over 4 million active installs.
Installing WP Mail SMTP
- Go to WordPress Admin Dashboard → Plugins → Add New
- Search for "WP Mail SMTP" → Install Now → Activate
- Navigate to WP Mail SMTP → Settings → General
- Enter From Email (the address shown in the "From" field) and From Name
- Select your Mailer (Gmail, Hosting SMTP, Mailgun, etc.)
- Enter the required credentials for your chosen mailer → Save Settings
- Test the configuration at WP Mail SMTP → Tools → Email Test
Option 1: Gmail SMTP with App Password
Google no longer allows using your regular password with SMTP. You must create an App Password instead—a 16-character password that substitutes for your real password for apps that don't support 2FA natively:
- Open your Google Account → Security → 2-Step Verification (must be enabled first)
- Search for "App passwords" near the bottom of the Security page
- Select App: "Mail" and Device: "Other (Custom name)" → enter your site name
- Click Generate — you'll receive a 16-character password (save it now; it's shown only once)
- Back in WP Mail SMTP, select Mailer: "Other SMTP"
- Fill in: SMTP Host:
smtp.gmail.com, Port:587, Encryption: TLS, Username: your Gmail address, Password: the App Password you just generated
Gmail SMTP free limits: Up to 500 emails per day (or 100 per hour) for standard Gmail accounts. With Google Workspace this increases to 2,000 emails per day. Suitable for low-to-medium traffic sites.
Option 2: Your Hosting SMTP Server
If you already have an email account on AsiaGB hosting, you can use the hosting SMTP server directly. The advantage is that email is sent from the same domain as your website, making SPF/DKIM configuration more straightforward.
SMTP settings for AsiaGB hosting:
- SMTP Host:
mail.yourdomain.com(replace with your actual domain) - SMTP Port:
587(STARTTLS) or465(SSL/TLS) - Encryption: TLS (Port 587) or SSL (Port 465)
- Authentication: Always enabled
- Username: Full email address, e.g.
[email protected] - Password: The password of that email account
Port 587 vs 465: Try Port 587 with STARTTLS first — most firewalls don't block it. If the connection fails, try Port 465 with SSL/TLS instead. Both are equally secure; they differ only in how the encryption handshake is initiated.
Configuring SMTP in PHP with PHPMailer
If you're building a custom PHP website or using a framework like Laravel, CodeIgniter, or plain PHP, PHPMailer is the best library for sending email. It fully supports SMTP, HTML email, attachments, and SSL/TLS encryption.
Install via Composer
composer require phpmailer/phpmailer
Example: Sending Email with PHPMailer
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true); // true = enable exceptions
try {
// Configure SMTP server
$mail->isSMTP();
$mail->Host = 'mail.yourdomain.com'; // Hosting SMTP server
$mail->SMTPAuth = true;
$mail->Username = '[email protected]'; // Email account
$mail->Password = 'your_email_password'; // Email password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // TLS
$mail->Port = 587;
// Set sender and recipient
$mail->setFrom('[email protected]', 'Your Website Name');
$mail->addAddress('[email protected]', 'Recipient Name');
$mail->addReplyTo('[email protected]', 'Customer Support');
// Email content
$mail->isHTML(true);
$mail->CharSet = 'UTF-8'; // Important for non-ASCII characters
$mail->Subject = 'Order Confirmation #12345';
$mail->Body = '<h2>Thank You for Your Order</h2>'
. '<p>Your order has been confirmed.</p>';
$mail->AltBody = 'Thank you for your order. Your order has been confirmed.';
$mail->send();
echo 'Email sent successfully';
} catch (Exception $e) {
echo "Failed to send email: {$mail->ErrorInfo}";
}
Important: Never store your SMTP password directly in your code. Use environment variables or a config file stored outside the document root. Never commit credentials to version control.
AsiaGB Email Hosting on DirectAdmin
All AsiaGB hosting plans support creating email accounts on your domain through the DirectAdmin control panel, which can be used immediately for SMTP authentication.
Creating an Email Account in DirectAdmin
- Log in to DirectAdmin → E-mail Management section
- Click E-mail Accounts
- Click Create Account
- Enter a username (e.g.
noreplyorcontact) and set a password - Set the Quota (mailbox size) as needed
- Click Create — the email address is ready to use immediately
SMTP Settings for DirectAdmin Email Accounts
mail.yourdomain.com
Replace yourdomain.com with your actual domain. This hostname works for SMTP, IMAP, and POP3.
587 with STARTTLS
The standard port for authenticated SMTP that passes through most firewalls. Use with Encryption: TLS.
465 with SSL/TLS
SMTPS — establishes an SSL connection from the start. Use if Port 587 is blocked by your ISP or firewall.
Username = Full Email Address
Enter the full email address such as [email protected] — not just the part before @. DirectAdmin requires the full address for authentication.
SPF, DKIM, and DMARC: Why They Matter and How to Configure Them
Even with SMTP configured correctly, without SPF, DKIM, and DMARC your emails still have a high chance of landing in spam. Email providers use these records to verify that an email claiming to come from your domain actually originated from an authorized server.
SPF (Sender Policy Framework)
SPF is a TXT DNS record that specifies which IP addresses or servers are authorized to send email on behalf of your domain. If the receiving email server detects that an email came from an IP not listed in your SPF record, it will mark the check as Fail and may reject or spam the message.
Example SPF record for hosting on AsiaGB servers:
v=spf1 include:yourhostingserver.com ~all
DKIM (DomainKeys Identified Mail)
DKIM adds a digital signature to every email header you send. The receiving server verifies this signature against the public key published in your DNS. If the signatures match, it confirms the email was not modified in transit and originated from your actual domain.
DMARC (Domain-based Message Authentication, Reporting and Conformance)
DMARC is a policy that tells receiving servers what to do with emails that fail SPF or DKIM checks: do nothing (none), quarantine (move to Spam), or reject outright. You can also receive reports of rejected emails for analysis.
How to Configure in DirectAdmin DNS Manager
- Log in to DirectAdmin → Domain Management → DNS Management
- Select the domain you want to configure
- Add a TXT Record for SPF: Name =
@or your domain, Value = your SPF record - For DKIM: newer versions of DirectAdmin have an Enable DKIM button in E-mail Manager — click Enable and the system will generate a key pair and add the DNS record automatically
- Add a TXT Record for DMARC: Name =
_dmarc, example Value:
# DMARC Record (start with p=none to monitor first) _dmarc.yourdomain.com TXT "v=DMARC1; p=none; rua=mailto:[email protected]" # Once confident, change to p=quarantine or p=reject _dmarc.yourdomain.com TXT "v=DMARC1; p=quarantine; pct=100; rua=mailto:[email protected]"
Recommendation: Start with p=none to collect reports for 1–2 weeks before enforcing. Then switch to p=quarantine or p=reject for full protection against email spoofing.
Mailgun / SendGrid Free Tier: When to Use an API Instead of Hosting SMTP
Hosting SMTP works well for typical websites with low to moderate email volumes, but as your business grows there are good reasons to switch to an Email API:
- High volume — If you need to send more than 500–1,000 emails per day (order confirmations, newsletters, notifications), your hosting SMTP may be insufficient or hit rate limits.
- Analytics — Mailgun and SendGrid provide dashboards showing Open Rate, Click Rate, Bounce Rate, and Spam Complaints in real-time, which standard SMTP does not offer.
- Better deliverability — Email API providers maintain dedicated IP pools with established high-reputation histories and proper IP warm-up processes, resulting in better inbox placement rates.
- Automatic retry and bounce handling — If sending fails, the API retries automatically and notifies you of bounces and unsubscribes via webhooks.
Mailgun Free Tier: 100 emails per day, free for the first 3 months, then starting from $35/month for 50,000 emails.
SendGrid Free Tier: 100 emails per day with no time limit — ideal for small websites.
Guideline: If your site sends fewer than 200 emails per day, hosting SMTP is sufficient and far simpler to set up. Above 500–1,000 per day, consider an Email API for better deliverability and reliability.
Pre-Launch Email Checklist
Before going live, verify each of the following items to ensure your emails reach recipients and stay out of the spam folder:
- SPF record is set in DNS and fully propagated (verify at mxtoolbox.com/spf.aspx)
- DKIM is enabled in DirectAdmin E-mail Manager and the DNS record is correct
- DMARC record has been added to DNS (start with p=none)
- Sent a test email to mail-tester.com and received a score of at least 8/10
- From Email address matches the domain where SPF/DKIM are configured (not Gmail or another domain)
- Marketing emails include an Unsubscribe link (required by Gmail/Yahoo 2024 sender policy)
- Test emails to Gmail, Outlook, and Yahoo all land in the inbox, not spam
- Server IP is not blacklisted (check at mxtoolbox.com/blacklists.aspx)
- Email Subject and Body don't contain spam trigger words like "FREE!", "Click Now", "Make Money"
- Reply-To is configured correctly and the inbox is monitored (avoid noreply unless truly necessary)
How to Test with mail-tester.com
- Visit mail-tester.com — you'll receive a temporary address like
[email protected] - Send a test email from your system to that address
- Return to mail-tester.com and click "Then check your score"
- Review your score and any issues to fix. Aim for 10/10, or at least 9/10
Common Problems and How to Fix Them
Emails Landing in Spam
Most common causes: missing SPF/DKIM, From address doesn't match the domain with SPF/DKIM configured, email body contains spam trigger words, or the server IP is blacklisted. Fix: set up SPF/DKIM completely, test with mail-tester.com, and check blacklists.
Emails Sending Intermittently
Usually caused by SMTP server rate limiting, timeouts from network instability, or a shared IP being temporarily blocked by a spam filter. Fix: check SMTP error logs, reduce sending frequency, or switch to an Email API that handles automatic retries.
Email Bounces
Bounces come in two types: Hard Bounces occur when the recipient address doesn't exist or the domain is invalid (remove these addresses immediately); Soft Bounces happen when the mailbox is full or the destination server is temporarily unavailable (the system retries automatically). PHPMailer and most Email APIs provide the bounce type in the error message.
Garbled Characters in Email Body
An encoding issue: set $mail->CharSet = 'UTF-8' in PHPMailer, or add the header Content-Type: text/html; charset=UTF-8 when using PHP mail(). Also ensure your PHP file itself is saved with UTF-8 encoding.
Email Hosting with SMTP on Your Own Domain
AsiaGB provides Email Hosting on DirectAdmin with full SMTP, IMAP/POP3, SPF, and DKIM support. Create email accounts on your domain today. Thailand-based servers, starting from THB 500/year.
View Hosting Plans