DEV Community

MD ARIFUL HAQUE
MD ARIFUL HAQUE

Posted on

Deliver Emails Safely with PHP: A Guide to Using SMTP for Spam-Free Emails

Here’s a step-by-step example of how to send emails without landing in the spam folder using PHP SMTP.

We'll use the PHPMailer library, which simplifies sending emails via SMTP and helps improve deliverability. Following these steps, you’ll learn how to properly configure SMTP to avoid emails landing in the spam folder.

Step 1: Install PHPMailer

First, you need to install the PHPMailer library. You can do this using Composer.

composer require phpmailer/phpmailer
Enter fullscreen mode Exit fullscreen mode

If you don’t have Composer, you can download PHPMailer manually from GitHub and include it in your project.

Step 2: Create the PHP Mail Script

Create a new file send_email.php where you will write the script to send the email using PHPMailer with SMTP.

<?php
// Load Composer's autoloader if using Composer
require 'vendor/autoload.php';

// Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->isSMTP();                                          // Use SMTP
    $mail->Host = 'smtp.example.com';                         // Set the SMTP server (use your SMTP provider)
    $mail->SMTPAuth = true;                                   // Enable SMTP authentication
    $mail->Username = 'your_email@example.com';               // SMTP username
    $mail->Password = 'your_password';                        // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;       // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                        // TCP port to connect to (587 is common for TLS)

    //Recipients
    $mail->setFrom('your_email@example.com', 'Your Name');
    $mail->addAddress('recipient@example.com', 'Recipient Name');  // Add recipient
    $mail->addReplyTo('reply_to@example.com', 'Reply Address');    // Add a reply-to address

    // Content
    $mail->isHTML(true);                                        // Set email format to HTML
    $mail->Subject = 'Test Email Subject';
    $mail->Body    = 'This is a <b>test email</b> sent using PHPMailer and SMTP.';
    $mail->AltBody = 'This is a plain-text version of the email for non-HTML email clients.';

    // Send the email
    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
Enter fullscreen mode Exit fullscreen mode

Part-by-Part Breakdown:

  1. PHPMailer Initialization:

    • After including the necessary files via Composer, we create an instance of the PHPMailer class.
    • The try-catch block is used to handle any exceptions that may occur while sending the email.
  2. SMTP Server Configuration:

    • $mail->isSMTP() tells PHPMailer to use SMTP for sending the email.
    • $mail->Host = 'smtp.example.com': Replace 'smtp.example.com' with your SMTP provider’s host (e.g., Gmail’s SMTP is 'smtp.gmail.com').
    • $mail->SMTPAuth = true: This enables authentication, which is usually required by SMTP servers.
    • $mail->Username and $mail->Password: Enter your SMTP credentials here.
    • $mail->SMTPSecure: This sets the encryption method. TLS (STARTTLS) is recommended for security.
    • $mail->Port: Common SMTP ports are 587 for TLS and 465 for SSL. Use the port required by your SMTP server.
  3. Setting the Sender and Recipient:

    • $mail->setFrom('your_email@example.com', 'Your Name'): Specifies the sender’s email and name.
    • $mail->addAddress('recipient@example.com', 'Recipient Name'): Adds the recipient's email and name.
    • $mail->addReplyTo(): Sets the reply-to email address (optional).
  4. Setting the Email Content:

    • $mail->isHTML(true): Specifies that the email content will be HTML.
    • $mail->Subject: Sets the email subject.
    • $mail->Body: This is the HTML content of the email.
    • $mail->AltBody: This is a plain-text version of the email body, useful for email clients that don’t support HTML.
  5. Sending the Email:

    • $mail->send() attempts to send the email. If successful, a success message is printed; otherwise, the error is caught and displayed.

Step 3: SMTP Configuration and Best Practices

To avoid emails going to the spam folder, it’s crucial to follow these best practices:

  1. Use a Reputable SMTP Provider:

    Using a trusted SMTP provider like Gmail, SendGrid, or Mailgun improves deliverability because they are less likely to be flagged as spam.

  2. Authenticate Your Domain:

    Set up SPF (Sender Policy Framework), DKIM (DomainKeys Identified Mail), and DMARC (Domain-based Message Authentication, Reporting & Conformance) records for your domain to verify the legitimacy of your emails.

  3. Avoid Spammy Content:

    Ensure your email content is clean and not flagged as spam. Avoid excessive use of all-caps, spammy words (like "free," "winner," etc.), and too many links.

  4. Use Plain-Text Alternative:

    Always include a plain-text version of your email ($mail->AltBody). Some email clients flag HTML-only emails as suspicious.

  5. Avoid Free Email Services as Senders:

    Use a professional email address from your own domain instead of free services like Gmail, Yahoo, etc., to avoid being flagged as spam.

  6. Limit the Number of Recipients per Email:

    If sending bulk emails, use proper bulk email services instead of sending to many recipients in one message to avoid being flagged for spamming.

Step 4: Run the Script

Upload the send_email.php file to your server and run it in the browser or through the command line:

php send_email.php
Enter fullscreen mode Exit fullscreen mode

If the configuration is correct, you’ll see the message:

Message has been sent
Enter fullscreen mode Exit fullscreen mode

If there’s an error, it will display:

Message could not be sent. Mailer Error: {Error Message}
Enter fullscreen mode Exit fullscreen mode

Conclusion

By using PHPMailer and a proper SMTP setup, you can ensure your emails are sent reliably and with a lower chance of landing in the spam folder. Here's a quick summary:

  1. Install PHPMailer to simplify email sending with SMTP.
  2. Configure SMTP correctly with authentication and encryption.
  3. Use proper domain verification (SPF, DKIM, DMARC) to increase deliverability.
  4. Write clean, non-spammy email content and always include a plain-text version.
  5. Run the script and monitor the success message or error log.

This approach ensures better deliverability and reduces the chances of your emails being marked as spam.

Feel free to follow me:

Top comments (0)