如何从 django 表单在我的电子邮件中发送信息? - 姜戈 2
Posted
技术标签:
【中文标题】如何从 django 表单在我的电子邮件中发送信息? - 姜戈 2【英文标题】:How to send information on my email from django form? - Django 2 【发布时间】:2019-06-05 07:39:50 【问题描述】:如何通过 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
【问题讨论】:
【参考方案1】:好吧,您正在使用console backend,这就是您在控制台中看到消息的原因。如果您使用SMTP backend,则可以将此电子邮件发送到您的帐户。为此,您需要像这样配置:
首先你需要在settings.py中更新后端:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
然后更新settings.py
中的smtp配置:
# this configuration is for gmail
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'test@gmail.com'
EMAIL_HOST_PASSWORD = 'test'
EMAIL_PORT = 587
详情请查看email documentation for Django。
【讨论】:
错误:(535,b'5.7.8 用户名和密码不被接受。了解详情\n5.7.8 support.google.com/mail/?p=BadCredentials g12-v6sm14949570lja.74 - gsmtp') 在线:send_mail(subject, message, email, ['yarik.nashivan@gmail.com'])EMAIL_HOST_USER
和 EMAIL_HOST_PASSWORD
应该是您的电子邮件地址和密码。我已经给出了答案。
停止,如果我在本地主机上可以这样做吗?或者我需要托管?
是的,您可以在 localhost 中执行此操作。以上是关于如何从 django 表单在我的电子邮件中发送信息? - 姜戈 2的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 smtp.EmailBackend 在 Django 中发送电子邮件而无需通过邮件服务器进行身份验证