-1

I started fresh in programming and tried to send an email using php with a csv file as an attachment. Right now, after pressing "submit", I receive an email with the necessary information, but the attached csv file is empty and I don't know why.

I've tried several things and failed and would like to know the solution from this point on:

<?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://stackoverflow.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>";

} 
?>

Thanks in advance!

ADyson
  • 57,178
  • 14
  • 51
  • 63
Jax667
  • 1
  • 1
  • 1
    Save yourself the fiddly and error-prone task of building the email by hand and just use PHPMailer, which makes adding an attachment _much_ easier. – ADyson Dec 13 '21 at 22:03

1 Answers1

0

Using PHPMailer

PHPMailer uses SMTP, so you have to create an email and password as a sender email then set your parameters

    <?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}";
}

let me know if you have any questions

Mohamed EL-Gendy
  • 566
  • 4
  • 11
  • `PHPMailer uses SMTP`...not necessarily. It can be configured to use `mail()` under the hood. See https://stackoverflow.com/questions/39029466/what-is-the-difference-between-ismail-and-issmtp. – ADyson Dec 13 '21 at 22:38
  • Yes, but in most cases `mail()` arrives with errors and that was my experience – Mohamed EL-Gendy Dec 13 '21 at 22:42
  • what do you mean "arrives with errors" exactly? Anyway that's your experience, not the OP's. They were sending email ok until they tried to make the attachment. PHPMailer makes the process of adding the attachment simpler. That can solve the OP's problem, without suggesting that it's necessary to convert their entire mail system to using an SMTP service. 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 and likely haven't even got. – ADyson Dec 13 '21 at 22:52
  • Also you simply made a false statement because PHPMailer does not only use SMTP...which was why I commented originally. – ADyson Dec 13 '21 at 22:52
  • Thank you for that answer and the suggestions, but I'd prefer a direct solution to the posted code. What exactly did I do wrong or did you insinuate that there is nothing wrong with the code? – Jax667 Dec 13 '21 at 23:22
  • I'll try to solve this issue using phpmailer – Jax667 Dec 14 '21 at 00:40
  • 1
    Thanks, @ADyson , I got your advice about `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 ` – Mohamed EL-Gendy Dec 14 '21 at 14:09
  • @Jax667 I was trying to send emails with `mail()` and add an attachment using PHPMailer and in most cases, the email arrive without any attachment and without any errors shown from PHPMailer – Mohamed EL-Gendy Dec 14 '21 at 14:11