我正在使用 PHPMailer 发送带有可选附件文件的电子邮件。当发送带有附件的电子邮件存在时,这工作正常。但问题是当附件为空时,PHPmailer 拒绝发送电子邮件,有什么解决办法吗?
<?php
use PHPMailer\PHPMailer\PHPMailer;
$msg = '';
$sender_name = $_POST['sender_name'];
// Upload handled successfully
// Now create a message
require 'vendor/autoload.php';
$mail = new PHPMailer;
$mail->setFrom('info@*****.com', 'first last');
$mail->addAddress('info@*****.com');
$mail->Subject = 'PHPMailer file sender';
$mail->Body = "Contact form submission:\n" . "Name: $sender_name\n";
if (array_key_exists('userfile', $_FILES)) {
// First handle the upload
// Don't trust provided filename - same goes for MIME types
// See http://php.net/manual/en/features.file-upload.php#114004 for more thorough upload validation
$uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name']));
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
// Attach the uploaded file
//$mail->addAttachment($uploadfile, 'My uploaded file');
$name = $_FILES['userfile']['name'];
$ext = end((explode(".", $name)));
$mail->addAttachment($uploadfile, 'You Have Attachment.'.$ext);
} else {
$msg .= 'Failed to move file to ' . $uploadfile;
}
}
if (!$mail->send()) {
$msg .= "Mailer Error: " . $mail->ErrorInfo;
} else {
$msg .= "Message sent!";
}
?>
这是位于 PHP 代码下的 html 女巫:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>PHPMailer Upload</title>
</head>
<body>
<?php if (empty($msg)) { ?>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
<br>
<input type="text" name="sender_name">
<br>
Send this file: <input name="userfile" type="file">
<br>
<input type="submit" value="Send File">
</form>
<?php } else {
echo $msg;
} ?>
</body>
</html>
蝴蝶刀刀
largeQ
湖上湖