Gửi Email bằng SMTP trong PHP sử dụng PHPMailer
Chúng tôi xin giới thiệu đến các bạn một thư viện gửi mail thông dụng nhất 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 về thư viện PHPMailer.
- Github: https://github.com/PHPMailer/PHPMailer
- Tác giả: Brent R. Matzelle
- Lần đầu tiên được phát hành từ năm 2001; 22 năm trước kể từ thời điểm viết
- Được viết bằng ngôn ngữ lập trình PHP
Ưu điểm của việc sử dụng PHPMailer
- Đây chắc chắn là mã nguồn 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ư: WordPress, Drupal, 1CRM, SugarCRM, Yii, Joomla…
- Tích hợp SMTP – Bạn có thể gửi email mà không cần máy chủ thư cục bộ.
- Gửi email tới nhiều đối tượng bằng TO, CC, BCC và Reply-to
- Thêm nhiều File đính kèm khi gửi email
- Hỗ trợ nội dung UTF-8 và mã hóa 8bit, base64, nhị phân và có thể in được trích dẫn
- Hỗ trợ UTF-8, 8bit, base64, nhị phân, v.v.
- Xác thực SMTP với cơ chế LOGIN,PLAIN,CRAM-MD5 và XOAUTH2 thông qua SMTPS và SMTP+STARTTLS
- Tự động kiểm tra địa chỉ email
- Ngăn chặn các cuộc tấn công tiêm tiêu đề
- Báo cáo lỗi bằng 50 ngôn ngữ
- Hỗ trợ DKIM và ký S/MIME
- Thích hợp từ PHP5.5 đến mới nhất
- Sử dụng Không gian tên để ngăn trùng lặp tên lớp
Hướng dẫn tích hợp PHPMailer vào dự án PHP
Bước 1: Để sử dụng chúng ta sử dụng công cụ quản lý gói của PHP composer. Mời các bạn tham khảo bài viết sau về composer.
Đầu tiên là đặt nó trong tập tin nhà soạn nhạc.json
"phpmailer/phpmailer": "^6.7.1"
Bạn có thể sử dụng lệnh sau để kiểm tra mã nguồn của thư viện.
composer require phpmailer/phpmailer
Nếu bạn không có File composer.json, nó sẽ tạo File đó cho bạn.
Bước 2: Để gửi email bằng SMTP bạn cần có 1 tài khoản SMTP, có thể dùng Gmail riêng để gửi. Mời bạn tham khảo bài viết sau:
Bước 3: Tạo 1 tập tin sendmail.php Thư viện nhúng để gửi email. Dưới đây là một ví dụ để 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="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}"; }
Ví dụ trên khá dài, chúng ta 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="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 tập tin sendmail.php để gửi thư điện tử.
php sendmail.php
Như vậy là chúng ta đã có thể gửi email thành công.
Nguồn: vinasupport.com