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

Mat*_*zuk 5 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>
Run Code Online (Sandbox Code Playgroud)

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.';
    }
?>
Run Code Online (Sandbox Code Playgroud)

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

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

Mar*_*c B 8

不,它不需要 URL 或目录。它采用文件的直接路径。

例如

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

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

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

<input type="file" name="thefile" />
                         ^^^^^^^
$_FILES['thefile']['tmp_name']
         ^^^^^^^
Run Code Online (Sandbox Code Playgroud)

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