Sending a emqil with an attachment from django
djando gurus! I need your help! I have an app. It should get the file from the form, then save it to the database and send it by email. I made a model, a form and a view. It seems that everything works fine, the file is saved in the database, a message with an attachment is sent. But the file size in the email attachment = 0 bytes and there is nothing to open it in any email client. What am I doing wrong? Here is a bit of my code:
models.py:
class Email(models.Model):
...
email = models.EmailField(default='...', verbose_name='Email')
forms.py:
class EmailForm(forms.ModelForm):
class Meta:
model = Email
fields = [..., 'time', 'file', ...]
widgets = {
...
'file': forms.FileInput(),
}
views.py:
def sender(request):
if request.method == 'POST':
form = EmailForm(request.POST, request.FILES)
if form.is_valid():
email_save = form.save()
...
email_date = request.POST.get('date', '')
html_content = render_to_string('email_sender/email_tmpl.html', {
...
})
txt_content = strip_tags(html_content)
email = EmailMultiAlternatives(
email_title,
txt_content,
settings.EMAIL_HOST_USER,
[email_adress]
)
email.attach_alternative(html_content, 'text/html')
if request.FILES:
email_file = request.FILES['file']
email.attach(email_file.name, email_file.read(), email_file.content_type)
email.send()
return redirect(sender)