搜尋
首頁後端開發php教程使用 PHP 安全地傳送電子郵件:使用 SMTP 發送無垃圾郵件的指南

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

다음은 PHP SMTP를 사용하여 스팸 폴더에 들어가지 않고 이메일을 보내는 방법

의 단계별 예입니다.

SMTP를 통해 이메일 전송을 단순화하고 전달 가능성을 향상시키는 PHPMailer 라이브러리를 사용하겠습니다. 다음 단계에 따라 이메일이 스팸 폴더에 들어가지 않도록 SMTP를 올바르게 구성하는 방법을 배우게 됩니다.

1단계: PHPMailer 설치

먼저 PHPMailer 라이브러리를 설치해야 합니다. Composer를 사용하여 이 작업을 수행할 수 있습니다.

composer require phpmailer/phpmailer

Composer가 없으면 GitHub에서 PHPMailer를 수동으로 다운로드하여 프로젝트에 포함할 수 있습니다.

2단계: PHP 메일 스크립트 만들기

SMTP와 함께 PHPMailer를 사용하여 이메일을 보내는 스크립트를 작성할 새 파일 send_email.php를 만듭니다.

<?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}";
}

부품별 분석:

  1. PHP메일러 초기화:

    • 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', 'Recipient Name'): 받는 사람의 이메일과 이름을 추가합니다.
    • $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(DomainKeys Identified Mail) 및 DMARC(도메인 기반 메시지 인증, 보고 및 준수) 레코드를 설정하세요. 도메인을 사용하여 이메일의 적법성을 확인하세요.

  3. 스팸 콘텐츠 방지:

    이메일 내용이 깨끗하고 스팸으로 표시되지 않았는지 확인하세요. 모두 대문자를 과도하게 사용하거나 스팸성 단어(예: "무료", "승자" 등)를 사용하거나 링크를 너무 많이 사용하지 마세요.

  4. 일반 텍스트 대안 사용:

    항상 이메일의 일반 텍스트 버전을 포함하세요($mail->AltBody). 일부 이메일 클라이언트는 HTML 전용 이메일을 의심스러운 것으로 표시합니다.

  5. 발신자로서 무료 이메일 서비스 피하기:

    스팸으로 신고되지 않으려면 Gmail, Yahoo 등과 같은 무료 서비스 대신 자신의 도메인에 있는 전문 이메일 주소를 사용하세요.

  6. 이메일당 수신자 수 제한:

    대량 이메일을 보내는 경우 스팸 신고를 피하기 위해 하나의 메시지를 여러 수신자에게 보내는 대신 적절한 대량 이메일 서비스를 사용하십시오.

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:

  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

以上是使用 PHP 安全地傳送電子郵件:使用 SMTP 發送無垃圾郵件的指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何使PHP應用程序更快如何使PHP應用程序更快May 12, 2025 am 12:12 AM

tomakephpapplicationsfaster,關注台詞:1)useopcodeCachingLikeLikeLikeLikeLikePachetoStorePreciledScompiledScriptbyTecode.2)MinimimiedAtabaseSqueriSegrieSqueriSegeriSybysequeryCachingandeffeftExting.3)Leveragephp7 leveragephp7 leveragephp7 leveragephpphp7功能forbettercodeefficy.4)

PHP性能優化清單:立即提高速度PHP性能優化清單:立即提高速度May 12, 2025 am 12:07 AM

到ImprovephPapplicationspeed,關注台詞:1)啟用opcodeCachingwithapCutoredUcescriptexecutiontime.2)實現databasequerycachingingusingpdotominiminimizedatabasehits.3)usehttp/2tomultiplexrequlexrequestsandreduceconnection.4 limitesclection.4.4

PHP依賴注入:提高代碼可檢驗性PHP依賴注入:提高代碼可檢驗性May 12, 2025 am 12:03 AM

依赖注入(DI)通过显式传递依赖关系,显著提升了PHP代码的可测试性。1)DI解耦类与具体实现,使测试和维护更灵活。2)三种类型中,构造函数注入明确表达依赖,保持状态一致。3)使用DI容器管理复杂依赖,提升代码质量和开发效率。

PHP性能優化:數據庫查詢優化PHP性能優化:數據庫查詢優化May 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

簡單指南:帶有PHP腳本的電子郵件發送簡單指南:帶有PHP腳本的電子郵件發送May 12, 2025 am 12:02 AM

phpisusedforsenderemailsduetoitsbuilt-inmail()函數andsupportivelibrariesLikePhpMailerAndSwiftMailer.1)usethemail()functionForbasiceMails,butithasimails.2)butithasimail.2)

PHP性能:識別和修復瓶頸PHP性能:識別和修復瓶頸May 11, 2025 am 12:13 AM

PHP性能瓶颈可以通过以下步骤解决:1)使用Xdebug或Blackfire进行性能分析,找出问题所在;2)优化数据库查询并使用缓存,如APCu;3)使用array_filter等高效函数优化数组操作;4)配置OPcache进行字节码缓存;5)优化前端,如减少HTTP请求和优化图片;6)持续监控和优化性能。通过这些方法,可以显著提升PHP应用的性能。

PHP的依賴注入:快速摘要PHP的依賴注入:快速摘要May 11, 2025 am 12:09 AM

依賴性注射(DI)InphpisadesignPatternthatManages和ReducesClassDeptions,增強量強制性,可驗證性和MATIALWINABIOS.ItallowSpasspassingDepentenciesLikEdenciesLikedAbaseConnectionStoclasseconnectionStoclasseSasasasasareTers,interitationAseTestingEaseTestingEaseTestingEaseTestingEasingAndScalability。

提高PHP性能:緩存策略和技術提高PHP性能:緩存策略和技術May 11, 2025 am 12:08 AM

cachingimprovesphpermenceByStorcyResultSofComputationsorqucrouctationsorquctationsorquickretrieval,reducingServerLoadAndenHancingResponsetimes.feftectivestrategiesinclude:1)opcodecaching,whereStoresCompiledSinmememorytssinmemorytoskipcompliation; 2)datacaching datacachingsingMemccachingmcachingmcachings

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中