PHPMailer 是一个用于发送电子邮件的 PHP 库。它支持多种邮件传输协议,包括 SMTP、sendmail、qmail 和 PHP 自带的 mail() 函数。PHPMailer 提供了丰富的功能,如 HTML 邮件、附件、字符集支持等。
PHPMailer 主要有以下几种类型:
PHPMailer 适用于各种需要发送电子邮件的场景,如:
以下是一个使用 PHPMailer 发送 SMTP 邮件的示例代码:
<?php
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true);
try {
// Server settings
$mail->SMTPDebug = 2; // 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 = 'password'; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
$mail->Port = 587; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
// Recipients
$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('recipient@example.com', 'Joe User'); // Add a recipient
// 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}";
}
?>
原因:
解决方法:
原因:
解决方法:
UTF-8
。$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64';
原因:
解决方法:
通过以上方法,可以有效解决 PHPMailer 在实际应用中遇到的常见问题。
领取专属 10元无门槛券
手把手带您无忧上云