简体   繁体   中英

send_mail only works in terminal in django

I'm trying to get my website to send a email when a button is pressed. However, it only sends a email when I use send_mail in the shell and does nothing when the button is pressed.

I currently have the following in my settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST_USER = '#'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_PASSWORD = '#'

The # is of course only there for this question

In my html file I have

 <form method="post">
  {% csrf_token %}
  <button type="submit" name="place_order" class="btn btn-success">
   Place Order</button>
 </form>

the place_order links up with my views.py which checks whether or not the button is clicked

 checkout = request.POST.get('place_order')
        if checkout:
            send_mail('Django test mail', 'this is django test body', 
            '#', ['#'], fail_silently=False,)
            messages.info(request, f'Your order has been placed!') 

there is no value in post request named place_order because its a button , not a input so if statement would be false and send_mail wont be triggered:

 checkout = request.POST.get('place_order')
        if checkout: # <=== here
            send_mail('Django test mail', 'this is django test body', 
            '#', ['#'], fail_silently=False,)
            messages.info(request, f'Your order has been placed!') 

so if you change your HTML to something like:

<form method="post">
  {% csrf_token %}
  <input type="hidden" name="place_order" value="blablabla"/> # value shouldn't be empty
  <button type="submit" class="btn btn-success">
   Place Order</button>
 </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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