L
L
leni_m2017-09-05 12:49:03
PHP
leni_m, 2017-09-05 12:49:03

How to send email attachment in php?

Hello Toaster!
I'm trying to send an attachment (pdf file to mail) with regular php.
I found the code on the internet and wrote a function

public static function sendEmailInvoicePdf($filename, $email)
    {
        $name        = "Название здесь идет";
        $to          = "$name <$email>";
        $from        = "Вася";
        $subject     = "Тема";
        $mainMessage = "Привет,я сообщение с pdf файлом";
        $fileatt     = $filename; // Расположение файла
        $fileatttype = "application/pdf";
        $fileattname = "test.pdf"; //Имя, которое вы хотите использовать для отправки, или вы можете использовать то же имя
        $headers     = "From: $from";
// Открываем и читаем файл в переменную.
        $file = fopen($fileatt, 'rb');
        $data = fread($file, filesize($fileatt));
        fclose($file);
// Это прикрепляет файл
        $semi_rand     = md5(time());
        $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
        $headers      .= "\nMIME-Version: 1.0\n" .
            "Content-Type: multipart/mixed;\n" .
            " boundary=\"{$mime_boundary}\"";
        $message = "Это multi-part сообщение в формате MIME․\n\n" .
            "-{$mime_boundary}\n" .
            "Content-Type: text/html; charset=\"utf-8 \n" .
            "Content-Transfer-Encoding: 7bit\n\n" .
            $mainMessage  . "\n\n";
        $data = chunk_split(base64_encode($data));
        $message .= "--{$mime_boundary}\n" .
            "Content-Type: {$fileatttype};\n" .
            " name=\"{$fileattname}\"\n" .
            "Content-Disposition: attachment;\n" .
            " filename=\"{$fileattname}\"\n" .
            "Content-Transfer-Encoding: base64\n\n" .
            $data . "\n\n" .
            "-{$mime_boundary}-\n";
// Отправить письмо
        if(mail($to, $subject, $message, $headers))
        {
            echo "Письмо отправлено.";
        } else {
            echo "При отправке почты произошла ошибка.";
        }
    }

In general, a valid pdf comes to Yandex mail, $ subject (the subject of the letter) is also displayed, but the body of the message is not displayed.
Mail.ru does not receive a letter at all.
Krakozyabry comes to Outlook and the pdf file cannot be opened - it writes an error, type clumsy pdf.
Is there a postal framework to use or do I have some errors?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question