Django Email Attachment

Отправляем письма в Django с прикрепленным файлом

------forms.py----------
from django import forms

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)
-------views.py--------------

def send_email(request):
    if request.method != 'POST':
        form = EmailForm()
        return render_to_response('admin/Email.html', {'email_form': form})
	
    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(attach.name, attach.read(), attach.content_type)
            mail.send()
            return render_to_response('admin/Email.html', {'message': 'Sent email to %s'%email})
       except:
           return render_to_response('admin/Error.html', {'message': 'Either the attachment is too  big or corrupt'})
       return render_to_response('admin/Email.html', {'message': 'Unable to send email. Please try again later'})
---------template------

{% extends "admin/base_site.html" %}

{% block stylesheet %}{% load adminmedia %}{% admin_media_prefix %}css/dashboard.css{% endblock %}
{% block bodyclass %}dashboard{% endblock %}
{% block coltype %}colMS{% endblock %}

{% if not is_popup %}{% block breadcrumbs %}<div class="breadcrumbs"><a href="../">Home</a> › Send Email</div>{% endblock %}{% endif %}

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

<label> </label><label> </label><label> </label>
<input type ="submit"  name = "send" value = "Send"/>
</form>
{% endif %}
{% endblock content %}

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *