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

标签 php

我正准备为一个网站创建一个表单页面,该页面需要用户填写许多字段并将其发送到指定的电子邮件。

到目前为止,我已经创建了一个虚拟的 php 电子邮件页面,它使用 Google 的 SMTP 获取您的消息、1 个附件和收件人电子邮件地址。

这是我的 uploadtest.html 代码:

<body>

<h1>Test Upload</h1>

<form action="email.php" method="get">
Message: <input type="text" name="message">
Email: <input type="text" name="email"><br>
Attach File: <input type="file" name="file" id="file">
<input type="submit">
</form>


</body>

uploadtest.html 是用户将看到的内容

这是 email.php 的代码:

<?php
    require("class.phpmailer.php");

    $mail = new PHPMailer();

    $recipiant = $_GET["email"];
    $message = $_GET["message"];

    $mail->IsSMTP();  // telling the class to use SMTP
    $mail->SMTPAuth   = true; // SMTP authentication
    $mail->Host       = "smtp.gmail.com"; // SMTP server
    $mail->Port       = 465; // SMTP Port
    $mail->SMTPSecure = 'ssl';
    $mail->Username   = "xxxxx@gmail.com"; // SMTP account username
    $mail->Password   = "xxxxxxxx";        // SMTP account password


    $mail->AddAttachment($_FILES['tmp_name']); //****HERE'S MY MAIN PROBLEM!!!


    $mail->SetFrom('cinicraftmatt@gmail.com', 'CiniCraft.com'); // FROM
    $mail->AddReplyTo('cinicraftmatt@gmail.com', 'Dom'); // Reply TO

    $mail->AddAddress($recipiant, 'Dominik Andrzejczuk'); // recipient email

    $mail->Subject    = "First SMTP Message"; // email subject
    $mail->Body       = $message;





    if(!$mail->Send()) {
      echo 'Message was not sent.';
      echo 'Mailer error: ' . $mail->ErrorInfo;
    } else {
      echo 'Message has been sent.';
    }
?>

因此,据我所知,PHPMailer 的 AddAttachment() 方法将您要附加的文件 DIRECTORY 的 URL 作为参数。这就是我的主要问题所在。

变量的名称应该是什么,它会获取我上传的文件 (dir/upload.jpg) 的位置,以便我可以将它用作 AddAttachment() 方法中的参数?

最佳答案

不,它不需要 URL 或目录。它采用指向 FILE 的直接路径。

例如

$mailer->AddAttachment(
    '/path/to/file/on/your/server.txt',
    'name_of_file_in_email',
    'base64',
    'mime/type'
);

路径是不言自明的。 name_of_file_in_email 允许您“重命名”文件,这样您就可以在服务器上加载名为“foo.exe”的文件,它可以在客户端收到的电子邮件中显示为“bar.jpg” .

您的问题是您尝试附加上传的文件,但使用了错误的来源。应该是

<input type="file" name="thefile" />
                         ^^^^^^^
$_FILES['thefile']['tmp_name']
         ^^^^^^^

注意字段名称与 $_FILES 的关系。

关于php - 通过 PHPMailer 发送带附件的电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17818417/

相关文章:

php - 从 ubuntu 服务器 php 上的 mysql 开始

php - MySQL/PHP - 多层类别结构

php - 如何在网页上隐藏下载源

php - ZeroMQ 和 PHP-FPM

php - Laravel:页面上带有 url 参数的表单

php - 通过 PHP 执行。我无法将输出(stderr)放入文件中

javascript - 如何更改 HTML 标记内模板化字符串的日期格式

php - 使用 PHP include 时改变 CSS sprite 导航栏的状态

php - 如何将用户从下拉选择框列表中选择的选项的值存储到 mysql 数据库中?

php - 根据三列(city+streetaddress+state)值选择相似地址记录连同mysql中的join操作