对于后端PHP开发,我还很陌生...我知道如何将发布的数据捕获到PHP变量中,并将这些变量注入到我的HTML电子邮件正文中。但是,我不知道如何在HTML内实现PHP“ foreach”功能。
目标如下:
使用PHPmailer通过简单的PHP“ foreach”功能发送HTML电子邮件,以捕获输入数据并将其粘贴到HTML电子邮件的正文中。
我已经简化了我的问题:我想对每个函数使用a来捕获名称属性为“ FRUIT”的所有输入,并将它们各自的数据属性和值注入HTML正文中。
预期的行为是公开一封电子邮件,其内容如下:
苹果:1
香蕉:2
这是我的简化的 HTML 表单:
<form id="form" action="(action.php) method="POST">
<input type="text" name="FRUIT[]" data-attribute="apple" value="1">
<input type="text" name="FRUIT[]" data-attribute="banana" value="2">
<input type="submit" value="submit">
</form>
这是我简化的 PHP 操作脚本:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require '/home/furtbswy/public_html/PHPMailer-master/src/Exception.php';
require '/home/furtbswy/public_html//PHPMailer-master/src/PHPMailer.php';
require '/home/furtbswy/public_html/PHPMailer-master/src/SMTP.php';
$mail = new PHPMailer(false);
try {
$from = 'xxxxxxh@gmail.com';
$to = $_POST['EMAIL'];
$fruits= '';
foreach ($_POST['FRUIT'] as $key => $value) {
$fruits.= "$key: $value <br>";
}
$message = '
<html>
<body>
Fruits: ' . $fruits. '
</body>
</html>
';
// PHPmailer setup
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->username = $from;
$mail->Password = 'xxxxxx';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
// recipients
$mail->setfrom($from);
$mail->addAddress($to);
// content
$mail->Subject = 'confirmation';
$mail->isHTML(true);
$mail->Body = $message;
$mail->send();
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
?>