我在尝试使用 PHP 的 PHPMailer 库发送电子邮件时遇到问题。我收到一条错误消息,显示“无法发送邮件”。我尝试了不同的方式来发送邮件,即使我得到了 ChatGpt 的帮助,但我不能。我已按照文档进行操作,我的代码如下所示:
<form action="mail.php" method="post">
<input type="text" name="name">
<input type="email" name="email" id="">
<input type="submit" value="submit">
</form>
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require __DIR__ . '/PHPMailer-master/PHPMailer.php';
require __DIR__ . '/PHPMailer-master/Exception.php';
require __DIR__ . '/PHPMailer-master/SMTP.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
$mail = new PHPMailer(true);
try {
// SMTP configuration
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'mypassword'; // Replace with your Gmail password
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
// Sender and recipient details
$mail->setFrom('[email protected]', 'Ahmed Maajid');
$mail->addAddress('[email protected]'); // Set your Gmail address as both sender and recipient
// Email content
$mail->isHTML(false);
$mail->Subject = 'New submission from your website';
$mail->Body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email;
$mail->send();
echo 'Email sent successfully!';
} catch (Exception $e) {
echo 'Oops! There was a problem: ' . $mail->ErrorInfo;
}
}
?>
Composer 是启动和运行 PHPMailer 的最简单方法。只需打开终端并输入:
composer require phpmailer/phpmailer
。这是发送电子邮件的代码片段:
require("./vendor/phpmailer/phpmailer/src/PHPMailer.php");
require("./vendor/phpmailer/phpmailer/src/SMTP.php");
// make all the setup to send email
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->IsSmtp();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->IsHTML(true);
$mail->Username = "[email protected]";
$mail->Password = "your_password";
$mail->setFrom("[email protected]");
// make email subject & body
$subject = "testing subject";
$messageBody = "testing message";
$mail->Subject = $subject;
$mail->Body = $messageBody;
// send to
$sendTo = "[email protected]";
$mail->AddAddress($sendTo);
// send request
if($mail->Send()) {
echo 'Email has been sent!';
} else {
echo $mail->ErrorInfo;
}