Latest Post

Tăng thứ hạng và truy cập tự nhiên với 10 phương pháp SEO hay nhất Kiếm Tiền Online (mmo): Khái Niệm và Các Hình Thức Phổ Biến

Chúng tôi xin giới thiệu một thư viện gửi email phổ biến trên ngôn ngữ lập trình PHP, đó là thư viện PHPMailer. Dưới đây là một số thông tin cơ bản về thư viện PHPMailer.

  • Github: https://github.com/PHPMailer/PHPMailer
  • Tác giả: Brent R. Matzelle
  • Phát hành lầ đầu từ năm 2001; 22 năm trước tính từ thời đểm viết bài
  • Viết bằng ngôn ngữ lập trình PHP

Ưu điểm khi sử dụng PHPMailer

  • Chắc chắn đây là source code phổ biến nhất để gửi email bằng PHP
  • Được sử dụng bởi nhiều phần mềm mã nguồn mở nổi tiếng như là: WordPress, Drupal, 1CRM, SugarCRM, Yii, Joomla…
  • Tích hợp SMTP – Bạn có thể gửi email mà không cần local mail server.
  • Gửi email cho nhiều đối tượng với TO, CC, BCC và Reply-to
  • Thêm nhiều tệp đính kèm khi gửi email
  • Support for UTF-8 content and 8bit, base64, binary, and quoted-printable encodings
  • Hỗ trợ nội dung mã UTF-8, 8bit, base64, binarry,…
  • Xác thực SMTP với LOGIN,PLAIN,CRAM-MD5 và cơ chế XOAUTH2 thông qua SMTPS và SMTP+STARTTLS
  • Kiểm tra địa chỉ email tự động
  • Ngăn chặn tấn công header injection
  • Báo lỗi bằng 50 ngôn ngữ
  • hỗ trợ DKIM và ký danh S/MIME
  • Phù hợp từ PHP5.5 đến mới nhất
  • Sử dụng Namespace để ngăn ngừa trùng tên Class

Hướng dẫn tích hợp PHPMailer vào trong 1 project PHP

Bước 1: Để sử dụng nó chúng ta sử dụng công cụ quản lý package của PHP là composer.

Đầu tiên là đưa nó vào trong file composer.json

"phpmailer/phpmailer": "^6.7.1"

Bạn có thể sử dụng command sau để checkout source code của thư viện.

composer require phpmailer/phpmailer

Trường hợp chưa có file composer.json nó sẽ tự tạo cho bạn.

Bước 2: Để gửi email bằng SMTP bạn cần 1 tài khoản SMTP, bạn có thể sử dụng chính Gmail của bạn để gửi.

Bước 3: Tạo 1 file sendmail.php nhúng thư viện để gửi email. Dưới đây là 1 ví dụ để các bạn tham khảo.

<?php
//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerSMTP;
use PHPMailerPHPMailerException;

//Load Composer's autoloader
require 'vendor/autoload.php';

//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
    $mail->isSMTP();                                            //Send using SMTP
    $mail->Host       = 'smtp.example.com';                     //Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
    $mail->Username   = '[email protected]';                     //SMTP username
    $mail->Password   = 'secret';                               //SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
    $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

    //Recipients
    $mail->setFrom('[email protected]', 'Mailer');
    $mail->addAddress('[email protected]', 'Joe User');     //Add a recipient
    $mail->addAddress('[email protected]');               //Name is optional
    $mail->addReplyTo('[email protected]', 'Information');
    $mail->addCC('[email protected]');
    $mail->addBCC('[email protected]');

    //Attachments
    $mail->addAttachment('/var/tmp/file.tar.gz');         //Add attachments
    $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    //Optional name

    //Content
    $mail->isHTML(true);                                  //Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

VD trên khá dài chúng tôi chỉ sử dụng đoạn code cơ bản sau:

<?php

/**
 * sendmail.php
 *
 * @author vinasupport.com
 * Date: 18/02/2023
 * Time: 14:12
 */
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerSMTP;
use PHPMailerPHPMailerException;

//Load Composer's autoloader
require 'vendor/autoload.php';

//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
//    $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
    $mail->isSMTP();                                            //Send using SMTP
    $mail->Host       = 'smtp.gmail.com';                     //Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
    $mail->Username   = '[email protected]';                     //SMTP username
    $mail->Password   = '12345678';                               //SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
    $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

    //Recipients
    $mail->setFrom('[email protected]', 'TestMail');
    $mail->addAddress('[email protected]', 'Joe User');

    //Content
    $mail->isHTML(true);                                  //Set email format to HTML
    $mail->Subject = 'Test email with smtp';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

Bước 4: Chạy file sendmail.php để gửi email.

php sendmail.php

Vậy là chúng ta có thể gửi email thành công.

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *