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

Barbara Streisand
Release: 2024-09-28 06:08:01
Original
485 people have browsed it

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

以下是如何使用 PHP SMTP 發送電子郵件而不進入垃圾郵件資料夾的逐步範例

我們將使用 PHPMailer 庫,它簡化了透過 SMTP 發送電子郵件的過程,並有助於提高送達率。請按照以下步驟,您將了解如何正確設定 SMTP 以避免電子郵件進入垃圾郵件資料夾。

步驟1:安裝PHPMailer

首先,您需要安裝 PHPMailer 函式庫。您可以使用 Composer 來完成此操作。

composer require phpmailer/phpmailer
Copy after login

如果您沒有 Composer,您可以從 GitHub 手動下載 PHPMailer 並將其包含在您的專案中。

步驟 2:建立 PHP 郵件腳本

建立一個新檔案 send_email.php,您將在其中編寫腳本以使用 PHPMailer 和 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}";
}
Copy after login

逐部分細分:

  1. PHPMailer 初始化:

    • 透過 Composer 包含必要的檔案後,我們建立 PHPMailer 類別的實例。
    • try-catch 區塊用於處理發送電子郵件時可能發生的任何異常。
  2. SMTP 伺服器設定:

    • $mail->isSMTP() 告訴 PHPMailer 使用 SMTP 發送電子郵件。
    • $mail->Host = 'smtp.example.com':將 'smtp.example.com' 替換為您的 SMTP 提供者的主機(例如,Gmail 的 SMTP 是 'smtp.gmail.com')。
    • $mail->SMTPAuth = true:這將啟用身份驗證,這通常是 SMTP 伺服器所需的。
    • $mail->使用者名稱和$mail->密碼:在此輸入您的 SMTP 憑證。
    • $mail->SMTPSecure:設定加密方法。為了安全起見,建議使用 TLS (STARTTLS)。
    • $mail->Port:常見的 SMTP 連接埠為 TLS 的 587 和 SSL 的 465。使用您的 SMTP 伺服器所需的連接埠。
  3. 設定寄件者和收件者:

    • $mail->setFrom('your_email@example.com', 'Your Name'): 指定寄件者的電子郵件和姓名。
    • $mail->addAddress('recipient@example.com', '收件者姓名'): 新增收件者的電子郵件和姓名。
    • $mail->addReplyTo(): 設定回覆電子郵件地址(可選)。
  4. 設定郵件內容:

    • $mail->isHTML(true): 指定電子郵件內容將為 HTML。
    • $mail->Subject:設定電子郵件主題。
    • $mail->Body:這是電子郵件的 HTML 內容。
    • $mail->AltBody:這是電子郵件正文的純文字版本,對於不支援 HTML 的電子郵件用戶端很有用。
  5. 發送電子郵件

    • $mail->send() 嘗試傳送電子郵件。如果成功,則列印成功訊息;否則,錯誤將被捕獲並顯示。

步驟 3:SMTP 設定和最佳實踐

為了避免電子郵件進入垃圾郵件資料夾,遵循以下最佳實踐至關重要:

  1. 使用信譽良好的 SMTP 提供者

    使用 Gmail、SendGrid 或 Mailgun 等受信任的 SMTP 提供者可以提高送達率,因為它們不太可能被標記為垃圾郵件。

  2. 驗證您的網域名稱:

    為您的郵件設定SPF(寄件者政策框架)、DKIM(網域金鑰識別郵件)和DMARC(基於網域的郵件驗證、報告和一致性)記錄域來驗證您的電子郵件的合法性。

  3. 避免垃圾內容

    確保您的電子郵件內容乾淨且未被標記為垃圾郵件。避免過度使用全部大寫、垃圾字詞(如「免費」、「獲勝者」等)以及過多的連結。

  4. 使用純文字取代:

    始終包含電子郵件的純文字版本 ($mail->AltBody)。一些電子郵件用戶端將純 HTML 電子郵件標記為可疑。

  5. 避免使用免費電子郵件服務作為寄件者

    使用您自己網域中的專業電子郵件地址,而不是 Gmail、Yahoo 等免費服務,以避免被標記為垃圾郵件。

  6. 限制每封電子郵件的收件者數量

    如果發送大量電子郵件,請使用適當的大量電子郵件服務,而不是在一封郵件中發送給多個收件人,以避免被標記為垃圾郵件。

第 4 步:運行腳本

將send_email.php檔案上傳到您的伺服器並在瀏覽器中或透過命令列運行它:

php send_email.php
Copy after login

如果配置正確,您將看到訊息:

Message has been sent
Copy after login

If there’s an error, it will display:

Message could not be sent. Mailer Error: {Error Message}
Copy after login

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

The above is the detailed content of Deliver Emails Safely with PHP: A Guide to Using SMTP for Spam-Free Emails. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!