提问人:Leonie 提问时间:10/30/2023 最后编辑:Leonie 更新时间:10/30/2023 访问量:50
使用 Django 发送电子邮件,而不是接收电子邮件
Sending emails with Django, not receiving email
问:
我正在尝试在 Django 中实现联系表单。如果我将EMAIL_BACKEND更改为控制台而不是 smtp,它会在终端中本地工作。我已经在 Gmail 中设置了 2FA 并将其用作密码,我也正在部署到 Heroku,在那里我设置了正确的配置变量。谁能看出为什么这可能不起作用?
setting.py 文件
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
DEFAULT_FROM_EMAIL = os.environ.get('EMAIL_HOST_USER')
SERVER_EMAIL = os.environ.get('EMAIL_HOST_USER')
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = False
EMAIL_PORT = 465
EMAIL_USE_SSL = True
EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER')
EMAIL_HOST_PASS = os.environ.get('EMAIL_HOST_PASS')
views.py
from django.shortcuts import render, redirect
from django.core.mail import EmailMessage, get_connection
from django.conf import settings
# Create your views here.
# https://opensource.com/article/22/12/django-send-emails-smtp
def send_email(request):
if request.method == "POST":
with get_connection(
host=settings.EMAIL_HOST,
port=settings.EMAIL_PORT,
username=settings.EMAIL_HOST_USER,
password=settings.EMAIL_HOST_PASS,
use_tls=settings.EMAIL_USE_TLS
) as connection:
name = request.POST.get("name")
email_from = settings.EMAIL_HOST_USER
recipient_list = [request.POST.get("email"), ]
message = request.POST.get("message")
EmailMessage(name, message, email_from,
recipient_list, connection=connection).send()
return render(request, 'contact.html')
联系人:.html
<section class="container">
<div class="row justify-content-md-center">
<div class="col-sm-6 center-form">
<h1>Contact Us:</h1>
<form method="POST" action="{% url 'mail' %}" id="contact-form">
{% csrf_token %}
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" id="name" placeholder="Name" required>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" name="email" id="email" placeholder="Email" required>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" name="message" rows="3" id="message" required></textarea>
</div>
<div>
<p>
<button type="submit" class="btn btn-lg submit-button">
Submit
</button>
</p>
</div>
</form>
</div>
</div>
</section>
编辑:
所以我发现它正在发送电子邮件,但是食谱是输入到表单中的电子邮件,而主机电子邮件是发送它的电子邮件。我更改了这两行:
email_from = request.POST.get("email")
recipient_list = settings.EMAIL_HOST_USER
我收到服务器错误 500。但是,通过将recipient_list添加到元组中,可以修复此问题。我现在面临一个新问题,无论我在电子邮件输入中提供什么电子邮件,它都会从我那里向我发送电子邮件。
答: 暂无答案
评论
contact.html