Django documentation is lacking in giving an example for sending an email with attachment. Hopefully this code helps those who are trying to send email with attachments
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | ------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 %}
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
you forget
#
Great snippet! Really simple. However, I would strongly suggest not using an empty
except:
statement. Find out what errors can happen that aren't "python related" and write them in theexcept
statement. Alternatively you can do this:#
Please login first before commenting.