"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Deliver Emails Safely with PHP: A Guide to Using SMTP for Spam-Free Emails

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

Published on 2024-11-08
Browse:688

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

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.

isSMTP();                                          // Use SMTP
    $mail->Host = 'smtp.example.com';                         // Set the SMTP server (use your SMTP provider)
    $mail->SMTPAuth = true;                                   // Enable SMTP authentication
    $mail->Username = '[email protected]';               // 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('[email protected]', 'Your Name');
    $mail->addAddress('[email protected]', 'Recipient Name');  // Add recipient
    $mail->addReplyTo('[email protected]', '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 test email 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}";
}

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('[email protected]', 'Your Name'): Specifies the sender’s email and name.
    • $mail->addAddress('[email protected]', '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

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

Message has been sent

If there’s an error, it will display:

Message could not be sent. Mailer Error: {Error Message}

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:

  • LinkedIn
  • GitHub
Release Statement This article is reproduced at: https://dev.to/mdarifulhaque/deliver-emails-safely-with-php-a-guide-to-using-smtp-for-spam-free-emails-12d4?1If there is any infringement, please Contact [email protected] to delete
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3