


以下是如何使用 PHP SMTP 發送電子郵件而不進入垃圾郵件資料夾的逐步範例。
我們將使用 PHPMailer 庫,它簡化了透過 SMTP 發送電子郵件的過程,並有助於提高送達率。請按照以下步驟,您將了解如何正確設定 SMTP 以避免電子郵件進入垃圾郵件資料夾。
步驟1:安裝PHPMailer
首先,您需要安裝 PHPMailer 函式庫。您可以使用 Composer 來完成此操作。
composer require phpmailer/phpmailer
如果您沒有 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}"; }
逐部分細分:
-
PHPMailer 初始化:
- 透過 Composer 包含必要的檔案後,我們建立 PHPMailer 類別的實例。
- try-catch 區塊用於處理發送電子郵件時可能發生的任何異常。
-
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 伺服器所需的連接埠。
-
設定寄件者和收件者:
- $mail->setFrom('your_email@example.com', 'Your Name'): 指定寄件者的電子郵件和姓名。
- $mail->addAddress('recipient@example.com', '收件者姓名'): 新增收件者的電子郵件和姓名。
- $mail->addReplyTo(): 設定回覆電子郵件地址(可選)。
-
設定郵件內容:
- $mail->isHTML(true): 指定電子郵件內容將為 HTML。
- $mail->Subject:設定電子郵件主題。
- $mail->Body:這是電子郵件的 HTML 內容。
- $mail->AltBody:這是電子郵件正文的純文字版本,對於不支援 HTML 的電子郵件用戶端很有用。
-
發送電子郵件:
- $mail->send() 嘗試傳送電子郵件。如果成功,則列印成功訊息;否則,錯誤將被捕獲並顯示。
步驟 3:SMTP 設定和最佳實踐
為了避免電子郵件進入垃圾郵件資料夾,遵循以下最佳實踐至關重要:
使用信譽良好的 SMTP 提供者:
使用 Gmail、SendGrid 或 Mailgun 等受信任的 SMTP 提供者可以提高送達率,因為它們不太可能被標記為垃圾郵件。驗證您的網域名稱:
為您的郵件設定SPF(寄件者政策框架)、DKIM(網域金鑰識別郵件)和DMARC(基於網域的郵件驗證、報告和一致性)記錄域來驗證您的電子郵件的合法性。避免垃圾內容:
確保您的電子郵件內容乾淨且未被標記為垃圾郵件。避免過度使用全部大寫、垃圾字詞(如「免費」、「獲勝者」等)以及過多的連結。使用純文字取代:
始終包含電子郵件的純文字版本 ($mail->AltBody)。一些電子郵件用戶端將純 HTML 電子郵件標記為可疑。避免使用免費電子郵件服務作為寄件者:
使用您自己網域中的專業電子郵件地址,而不是 Gmail、Yahoo 等免費服務,以避免被標記為垃圾郵件。限制每封電子郵件的收件者數量:
如果發送大量電子郵件,請使用適當的大量電子郵件服務,而不是在一封郵件中發送給多個收件人,以避免被標記為垃圾郵件。
第 4 步:運行腳本
將send_email.php檔案上傳到您的伺服器並在瀏覽器中或透過命令列運行它:
php send_email.php
如果配置正確,您將看到訊息:
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:
- Install PHPMailer to simplify email sending with SMTP.
- Configure SMTP correctly with authentication and encryption.
- Use proper domain verification (SPF, DKIM, DMARC) to increase deliverability.
- Write clean, non-spammy email content and always include a plain-text version.
- 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:
- 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!

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

In this article, we're going to explore the notification system in the Laravel web framework. The notification system in Laravel allows you to send notifications to users over different channels. Today, we'll discuss how you can send notifications ov


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
