如何通过django表单在我的电子邮件中发送信息。现在,我只能在控制台output on my cmd
中看到信息模板:
{% extends 'base.html' %}
{% load widget_tweaks %}
{% block title %}
Contact Us
{% endblock %}
{% block content %}
<h2 class="mt-4 ml-4">Contact Me</h2>
<form method="post">
<div class="container mt-4">
{% csrf_token %}
<div class="col-md-4">
{{ form.subject.label }}
{% render_field form.subject class+="form-control" %}
</div>
<div class="col-md-4">
{{ form.email.label }}
{% render_field form.email type="email" class+="form-control" %}
</div>
<div class="col-md-4">
{{ form.message.label }}
{% render_field form.message class+="form-control" rows="4" cols="6" %}
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary mt-2 ml-3">Send</button>
</div>
</div>
</form>
{% endblock %}
forms.py:
from django import forms
class ContactForm(forms.Form):
email = forms.EmailField(required=True)
subject = forms.CharField(required=True)
message = forms.CharField(widget=forms.Textarea, required=False)
views.py:
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from .forms import ContactForm
def emailView(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
try:
send_mail(subject, message, email, ['yarik.nashivan@gmail.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, "email.html", {'form': form})
def successView(request):
return HttpResponse('Success! Thank you for your message. <p>You will be redirected to the main page in 3 seconds.</p> <meta http-equiv="refresh" content="3;url=/"> ')
别看它:fgkjdfldfjgndfkgndfskj vdafk kjdsjaf jjjfd jdsaf dj fdsjn dnjndfj jdffjk hdsffdfgfdb sfdf
答案 0 :(得分:2)
好吧,您正在使用console backend,这就是为什么您在控制台中看到该消息的原因。如果您使用SMTP backend,则可以将此电子邮件发送到您的帐户。为此,您需要这样配置:
首先,您需要在settings.py中更新后端:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="clickable" id="firstID">Placeholder text</div>
<div class="clickable" id="secondID">Placeholder text</div>
<div class="clickable" id="thirdID">Placeholder text</div>
然后更新EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
中的smtp配置:
settings.py
有关详细信息,请检查email documentation for Django。