| | 117 | |
|---|
| | 118 | Preventing header injection |
|---|
| | 119 | =========================== |
|---|
| | 120 | |
|---|
| | 121 | **New in Django development version.** |
|---|
| | 122 | |
|---|
| | 123 | `Header injection`_ is a security exploit in which an attacker inserts extra |
|---|
| | 124 | e-mail headers to control the "To:" and "From:" in e-mail messages that your |
|---|
| | 125 | scripts generate. |
|---|
| | 126 | |
|---|
| | 127 | The Django e-mail functions outlined above all protect against header injection |
|---|
| | 128 | by forbidding newlines in header values. If any ``subject``, ``from_email`` or |
|---|
| | 129 | ``recipient_list`` contains a newline, the e-mail function (e.g. |
|---|
| | 130 | ``send_mail()``) will raise ``ValueError`` and, hence, will not send the |
|---|
| | 131 | e-mail. It's your responsibility to validate all data before passing it to the |
|---|
| | 132 | e-mail functions. |
|---|
| | 133 | |
|---|
| | 134 | Here's an example view that takes a ``subject``, ``message`` and ``from_email`` |
|---|
| | 135 | from the request's POST data, sends that to admin@example.com and redirects to |
|---|
| | 136 | "/contact/thanks/" when it's done:: |
|---|
| | 137 | |
|---|
| | 138 | from django.core.mail import send_mail |
|---|
| | 139 | |
|---|
| | 140 | def send_email(request): |
|---|
| | 141 | subject = request.POST.get('subject', '') |
|---|
| | 142 | message = request.POST.get('message', '') |
|---|
| | 143 | from_email = request.POST.get('from_email', '') |
|---|
| | 144 | if subject and message and from_email \ |
|---|
| | 145 | and '\n' not in subject and '\n' not in message |
|---|
| | 146 | and '\n' not in from_email: |
|---|
| | 147 | send_mail(subject, message, from_email, ['admin@example.com']) |
|---|
| | 148 | return HttpResponseRedirect('/contact/thanks/') |
|---|
| | 149 | else: |
|---|
| | 150 | # In reality we'd use a manipulator |
|---|
| | 151 | # to get proper validation errors. |
|---|
| | 152 | return HttpResponse('Make sure all fields are entered and valid.') |
|---|
| | 153 | |
|---|
| | 154 | .. _Header injection: http://securephp.damonkohler.com/index.php/Email_Injection |
|---|