从 html 表单发送带有 csv 附件的电子邮件

Posted

技术标签:

【中文标题】从 html 表单发送带有 csv 附件的电子邮件【英文标题】:Sending an email with a csv attachment from an html form 【发布时间】:2022-01-17 07:45:02 【问题描述】:

我刚开始编程,并尝试使用 php 发送一封带有 csv 文件作为附件的电子邮件。现在,按“提交”后,我收到一封包含必要信息的电子邮件,但附加的 csv 文件是空的,我不知道为什么。

我尝试了几件事,但都失败了,想知道从现在开始的解决方案:

<?php
if(isset($_POST['Absenden']))

    $firstname = $_POST ['firstname'];
    $lastname = $_POST ['lastname'];
    $email = $_POST ['email'];
    $phone = $_POST ['phone'];
    $job = $_POST ['job'];
    $address = $_POST ['address'];
    $message = $_POST ['message'];

    $subject= "Schüleranmeldung $firstname $lastname";
    $recipient = "mymail";
    
    $seperator = md5(time());
    $eol = "\r\n";
    // https://***.com/questions/12301358/send-attachments-with-php-mail
    $mailheader = "From: $email " . $eol;
    $mailheader .= "MIME-Version: 1.0 " . $eol;
    $mailheader .= "Content-Type: multipart/mixed; boundary=\"" . $seperator . "\"" . $eol . $eol;
    
    /* The email body */
    
    $txt = "--" . $seperator . $eol;
    $txt .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
    $txt .= "Content-Transfer-Encoding: 7bit" . $eol;
    $txt .= "Anmerkung: \n $message \n\n Name: $lastname \n Vorname: $firstname \n Beruf: $job \n Telefonnummer: $phone \n Adresse: $address" . $eol;
    $txt .= "--" . $seperator . $eol;

    //Content of csv file (two lines)
    $csv = "Vorname,Nachname,Address,Email,Telefon,Beruf\n";
    $csv .= "$firstname,$lastname,$address,$email,$phone,$job\n";
    
    // $content = file_get_contents($file);
    $content = chunk_split(base64_encode($csv));
    
    $FileName = $lastname."-".$firstname."-".date("d-m-y-h:i:s").".txt";
    
    $txt .= "Content-Type: application/octet-stream; name=\"" .   $FileName . "\"" . $eol;
    $txt .= "Content-Transfer-Encoding: base64" . $eol;
    $txt .= "Content-Disposition: attachment" . $eol;
    $txt .= $content . $eol . $eol;
    $txt .= "--" . $seperator . "--";

        mail($recipient, $subject, $txt, $mailheader);

        echo "<pre>" . $csv . "</pre>";
        echo "<pre>" . $content . "</pre>";

 
?>

提前致谢!

【问题讨论】:

省去手动构建电子邮件的繁琐且容易出错的任务,只需使用 PHPMailer,这使得添加附件非常更容易。 【参考方案1】:

使用PHPMailer

PHPMailer 使用 SMTP,因此您必须创建一个电子邮件和密码作为发件人电子邮件,然后设置您的参数

    <?php
//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

//Load Composer's autoloader
require 'vendor/autoload.php';

//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);

try 
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
$mail->isSMTP();                                            //Send using SMTP
$mail->Host       = 'smtp.example.com';                     //Set the SMTP server to send through
$mail->SMTPAuth   = true;                                   //Enable SMTP authentication
$mail->Username   = 'user@example.com';                     //SMTP username
$mail->Password   = 'secret';                               //SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
$mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

//Recipients
$mail->setFrom('from@example.com', 'Mailer');
$mail->addAddress('joe@example.net', 'Joe User');     //Add a recipient
$mail->addAddress('ellen@example.com');               //Name is optional
$mail->addReplyTo('info@example.com', 'Information');
$mail->addCC('cc@example.com');
$mail->addBCC('bcc@example.com');

//Attachments
$mail->addAttachment('/var/tmp/file.tar.gz');         //Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    //Optional name

//Content
$mail->ishtml(true);                                  //Set email format to HTML
$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

$mail->send();
echo 'Message has been sent';
 catch (Exception $e) 
echo "Message could not be sent. Mailer Error: $mail->ErrorInfo";

如果您有任何问题,请告诉我

【讨论】:

PHPMailer uses SMTP...不一定。它可以配置为在后台使用mail()。见***.com/questions/39029466/…。 是的,但在大多数情况下mail() 会出现错误,这是我的经验 你到底是什么意思“到达错误”?无论如何,这是您的经验,而不是OP。在他们尝试制作附件之前,他们一直在发送电子邮件。 PHPMailer 使添加附件的过程更简单。这可以解决 OP 的问题,而不是暗示有必要将他们的整个邮件系统转换为使用 SMTP 服务。不要将你的经验与其他人的经验混为一谈,坚持解决他们提出的问题,而不是他们没有提出的问题,甚至可能没有解决的问题。 另外你只是做了一个错误的陈述,因为 PHPMailer 不仅使用 SMTP ......这就是我最初评论的原因。 谢谢@ADyson,我得到了你关于Don't conflate your experiences with other people's, and stick to solving the problems they've asked about, not the ones they haven't asked about 的建议

以上是关于从 html 表单发送带有 csv 附件的电子邮件的主要内容,如果未能解决你的问题,请参考以下文章