[Django]-Sending emails with attachment in django

34👍

The error traceback you’ve posted doesn’t seem to have anything to do with the actual code – it seems to be some sort of problem with middleware (presumably when rendering the 500 error page).

However, your error is probably caused by your use of the undefined variable name attach in the calls to mail.attach. You don’t have an attach variable – you’ve called the posted files image1 etc, so you should use those names.

mail.attach(image1.name, image1.read(), image1.content_type)
mail.attach(image2.name, image2.read(), image2.content_type)
mail.attach(image3.name, image3.read(), image3.content_type)

0👍

Send Mail with attachment in Django

forms.py

from django import forms


class SendMailForm(forms.Form):
    email_id = forms.EmailField()
    email_cc = forms.EmailField()
    email_bcc = forms.EmailField()
    subject = forms.CharField(max_length=200)
    msg = forms.CharField(widget=forms.Textarea)
    attachment = forms.FileField()

views.py

from django.core.mail import EmailMessage
from django.shortcuts import render, HttpResponse, HttpResponseRedirect

from .forms import SendMailForm


# Create your views here.
def simple_send_mail(request):
    if request.method == 'POST':
        fm = SendMailForm(request.POST or None, request.FILES or None)
        if fm.is_valid():
            subject = fm.cleaned_data['subject']
            message = fm.cleaned_data['msg']
            from_mail = request.user.email
            print(from_mail)
            to_mail = fm.cleaned_data['email_id']
            to_cc = fm.cleaned_data['email_cc']
            to_bcc = fm.cleaned_data['email_bcc']
            print(fm.cleaned_data)
            attach = fm.cleaned_data['attachment']
            if from_mail and to_mail:
                try:
                    mail = EmailMessage(subject=subject, body=message, from_email=from_mail, to=[to_mail], bcc=[to_bcc],
                                        cc=[to_cc]
                                        )
                    mail.attach(attach.name, attach.read(), attach.content_type)
                    mail.send()
                # except Exception as ex:
                except ArithmeticError as aex:
                    print(aex.args)
                    return HttpResponse('Invalid header found')
                return HttpResponseRedirect('/mail/thanks/')
            else:
                return HttpResponse('Make sure all fields are entered and valid.')
    else:
        fm = SendMailForm()
    return render(request, 'mail/send_mail.html', {'fm': fm})

settings.py

# Email Configurations

# DEFAULT_FROM_EMAIL = ''
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'example@abc.com'
EMAIL_HOST_PASSWORD = '************'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

send_mail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Mail</title>
</head>
<body>
    <form method="POST" action="" enctype="multipart/form-data">
        {% csrf_token %}
        <center><h1>Mail send from "{{request.user.email}}"</h1></center>
        {{fm.as_p}}
        <input type="submit" value="Send">
    </form>
</body>
</html>

Leave a comment