Attachments sent with mail are not opening

Hello, I’ve started a project and it has a feature of sending mails after submitting form. User logs in, fills and submits form. Form renders in the index page and from index page user can reach the detail page for every post (meeting). I send mails as templates and mail content is dynamic, every reciever (selected in the form) recieves their own mail. This form has a file input and I can attach files to the mail and recievers get the mail with attachment but can not open. for example I send a 13kb pdf file but in the inbox it seems as 244 bayt and cannot be open. (content of the email is correct, type of the attachment is correct, name of it is also correct ). Where should I look for this problem. I am lost here and every respond is appreciated.
Here is the code I am using and if I need to share more please tell me.

view for creating meeting (toplanti in my language):

def toplantiekle(request):
    toplanti = Toplanti.objects.all()
    if request.method == 'POST':
        form = ToplantiForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            tarih = form.cleaned_data['tarih']
            konu = form.cleaned_data['konu']
            katilimcilar = form.cleaned_data['katilimci']
            for katilimci in katilimcilar:
                yeni_toplanti = form.save(commit=False)
                user_profile = Profil.objects.get(user=request.user)
                yeni_toplanti.profil = user_profile
                yeni_toplanti.save()
                form.save_m2m()

                template = render_to_string('toplantiapp/email.html',{
                    'isim': katilimci.katilimci,
                    'tarih': tarih,
                    'konu': konu,
                    'katilimci': katilimci,
                })
                plain_message = strip_tags(template)

                email = EmailMessage(
                    'Toplantı Bildirimi',
                    plain_message,
                    settings.EMAIL_HOST_USER,
                    [katilimci.mail],
                )
                
                for file in request.FILES.getlist('dosya_yukle'):
                    email.attach(file.name, file.read(), file.content_type)

                # email.fail_silently = False
                email.send()

            return redirect('toplantiapp:index')
        else:
            print(form.errors)
    else:
        form = ToplantiForm()
    return render(request, 'toplantiapp/toplantiekle.html', {
        'form':form
    })

this is the form that I use for creating meeting:

class ToplantiForm(forms.ModelForm):
    katilimci = forms.ModelMultipleChoiceField(queryset=Katilimci.objects.all(), required=True)
    class Meta:
        model = Toplanti
        fields = ('konu','tarih','katilimci','dis_katilimci','dosya_yukle','aciklama')
        widgets = {
            'konu':forms.TextInput(attrs={"placeholder":"Toplantının Konusu","style":"height:32px; border:1px solid #A0A0A0; border-radius:3px"}),
            'aciklama':forms.Textarea(attrs={'cols':50,'rows':25, 'placeholder':'Açıklama','style':'width:100%; border:solid 1px #A0A0A0 ; margin-bottom:10px; border-radius:3px; resize: none;'}),
            'tarih':forms.DateTimeInput(attrs={"type":"text", "onfocus":"(this.type='datetime-local')","placeholder":"Tarih","id":"tarih"}),
            'dis_katilimci':forms.TextInput(attrs={"placeholder":"TGS Dışı Katılımcılar","style":"height:32px; border:solid 1px #A0A0A0; border-radius:3px;"}),
            'dosya_yukle':forms.FileInput(attrs={"placeholder":"Dosya Yükle","style":"display:none; border:1px solid #D8D8D8; padding-left:2p; padding-top:10px; padding-bottom:12px; padding-right;52.8%; background-image: url('https://upload.wikimedia.org/wikipedia/commons/thumb/c/cf/Upload_alt_font_awesome.svg/1024px-Upload_alt_font_awesome.svg.png'); background-position:98%; background-repeat: no-repeat; background-size: 25px;","id":"dosya_ekleme","name":"dosya_ekleme","class":"dosya_ekleme"}),
            'katilimci':forms.CheckboxSelectMultiple(attrs={"placeholder":"TGS Katılımcıları","class":"katilimciselect"}) # bunun classını katılımcıselect'ten değiştirdim
        }
        labels = {
            'konu':'formkonu',
            'tarih':'tarih',
            'katilimci':'katilimci',
            'aciklama':'aciklama',
        }

email configuration in settings.py:

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER ='mailsend@gmail.com'
EMAIL_HOST_PASSWORD = 'mypassword'

Thank you from now :slight_smile:

How are you verifying this? Are you looking at the raw text being sent via smtp?

If I had to debug something like this, I’d use either the console or file mail handler and visually inspect the email being generated to ensure its validity.

Try it with a couple of very small attachments first, just to see what you get.

1 Like

I am sending mail to myself, email itself is already template and it is something like this:

<body style="text-decoration: none; background-color: gray;">
    Hello {{ name }}

    You are reading a reminder email for your meeting.

    Date: {{ date }}

    Subject of the Meeting: {{ subject }}

    test.v1
    
    Mail Testing
</body>

I’ve translated the objects this is why they are different from the view. And the mail that sent is correct for every reciever (I’ve tried different machines and recievers, with or without antivirus or control program). The mail I get has the same attachment I attached (same name, extension, type) but cannot be opened I don’t know why but I suspect the reason is the attachment procces because there is a big size difference.

and I am not sure I am able to do this right now but it is a good for me to start. Now I know where to start, thank you :slight_smile:

and now I’ve tried it with a 1 bayt txt file and file sent as 220 bayt txt file and it has no content. I am not realy sure where is the problem …

Hi, when saving the form, I suppose the file is saved in the storage along with the dosya_yukle model field.

I think this saving does a file.read(), so that the file pointer is at the end file after form saving.

As a consequence, the file.read() in the view reads the file from its end, leading to empty attachment.

Let’s try, in the for loop, before adding the file as an attachment to do file.seek(0)

1 Like

You are a true lifesaver. Thank you very much I was looking for this even I don’t know what I am exactly looking for… :slight_smile: