使用PHPMailer发送邮件需要先下载PHPMailer库,并在代码中引入PHPMailer类。然后,需要设置SMTP服务器、发件人地址、发件人密码、收件人地址、邮件主题、邮件内容等信息,最后调用PHPMailer的send()方法发送邮件。
-
下载PHPMailer库,将PHPMailer类所在的文件夹复制到项目中。
-
在代码中引入PHPMailer类,使用命名空间或require_once语句。
-
创建PHPMailer对象,设置SMTP服务器、发件人地址、发件人密码、收件人地址、邮件主题、邮件内容等信息。例如:
$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = "smtp.example.com";
$mail->SMTPAuth = true;
$mail->Username = "yourname@example.com";
$mail->Password = "yourpassword";
$mail->SMTPSecure = "tls";
$mail->Port = 587;
$mail->setFrom("yourname@example.com", "Your Name");
$mail->addAddress("recipient@example.com");
$mail->Subject = "Test Email";
$mail->Body = "Hello, this is a test email.";
- 调用PHPMailer的send()方法发送邮件。例如:
if ($mail->send()) {
echo "Email sent successfully.";
} else {
echo "Email could not be sent.";
}
注意:在使用PHPMailer发送邮件时,需要确保SMTP服务器的配置信息正确,否则邮件可能无法发送成功。