Django 2.0.9 - Upload file and send by email

1

I'm new to Django and I'm creating a web environment that sends emails. I can send the email without the attachment, however I need to include attachment. I'm using the form with the FILE FIELD field, but when I send the email the following error occurs:

'InMemoryUploadedFile' object does not support indexing

Below is view.py:

. . .

@login_required
def enviar_email(request):
    context = {}
    if request.method == 'POST':
        form = Email(request.POST, request.FILES) 
        if form.is_valid():
            emails = User.objects.filter(tipo_produto=form.cleaned_data['tipo_produto'])
            lista_email=[""]*emails.count()
            i = 0
            if emails.count() != 0:

                for email in emails:
                    envio = Transacao(
                        tipo_produto = form.cleaned_data['tipo_produto'],
                        mensage = form.cleaned_data['mensage'],
                        email = email.email)
                    envio.save()

                    lista_email[i] = emai.email
                    i = i + 1

                form.send_mail(lista_email, request.FILES['file']) # Aciona função do formulário que realiza o envio de email.
                form = Email()
                messages.success(request, 'Email envio com sucesso!') 
            else:
                messages.info(request, 'Nenhum email está cadastrado para o produto escolhido!')
    else: # caso contrário preenche formulário em branco
        form = Email()

    context['form'] = form

    template_name = 'courses/email.html' 
    return render(request, template_name, context)

The following forms.py:

from django import forms 
from django.core.mail import send_mail 
from django.conf import settings
from projeto.core.mail import send_mail_template

TIPO_CHOICES = (
        (1, 'Clipping - Diário'),
        (2, 'Epidemiológico - Quinzenal'),
        (3, 'Monitoramento - Semanal'),
    )

class Email(forms.Form):

    tipo_produto = forms.ChoiceField(
        choices=TIPO_CHOICES, label='Produto', widget=forms.Select(), required=True
    )
    mensage = forms.CharField(label='Mensagem', widget=forms.Textarea) # Campo texto de área
    file = forms.FileField(label='Arquivo')

    def send_mail(self, lista_email, arquivo):
        subject = 'Envio de Produto'
        context = {
            'mensage': self.cleaned_data['mensage']
        }

        template_name = 'courses/contact_email.html' # Template de email

        send_mail_template(subject, template_name, context, lista_email, arquivo)

Below is send_mail_template.py:

from django.template.loader import render_to_string
from django.template.defaultfilters import striptags
from django.core.mail import EmailMultiAlternatives
from django.conf import settings

def send_mail_template(subject, template_name, context, recipient_list, 
    from_email=settings.DEFAULT_FROM_EMAIL, fail_silently=False, files=None):

    message_html = render_to_string(template_name, context)

    message_txt = striptags(message_html)

    email = EmailMultiAlternatives(
        subject=subject, body=message_txt, from_email=from_email, 
        to=recipient_list
    )

    if files:
        email.attach(files.name, files.read(), files.content_type)

    email.attach_alternative(message_html, "text/html")
    email.send(fail_silently=fail_silently) 

Follow the email.html below:

{% extends "base.html" %}

{% block content %}
<div class="content">
    <div class="pure-g-r content-ribbon">
        <div class="pure-u-1">
            <h3>Email para envio de produto</h3>
            <form action="#contato" class="pure-form pure-form-aligned" enctype="multipart/form-data" method="post">
                {% csrf_token %}
                <fieldset>
                    {% for field in form %}
                    <div class="pure-control-group">
                        {{ field.label_tag }}
                        {{ field }}
                        {% if field.errors %}
                        <ul class="errorlist">
                            {% for error in field.errors %}
                            <li>{{ error }}</li>
                            {% endfor %}
                        </ul>
                        {% endif %}
                    </div>
                    {% endfor %}
                    <div class="pure-controls">
                        <button type="submit" class="pure-button pure-button-primary">Enviar</button>
                    </div>
                </fieldset>
            </form>
        </div>
    </div>
</div>
{% endblock %}

Can you help me solve this problem?

    
asked by anonymous 28.10.2018 / 15:27

0 answers