[TIL] Gửi mail trong PHP bằng Gmail

Hôm trước mình với Tùng làm con app có phần gửi mail, định dùng SNS của AWS mà có vẻ không giòn lắm, bắt xác thực linh tinh. Bực mình, tự code mịa cho nhanh.

Sau đây là cách code bằng PHP.

Bước 1: Tạo app password cho gmail.

Yêu cầu: tài khoản của bạn đã bật 2FA.

  • Nhập tên cho App password
  • Sau khi tạo xong sẽ hiện ra 1 cái popup có chứa password. Bạn lưu lại password này

Bước 2: Thêm code PHP

  • Dùng composer, cài PHPMailer:
composer require phpmailer/phpmailer

Hoặc không thì bạn vào repo gốc, down về: https://github.com/PHPMailer/PHPMailer

  • Thêm code gửi mail
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// Setting response header json
header('Content-Type: application/json');
// Check if not post method -> throw error
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit();
}
// Decode json body
$body = json_decode(file_get_contents('php://input'), true);
// Check if missing email -> throw error
if (!isset($body['email'])) {
http_response_code(400);
echo json_encode(['error' => 'Missing email']);
exit();
}
// Check if missing subject -> throw error
if (!isset($body['subject'])) {
http_response_code(400);
echo json_encode(['error' => 'Missing subject']);
exit();
}
// Check if missing message -> throw error
if (!isset($body['message'])) {
http_response_code(400);
echo json_encode(['error' => 'Missing message']);
exit();
}
try {
// if (isset($_POST['submit'])) {
$mailData = [
'email' => $body['email'],
'subject' => $body['subject'],
'message' => $body['message']
];
require 'vendor/autoload.php';
$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'youremail@gmail';
$mail->Password = 'app_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('fromemail', "Minh Phong 306 Blog");
$mail->addAddress($mailData['email'], 'User');
$mail->isHTML(true);
$mail->Subject = $mailData['subject'];
$mail->Body = $mailData['message'];
$mail->AltBody = 'Alt body';
$mail->send();
echo json_encode(['message' => 'Message has been sent']);
// }
} catch (Exception $ex) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
view raw send_mail.php hosted with ❤ by GitHub
  • Anh em lưu ý:
    • App password: nhớ bỏ khoảng trắng đi, nó là 16 kí tự liền nhau.
    • $mail->Username = ‘youremail@gmail’; ~> đoạn này set email gửi đi
    • $mail->Password = ‘app_password’; ~> đoạn này là app pwd tạo ở bước 1
    • $mail->setFrom(‘fromemail’, “Minh Phong 306 Blog”); ~> đoạn này set hiển thị ở chỗ người gửi là mail đang gửi từ đâu đi và tên người gửi là gì.
    • $mail->addAddress($mailData[’email’], ‘User’); ~> Đoạn này set email người nhận.

Bước 3: Test và hưởng thụ thành quả

Chúc bạn thành công.

Cảm ơn bạn, vì đã đọc bài ^^.

Bình luận về bài viết này