首页 > 解决方案 > 使用 PHP 电子邮件发送 PDF 文件

问题描述

我正在尝试使用以下代码尝试发送带有 PDF 附件的 PHP 电子邮件。

我收到消息“邮件已发送。谢谢你'。但是,没有发送电子邮件。

请有人告诉我/向我解释我哪里出错了?

谢谢

<?php 
if(isset($_POST['submit'])){
    $to = "example@example.com"; // this is your Email address
    $from = $_POST['email']; // this is the sender's Email address
    $subject = "Subject Here";
    $message = $_POST['message'];
    $file = $_POST['upload'];
   
    
    $headers = 'From: someone@gmail.com ' . "\r\n" .
    'Reply-To: someone@gmail.com   ' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
    
    $headers2 = "From:" . $to;
    mail($to, $subject, $message, $file, $email, $headers);
    echo "Mail Sent. Thank you.";
    // You can also use header('Location: thank_you.php'); to redirect to another page.
    }
?>

<!DOCTYPE html>
<head>
<title>Form submission</title>
</head>
<body>

<form action="" method="post">
Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
<input type="file" name="upload" accept="application/pdf,application/vnd.ms-excel" />
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html> 

标签: phphtml

解决方案


您的代码有很多问题,建议先查看官方网站的语法和文档。例如,您将 $file 作为参数传递给邮件函数,但邮件函数中没有 FILE 参数(https://www.php.net/manual/en/function.mail.php

然后,您不会将上传的 PDF 保存到任何要发送的磁盘。上传的文件是通过$_FILES变量而不是$_POST变量捕获的。你也需要看到这一点。

然后发送任何文件都是一项棘手的工作,您可以通过使用一些库函数来简化您的工作,例如PHPMailer尝试引用这些函数。


推荐阅读