PHPMailer là một thư viện gửi email rất phổ biến, được phát triển tích cực để lưu trữ PHP . Và nó là nguồn mở.
1. Cài đặt PHPMailer
Trong ví dụ này, chúng tôi sẽ cài đặt PHPMailer bằng Composer, vì đó là phương pháp được nhiều nhà phát triển PHP ưa thích.
composer require phpmailer/phpmailer
2. Thêm mã vào ứng dụng của bạn
Bảng thông báo:
- robot@example.com: Địa chỉ email người gửi của bạn
- mail.example.com: SMTP server name
- ‘password’: Password email
- joe@example.com: Địa chỉ email người nhận
- Name of sender: Tên người gửi mong muốn
- Name of recipient: Tên người nhận mong muốn
<?php
require “vendor/autoload.php”;
$robo = ‘robot@example.com’;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$developmentMode = true;
$mailer = new PHPMailer($developmentMode);
try {
$mailer->SMTPDebug = 2;
$mailer->isSMTP();
if ($developmentMode) {
$mailer->SMTPOptions = [
‘ssl’=> [
‘verify_peer’ => false,
‘verify_peer_name’ => false,
‘allow_self_signed’ => true
]
];
}
$mailer->Host = ‘mail.example.com’;
$mailer->SMTPAuth = true;
$mailer->Username = ‘robot@example.com’;
$mailer->Password = ‘password’;
$mailer->SMTPSecure = ‘tls’;
$mailer->Port = 587;
$mailer->setFrom(‘robot@example.com’, ‘Name of sender’);
$mailer->addAddress(‘joe@example.com’, ‘Name of recipient’);
$mailer->isHTML(true);
$mailer->Subject = ‘PHPMailer Test’;
$mailer->Body = ‘This is a <b>SAMPLE<b> email sent through <b>PHPMailer<b>’;
$mailer->send();
$mailer->ClearAllRecipients();
echo “MAIL HAS BEEN SENT SUCCESSFULLY”;
} catch (Exception $e) {
echo “EMAIL SENDING FAILED. INFO: ” . $mailer->ErrorInfo;
}
?>
3. Mã PHP
<?php
// PHP code here
// No closing tag needed
4. Kết hợp mã PHP và HTML
<?php // PHP code here ?> <html> <!-- HTML code here --> </html> <?php // More PHP code here