Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

html - Gmail sending with attachment in Django

I am trying to send Gmail with attachments also in Django.

here my views.py:

def index(request):
    if request.method != 'POST':
        form = EmailForm()
        context = {'email_form': form}
        return render(request, 'app/index.html', context)

    form = EmailForm(request.POST, request.FILES)
    if form.is_valid():
        subject = form.cleaned_data['subject']
        message = form.cleaned_data['message']
        email = form.cleaned_data['email']
        attach = request.FILES['attach']
        try:
            mail = EmailMessage(subject, message, settings.EMAIL_HOST_USER, [email])
            mail.attach_file(attach.name, attach.read(), attach.content_type)
            mail.send()
            context = {'message': 'email sended'}
            print("email sended")
            return render(request, 'app/email_template.html', context)
        except:
            context = {'message': 'Either the attachment is too  big or corrupt'}
            print("Either the attachment is too  big or corrupt")
            return render(request, 'app/index.html', context)
        context = {'message': 'Unable to send email. Please try again later'}
        return render(request, 'app/index.html', context)

forms.py:

class EmailForm(forms.Form):
    email = forms.EmailField()
    subject = forms.CharField(max_length=100)
    attach = forms.Field(widget = forms.FileInput)
    message = forms.CharField(widget = forms.Textarea)

template:

<div class="container-fluid">
    <div class="col-xl-4">
        <h1>Welcome in django's world</h1>

        {{message}}

        <form method="POST" action ="." enctype="multipart/form-data">
        {% csrf_token %}
        <br></br>
        {{email_form.as_p}}

        <label>&nbsp;</label><label>&nbsp;</label><label>&nbsp;</label>
        <input type ="submit"  name = "send" value = "Send"/>
        </form>

    </div>
</div>

Now each and every time I tried to sent mail, it shows Either the attachment is too big or corrupt, which means it goes by the except: block, instead of the try block.I just print the exception msg, it says

__init__() takes from 1 to 2 positional arguments but 5 were given

Now how can I solve this problem such that Gmail will be sent successfully?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...