Send Email with PHP using SMTP Authentication
The following example demonstrates how to send email using PHP with SMTP authentication. This script connects directly to the Fast2Host mail server, authenticates with your credentials, and sends an email message.
Sample PHP Script
<?php
// Example usage
$to = "to@fast2host.com";
$nameto = "Recipient Name";
$from = "from@fast2host.com";
$namefrom = "Sender Name";
$subject = "Hello World Again!";
$message = "World, Hello!";
authSendEmail($from, $namefrom, $to, $nameto, $subject, $message);
// Function to send email with SMTP authentication
function authSendEmail($from, $namefrom, $to, $nameto, $subject, $message)
{
// SMTP + Server Details
$smtpServer = "mail.YOUR-DOMAIN.com";
$port = 25; // Use 49 (Windows hosting) or 26 (Linux hosting) if port 25 is blocked
$timeout = 30;
$username = "your-email@domain.com";
$password = "yourpassword";
$localhost = "mail.YOUR-DOMAIN.com";
$newLine = "\r\n";
// Connect to SMTP server
$smtpConnect = fsockopen($smtpServer, $port, $errno, $errstr, $timeout);
$smtpResponse = fgets($smtpConnect, 515);
if (empty($smtpConnect)) {
return "Failed to connect: $smtpResponse";
}
// Authenticate
fputs($smtpConnect, "AUTH LOGIN" . $newLine);
fgets($smtpConnect, 515);
fputs($smtpConnect, base64_encode($username) . $newLine);
fgets($smtpConnect, 515);
fputs($smtpConnect, base64_encode($password) . $newLine);
fgets($smtpConnect, 515);
// Say Hello
fputs($smtpConnect, "HELO $localhost" . $newLine);
fgets($smtpConnect, 515);
// Mail From / RCPT To
fputs($smtpConnect, "MAIL FROM: $from" . $newLine);
fgets($smtpConnect, 515);
fputs($smtpConnect, "RCPT TO: $to" . $newLine);
fgets($smtpConnect, 515);
// Send Data
fputs($smtpConnect, "DATA" . $newLine);
fgets($smtpConnect, 515);
// Construct Headers
$headers = "MIME-Version: 1.0" . $newLine;
$headers .= "Content-type: text/html; charset=iso-8859-1" . $newLine;
$headers .= "To: $nameto <$to>" . $newLine;
$headers .= "From: $namefrom <$from>" . $newLine;
fputs($smtpConnect, "To: $to\nFrom: $from\nSubject: $subject\n$headers\n\n$message\n.\n");
fgets($smtpConnect, 515);
// Quit
fputs($smtpConnect, "QUIT" . $newLine);
fgets($smtpConnect, 515);
}
?>
Configuration Notes
- SMTP Server: Use
mail.yourdomain.com. - Ports: Default is 25. Use 49 (Windows hosting) or 26 (Linux hosting) if port 25 is blocked.
- Authentication: Always use your full email address and password.
- Encryption: Consider enabling SSL/TLS if supported.
Best Practices
- Validate and sanitize all user input before sending emails to prevent abuse.
- Use try/catch or error handling to manage connection failures.
- For production sites, consider using libraries like PHPMailer or SwiftMailer for easier management.
- For bulk or newsletter emails, use a dedicated mailing service to avoid blacklisting.
✔ Tip: This script is intended for basic SMTP authentication.
For advanced features and reliability, use PHPMailer or SwiftMailer with Fast2Host SMTP settings.