Gửi Email bằng SMTP trong PHP sử dụng PHPMailer


Chúng tôi muốn giới thiệu đến các bạn thư viện gửi mail được sử dụng phổ biến nhất trên ngôn ngữ lập trình PHP đó chính là thư viện PHPMailer. Dưới đây là 1 số thông tin của 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. Vui lòng tham khảo bài viết sau vể 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. Các bạn vui lòng tham khảo bài viết sau:

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 PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

//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   = 'user@example.com';                     //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('from@example.com', 'Mailer');
    $mail->addAddress('joe@example.net', 'Joe User');     //Add a recipient
    $mail->addAddress('ellen@example.com');               //Name is optional
    $mail->addReplyTo('info@example.com', 'Information');
    $mail->addCC('cc@example.com');
    $mail->addBCC('bcc@example.com');

    //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 PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

//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   = 'testmail@vinasupport.com';                     //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('testmail@vinasupport.com', 'TestMail');
    $mail->addAddress('admin@vinasupport.com', '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.

Nguồn: vinasupport.com

 

             
SHARE

Bài viết liên quan

mode_edit Bình luận của bạn

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 *

account_circle
web