我无法让PHPMailer发送带有用户提交的图片附件的电子邮件。我每次尝试发送时都会收到“邮件错误”。我只是看不出有什么问题。 error_log中没有错误,每次都会失败。
处理图片附件的HTML输入:
<input type="file" name="file" placeholder="Choose an image." id="imageupload" accept="image/jpeg" />
PHP代码:
<?php
// Make sure logged in
include('../php_scripts/login-required.php');
// Make sure posted
if (!$_POST) {
header('location: ./404.php');
}
// Include PHPmailer
require 'site_includes/PHPMailer/class.phpmailer.php';
// Get variables
$offertype = $_POST['ot'];
if ($offertype == 1) {
$offertype = 'Discount';
} elseif ($offertype == 2) {
$offertype = 'Free';
} else {
$offertype = 'Not set';
}
$offerdetail = $_POST['od'];
// Check for errors
if (!isset($offertype) || empty($offertype)) {
$errors = 1;
header('location: ./create-advert.php?errors=' . $errors . '&ot=' . $offertype . '&od=' . $offerdetail);
} elseif (!isset($offerdetail) || empty($offerdetail)) {
$errors = 2;
header('location: ./create-advert.php?errors=' . $errors . '&ot=' . $offertype . '&od=' . $offerdetail);
}
// Get variables from database
include('../php_scripts/db-connect.php');
include('../php_scripts/get-userinfo.php');
// Set mail variables
$reply = $email;
$replyname = $fullname;
$to = 'test@example.com';
$toname = 'John Doe';
$from = 'example@example.com';
$subject = 'New Advert Request';
$message = 'Name: ' . $fullname . "\r\n" . "Company: " . $company . "\r\n" . "Phone: " . $phone . "\r\n" . "Email: " . $email . "\r\n\r\n" . $offertype . "\r\n" . "--------------------------------------------------" . "\r\n\r\n" . $offerdetail;
if (isset($_FILES['file'])) {
// Get attachment and upload
$tmp_name = $_FILES['file']['tmp_name'];
$name = $_FILES['file']['name'];
move_uploaded_file($tmp_name, "uploads/$name");
// Send email with attachment
$mail = new PHPMailer;
$mail->From = $from;
$mail->addAddress($to, $toname);
$mail->addReplyTo($reply, $replyname);
$mail->WordWrap = 50;
$mail->addAttachment(
'/uploads/' . $name,
$name,
'base64',
'mime/type'
);
$mail->Subject = $subject;
$mail->AltBody = $message;
if (!$mail->send()) {
echo 'Mail Error!';
exit;
} else {
echo 'Message has been sent!';
}
}
&GT;
我也知道我应该为可接受的文件扩展名创建一个数组(在这种情况下只有.jpg或.jpeg),但我也不确定如何以及在何处实现这些扩展名。
另外,我只更改了电子邮件中的$ to和$。为什么这总是无法发送?我要做的就是发送纯文本电子邮件,或者发送电子邮件附件,或者没有电子邮件附件。
答案 0 :(得分:1)
看起来您正在尝试从根/uploads
目录发送文件:
$mail->addAttachment(
'/uploads/' . $name,
在移动文件之前发送电子邮件会更容易,将$tmp_name
作为第一个参数传递给addAttachment()
方法。或者,可选地,确保在将文件移动到上载目录后指定文件的正确路径。 (猜测:"./uploads/$name"
- 点表示当前目录。)
此外,您可以尝试检查$mail->ErrorInfo
以了解错误的详细信息。