Làm cách nào để gửi email bằng PHP SMTP?

I migrated an application to a platform without a local transport agent (MTA). I did not want to configure an MTA, so I wrote this xxmail function to replace mail() with calls to a remote SMTP server. Hopefully it is of some use.

function xxmail($to, $subject, $body, $headers)
{
$smtp = stream_socket_client('tcp://smtp.yourmail.com:25', $eno, $estr, 30);

$B = 8192;
$c = "\r\n";
$s = '[email protected]';

________số 8

// Envelope
fwrite($smtp, 'mail from: ' . $s . $c);
  $junk = fgets($smtp, $B);
fwrite($smtp, 'rcpt to: ' . $to . $c);
  $junk = fgets($smtp, $B);
fwrite($smtp, 'data' . $c);
  $junk = fgets($smtp, $B);

$mail = new PHPMailer(true);
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->SMTPSecure = '';
$mail->SMTPAuth   = true;
$mail->Host       = 'mx.host.com';
$mail->Username   = 'username';
$mail->Password   = 'your password';
$mail->Port       = 2525;
0

$mail = new PHPMailer(true);
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->SMTPSecure = '';
$mail->SMTPAuth   = true;
$mail->Host       = 'mx.host.com';
$mail->Username   = 'username';
$mail->Password   = 'your password';
$mail->Port       = 2525;
1

$mail = new PHPMailer(true);
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->SMTPSecure = '';
$mail->SMTPAuth   = true;
$mail->Host       = 'mx.host.com';
$mail->Username   = 'username';
$mail->Password   = 'your password';
$mail->Port       = 2525;
2

Sử dụng PHPMailer để gửi email với máy chủ thư SMTP và MailSlurp. Định cấu hình truy cập IMAP và SMTP trong PHP bằng phpmailer và trình soạn thảo

Làm cách nào để gửi email bằng PHP SMTP?

PHP là một ngôn ngữ tuyệt vời để gửi email với SMTP. PHP cung cấp nhiều chức năng để gửi email trực tiếp hoặc bằng cách kết nối với máy chủ SMTP. Trong bài đăng này, chúng tôi sẽ thảo luận về tiêu chuẩn SMTP và các cách khác nhau để gửi email trong PHP bằng SMTP

Giao thức SMTP là gì?

SMTP hoặc giao thức chuyển thư đơn giản là cách tiêu chuẩn để trao đổi email giữa máy chủ và mã. Nếu bạn muốn gửi email bằng PHP bằng SMTP, trước tiên bạn phải xác định máy chủ mà bạn muốn kết nối. Đây có thể là máy chủ SMTP lưu trữ tài khoản email của người nhận hoặc máy chủ SMTP của riêng bạn sẽ thay mặt bạn gửi

Hầu hết các nhà cung cấp thư đều chạy máy chủ SMTP trên các cổng 25, 2525, 465 hoặc 578. MailSlurp là nhà cung cấp email miễn phí với máy chủ SMTP có sẵn trên các cổng sau

Giao thứcHostPortTLSMô tảSMTPmx. mailslurp. com2525falseMáy chủ SMTPIMAPmailslurp. click1143falseMáy chủ IMAP

Các phương thức gửi thư PHP

Vì PHP là một ngôn ngữ lâu đời và đáng kính nên có nhiều cách để gửi email. Phương thức lâu đời nhất là hàm mail(). Chức năng thư đã có từ PHP4 nhưng nó đi kèm với một số lưu ý. Đầu tiên, nó yêu cầu cấu hình bằng tệp hệ thống

$mail = new PHPMailer(true);
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->SMTPSecure = '';
$mail->SMTPAuth   = true;
$mail->Host       = 'mx.host.com';
$mail->Username   = 'username';
$mail->Password   = 'your password';
$mail->Port       = 2525;
3. Điều này có thể khó thiết lập. Các ứng dụng PHP hiện đại thường sử dụng thư viện cấp cao hơn như PHPMailer

PHPMailer - thư viện mail PHP phổ biến nhất

Do những hạn chế của chức năng

$mail = new PHPMailer(true);
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->SMTPSecure = '';
$mail->SMTPAuth   = true;
$mail->Host       = 'mx.host.com';
$mail->Username   = 'username';
$mail->Password   = 'your password';
$mail->Port       = 2525;
4 tích hợp, hầu hết các nhà phát triển khuyên bạn nên sử dụng thư viện mã nguồn mở PHPMailer. Bạn có thể cài đặt thư viện bằng trình soạn thảo
$mail = new PHPMailer(true);
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->SMTPSecure = '';
$mail->SMTPAuth   = true;
$mail->Host       = 'mx.host.com';
$mail->Username   = 'username';
$mail->Password   = 'your password';
$mail->Port       = 2525;
5. Sau đó, bao gồm các thư viện trong mã php của bạn bằng cách sử dụng tính năng tự động tải của nhà cung cấp để gửi email bằng SMTP trong PHP


require_once(__DIR__ . '/vendor/autoload.php');

use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

Kết nối với máy chủ SMTP bằng PHPMailer

Để gửi email SMTP bằng PHP, hãy nhập PHPMailer và định cấu hình một phiên bản để sử dụng cổng và tên máy chủ cho máy chủ SMTP của bạn

$mail = new PHPMailer(true);
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->SMTPSecure = '';
$mail->SMTPAuth   = true;
$mail->Host       = 'mx.host.com';
$mail->Username   = 'username';
$mail->Password   = 'your password';
$mail->Port       = 2525;

Nếu bạn sử dụng máy chủ MailSlurp SMTP, bạn có thể sử dụng phương pháp

$mail = new PHPMailer(true);
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->SMTPSecure = '';
$mail->SMTPAuth   = true;
$mail->Host       = 'mx.host.com';
$mail->Username   = 'username';
$mail->Password   = 'your password';
$mail->Port       = 2525;
6 để lấy tên người dùng và mật khẩu của mình

$smtpAccess = $inboxController->getImapSmtpAccess($inbox1->getId());

Gửi email SMTP bằng PHP

Để thực sự gửi email, trước tiên hãy kết nối với máy chủ, sau đó xây dựng thư theo từng phần

$smtpAccess = $inboxController->getImapSmtpAccess($inbox1->getId());

$mail = new PHPMailer(true);
try {
    // User smtp access to configure PhpMailer for MailSlurp
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;
    $mail->isSMTP();
    $mail->SMTPAuth   = true;
    $mail->Host       = $smtpAccess->getSmtpServerHost();
    $mail->Username   = $smtpAccess->getSmtpUsername();
    $mail->Password   = $smtpAccess->getSmtpPassword();
    $mail->SMTPSecure = '';
    $mail->Port       = $smtpAccess->getSmtpServerPort();

    // test connection (secure disabled)
    $connected = $mail->smtpConnect();
    $this->assertTrue($connected);

    // write email from inbox1 to inbox2
    $mail->setFrom($inbox1->getEmailAddress());
    $mail->addAddress($inbox2->getEmailAddress());
    $mail->isHTML(true);
    $mail->Subject = 'Hello inbox2';
    $mail->Body    = 'This is an HTML message';

    // send the email
    $sent = $mail->send();

    $this->assertTrue($sent);
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    throw new Exception($mail->ErrorInfo);
}

Kiểm tra gửi email với PhpUnit

Khi gửi email từ ứng dụng PHP của bạn, hãy xem xét kiểm tra email từ đầu đến cuối bằng MailSlurp. MailSlurp là dịch vụ miễn phí để bắt email trong tài khoản dùng một lần. Bạn có thể kết nối với máy chủ bằng SMTP và sau đó xác minh rằng đã nhận được email


require_once(__DIR__ . '/vendor/autoload.php');

use MailSlurp\ApiException;
use PHPMailer\PHPMailer\SMTP;
use PHPUnit\Framework\TestCase;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

/**
 * Example tests for MailSlurp (using PHP 7.1)
 */
class MailSlurp_SDK_Test extends TestCase
{

    public $config;

    /**
     * Setup mailslurp config for later use
     */
    public function setUp(): void
    {
        // get api key from environment variables (use your own key here)
        $API_KEY = getenv('API_KEY');
        $this->assertNotEmpty($API_KEY, "API Key must not be empty");

        // create configuration with api key
        $this->config = MailSlurp\Configuration::getDefaultConfiguration()->setApiKey('x-api-key', $API_KEY);
    }

    /**
     * @throws ApiException
     * @throws Exception
     */
    public function test_canSendSMTPEmail_usingPhpMailer() {
        // create an inbox
        $inboxController = new MailSlurp\Apis\InboxControllerApi(null, $this->config);
        $inbox1 = $inboxController->createInboxWithOptions(new \MailSlurp\Models\CreateInboxDto([ "inbox_type" => "SMTP_INBOX"]));
        $this->assertStringContainsString("@mailslurp.mx", $inbox1->getEmailAddress());

        $inbox2 = $inboxController->createInbox();
        $smtpAccess = $inboxController->getImapSmtpAccess($inbox1->getId());

        $mail = new PHPMailer(true);
        try {
            // User smtp access to configure PhpMailer for MailSlurp
            $mail->SMTPDebug = SMTP::DEBUG_SERVER;
            $mail->isSMTP();
            $mail->SMTPAuth   = true;
            $mail->Host       = $smtpAccess->getSmtpServerHost();
            $mail->Username   = $smtpAccess->getSmtpUsername();
            $mail->Password   = $smtpAccess->getSmtpPassword();
            $mail->SMTPSecure = '';
            $mail->Port       = $smtpAccess->getSmtpServerPort();

            // test connection (secure disabled)
            $connected = $mail->smtpConnect();
            $this->assertTrue($connected);

            // write email from inbox1 to inbox2
            $mail->setFrom($inbox1->getEmailAddress());
            $mail->addAddress($inbox2->getEmailAddress());
            $mail->isHTML(true);
            $mail->Subject = 'Hello inbox2';
            $mail->Body    = 'This is an HTML message';

            // send the email
            $sent = $mail->send();

            $this->assertTrue($sent);
        } catch (Exception $e) {
            echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
            throw new Exception($mail->ErrorInfo);
        }

        // wait for email to arrive in inbox2
        $waitForController = new MailSlurp\Apis\WaitForControllerApi(null, $this->config);
        $email = $waitForController->waitForLatestEmail($inbox2->getId(), 30000);
        $this->assertStringContainsString("Hello inbox2", $email->getSubject());
        $this->assertStringContainsString("HTML", $email->getBody());
    }
}

đọc thêm

Có nhiều cách khác để gửi và nhận email trong PHP bằng SMTP. Xem tài liệu dành cho nhà phát triển PHP để biết thêm thông tin

Thư PHP có sử dụng SMTP không?

Trình gửi thư PHP sử dụng Giao thức truyền thư đơn giản (SMTP) để gửi thư . Trên máy chủ được lưu trữ, cài đặt SMTP đã được đặt. Cài đặt thư SMTP có thể được định cấu hình từ “php. ini” trong thư mục cài đặt PHP.

Làm cách nào để gửi email bằng tập lệnh PHP?

1. Sử dụng hàm PHP mail() . Hàm mail() tích hợp sẵn của PHP là một trong những cách đơn giản nhất để gửi email trực tiếp từ chính máy chủ web. Nó chỉ cần ba tham số bắt buộc. địa chỉ email, chủ đề email và nội dung thư—và gửi nó đến người nhận.

Làm cách nào để gửi thư bằng PHP bằng trình gửi thư PHP?

PHPMailer là một thư viện mã và được sử dụng để gửi email một cách an toàn và dễ dàng thông qua mã PHP từ máy chủ web. .
isHTML(). Nếu được thông qua đúng, hãy đặt định dạng email thành HTML
Vấn đề. Đặt chủ đề của Thư
Thân thể. Đặt nội dung của Thư
AltBody. Nội dung thay thế trong trường hợp ứng dụng e-mail không hỗ trợ HTML

Làm cách nào để gửi email từ tập lệnh PHP bằng xác thực SMTP?

Cú pháp và tham số .
“$to” = (những) người nhận tin nhắn của bạn. Định dạng địa chỉ email có thể là user@example. com hoặc Người dùng user@example. com. .
“subject” = chủ đề tin nhắn của bạn “tin nhắn” = nội dung tin nhắn của bạn. .
“[$headers]” = người nhận thêm tin nhắn của bạn, có thể được bao gồm trong CC hoặc BCC