W
W
Web Building2020-12-13 23:41:18
PHP
Web Building, 2020-12-13 23:41:18

I am using PHPMailer. Why does ( $mail->addAttachment ) attach 2 identical files instead of different ones??

I attach in the letter, let's say 3 different files ...., but 2 identical ones come! Apparently the 3rd file "overwrites" the first 2. But why then does it come in only 2 copies, and not three?
As many advise, if you write in a standard way, if you use PHPMailer - it does not save!

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


Or something like:
$mail->addAttachment($_FILES['attachfile'][0]['tmp_name'], $_FILES['attachfile']['name']);
$mail->addAttachment($_FILES['attachfile'][1]['tmp_name'], $_FILES['attachfile']['name']);

- does not help at all! This is also not at all the same, because. only the body (text), letters, without attached files comes! Only the message in the letter comes, without any attached files. Please help me figure it out! How to attach several files with different (with all) extensions, for example: JPG, JPEG, PNG, GIF, txt, WEBP, docx, BMP, video...

Here are the required lines from the HTML form:

<form action="mysite.com/submit.php" method="POST" id="modalForm" name="feedback_form" class="contact_form" enctype="multipart/form-data">
    <input type="email" name="user_email" placeholder="[email protected]" required id="email" />
    <input type="file" id="file" name="attachfile[]" value="1" class="upload_files" multiple="multiple" />
    <button type="submit" id="btnSend" name="sendMail" class="submit">Submit Form</button>
</form>


HTML form handler, submit.php

use PHPMailer\PHPMailer\PHPMailer;   // создайте класс PHPMailer
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception; 
        
require_once "/home/homexnmx/public_html/vendor/autoload.php";
        
$email = $_POST['user_email'] = htmlspecialchars(stripslashes($_POST['user_email'])); 
         
$mail = new PHPMailer;  // по умолчанию используется php "mail()"
        
$mail->CharSet = 'UTF-8';
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = "smtp.yandex.ru";
$mail->SMTPAuth = true;
$mail->Username = "отпарвитель@yandex.ru";  // Имя пользователя и пароль
$mail->Password = "*****";
$mail->SMTPSecure = "ssl";
$mail->Port = 465;
$mail->From = "отправитель@yandex.ru";
$mail->FromName = "имя отправителя";
$mail->addAddress('получатель@mysite.com', 'Homexnmx');  // Имя получателя
$mail->isHTML(true);
$mail->Subject = 'Из модальной формы - adaptive.php';
        
$message = "<b>Email:</b>&emsp;$email<br>";  
                   
$mail->Body = $message;
   
//  Прикрепляются 2 одинаковых файла! Т.е. видимо 2-й затирает 1-й. 
if (!empty($_FILES['attachfile']['name'][0]))
{
    $target_file = count($_FILES['attachfile']['name']);  // $tempFiles
    for ($i = 0; $i < $target_file; $i++) { // получаем количество файлов с массива  // $tempFiles
        if ($_FILES['attachfile']['error'][$i] == 0) { // нет ошибки при передаче файла - продолжаем!
            if (!$mail->AddAttachment($_FILES['attachfile']['tmp_name'][$i], $_FILES['attachfile']['name'][$i], 'base64', $_FILES['attachfile']['type'][$i])) die($mail->ErrorInfo);
        }    $filename = "./uploads/". $_FILES['attachfile']["name"]; 
                   $mail->addAttachment($_FILES['attachfile']['tmp_name'], $_FILES['attachfile']['name']);

        // $mail->addAttachment($_FILES['attachfile'][0]['tmp_name'], $_FILES['attachfile']['name']);
        // $mail->addAttachment($_FILES['attachfile'][1]['tmp_name'], $_FILES['attachfile']['name']);

        // $mail->addAttachment($_FILES['attachfile'][0]['tmp_name'], $_FILES['attachfile'][0]['name']);
        // $mail->addAttachment($_FILES['attachfile'][1]['tmp_name'], $_FILES['attachfile'][1]['name']);

        //  $mail->addAttachment($_FILES['attachfile'][0]['tmp_name']);          
        //  $mail->addAttachment($_FILES['attachfile'][0]['name'], 'new.jpg');
    }
}

if (!$mail->send()) {
    echo $resalt = 'Message could not be sent!';      // Сообщение не может быть отправлено!
}


            else
{
    echo $resalt = '✅ <b>Message has been sent!</b><br><br><pre><b><a href="https://mysite.com/aptive.php" style="text-decoration:none;">⬅ Back to page</a></b></pre>';
} 
            
$mail->clearAddresses();  // очищаем список адресатов 
$mail->clearAttachments();  // очищаем файлы вложений


And the last one is Ajax - adaptive.js

$(document).ready(function() {
        $('#modalForm').submit(function(e) {
        e.preventDefault();
        var resalt = document.querySelector('.resalt');
        var data = new FormData(jQuery('form')[0]);
        jQuery.each(jQuery('#file')[0].files, function(i, name) {
            data.append('attachfile[]', name);
        });

        jQuery.ajax({
        url: 'https://mysite.com/submit.php',
                data: data,
                cache: false,
                contentType: false,  // запретит jQuery устанавливать заголовок Content-Type и оставит это действие объекту XMLHttpRequest
                processData: false,  // предотвратит автоматическое преобразование данных FormData в строку запроса
                method: 'POST',
                type: 'POST', // For jQuery < 1.9
    
                success: function(data) {
                resalt = '✅<b>JS Your message sent!</b>';
    
                    $('.block-popup').hide('');
                    $('.note').css('display', 'block');
                    $('.resalt').html(data);
            },
    
                error: function(jqXHR, exception) {
                resalt = 'Mailer Error';
    
                    $('.block-popup').hide('');
                    $('.note').css('display', 'block');
                    $('.resalt').html(data);
            }
        });
    });
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
galaxy, 2020-12-14
@galaxy

First, you are re-adding the files when submitting the form. This code:

jQuery.each(jQuery('#file')[0].files, function(i, name) {
            data.append('attachfile[]', name);
        });

not needed at all, the files are already in data.
Secondly, show the normal PHP code, and what exactly it sends. Your code can't work because of this:
}    $filename = "./uploads/". $_FILES['attachfile']["name"]; 
                   $mail->addAttachment($_FILES['attachfile']['tmp_name'], $_FILES['attachfile']['name']);

(apparently, some artifacts of previous attempts).
Without this, the code as a whole looks working. Log (or directly to the browser) the $_FILES or $mail->getAttachments() array and see if everything attaches correctly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question