Home Backend Development PHP Tutorial 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

Sep 28, 2024 am 06:08 AM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1236
24
Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

See all articles