简体   繁体   English

使用Django从表单POST数据发送电子邮件

[英]Sending emails from form POST data using Django

So I've written HTML code for a form that I want to send emails with using Django. 因此,我已经为要使用Django发送电子邮件的表单编写了HTML代码。 From everything I have seen, the Django email is being used with Django's own form module in order to send emails with the data. 从我所看到的一切来看,Django电子邮件正与Django自己的表单模块一起使用,以便发送包含数据的电子邮件。 I am wondering if it is possible at all to keep my current HTML form and access its POST data to use with Django's email functions? 我想知道是否可以保留我当前的HTML表单并访问其POST数据以与Django的电子邮件功能一起使用?

You don't need to use a django Form object (like a ContactForm) : your form's POST data can be accessed through the request argument of your view. 您不需要使用Django Form对象(例如ContactForm):可以通过视图的request参数访问表单的POST数据。

This example was taken from the documentation ( https://docs.djangoproject.com/en/dev/topics/email/#preventing-header-injection ) : 此示例摘自文档( https://docs.djangoproject.com/en/dev/topics/email/#preventing-header-injection ):

from django.core.mail import send_mail, BadHeaderError

def send_email(request):
    subject = request.POST.get('subject', '')
    message = request.POST.get('message', '')
    from_email = request.POST.get('from_email', '')
    if subject and message and from_email:
        try:
            send_mail(subject, message, from_email, ['admin@example.com'])
        except BadHeaderError:
            return HttpResponse('Invalid header found.')
        return HttpResponseRedirect('/contact/thanks/')

    else:
        # In reality we'd use a form class
        # to get proper validation errors.
        return HttpResponse('Make sure all fields are entered and valid.')

It's quick and dirty, but works fine. 它既快又脏,但效果很好。

However, it looks like you're still struggling with form handling inside django. 但是,看起来您仍然在django中进行表单处理方面的工作。 You may want to work on that before moving on. 您可能需要先进行处理,然后再继续。

Good luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM