使用phpMailer和PHP从表单发送文件附件,可以通过以下步骤实现:
composer require phpmailer/phpmailer
<form action="sendmail.php" method="post" enctype="multipart/form-data">
<label for="sender">发件人:</label>
<input type="email" name="sender" id="sender" required>
<br>
<label for="recipient">收件人:</label>
<input type="email" name="recipient" id="recipient" required>
<br>
<label for="subject">主题:</label>
<input type="text" name="subject" id="subject" required>
<br>
<label for="attachment">附件:</label>
<input type="file" name="attachment" id="attachment">
<br>
<input type="submit" value="发送">
</form>
<?php
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true);
try {
// 邮件服务器设置
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'username';
$mail->Password = 'password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
// 发件人、收件人、主题、正文设置
$mail->setFrom($_POST['sender'], 'Sender Name');
$mail->addAddress($_POST['recipient'], 'Recipient Name');
$mail->Subject = $_POST['subject'];
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->isHTML(true);
// 附件设置
if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] == UPLOAD_ERR_OK) {
$mail->addAttachment($_FILES['attachment']['tmp_name'],
$_FILES['attachment']['name']);
}
// 发送邮件
$mail->send();
echo 'Message has been sent';
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
以上就是使用phpMailer和PHP从表单发送文件附件的方法。
领取专属 10元无门槛券
手把手带您无忧上云