繁体   English   中英

通过PHPMailer发送带有附件的电子邮件

[英]Sending an email with an attachment via PHPMailer

我无法让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!';
    }
}

?>

我也知道我应该为可接受的文件扩展名(在这种情况下仅是.jpg或.jpeg)创建一个数组,但是也不确定如何以及在何处实现这些扩展名。

另外,我只更改了$ to和$ from电子邮件。 为什么这总是发送失败? 我要做的就是发送带有电子邮件附件或不带电子邮件附件的纯文本电子邮件。

看起来您正在尝试从/uploads根目录发送文件:

$mail->addAttachment(
    '/uploads/' . $name,

在移动文件之前,将$tmp_name作为第一个参数传递给addAttachment()方法将更容易发送电子邮件。 或者(可选),在将文件移至上载目录后,请确保为其指定正确的路径。 "./uploads/$name"猜测: "./uploads/$name" -点表示当前目录)。

另外,您可以尝试检查$mail->ErrorInfo以获得错误的详细信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM