基于Django的邮件模拟项目邮件发送失败问题求助
Django邮件模拟项目发送失败问题修复
问题定位
控制台报错inbox.js:10:7的根源是:
- 第10行代码中
from变量未定义,直接访问from.length会抛出引用错误,导致发送逻辑中断。 - 错误使用
to.length获取输入内容长度:to是DOM元素对象,to.length并非输入框的文本长度,正确写法应为to.value.length,且原判断条件from.length == 0 && to.length == 1000完全不符合业务逻辑。 - Fetch请求未设置
Content-Type: application/json头部,Django后端无法正确解析JSON格式的请求体。 - 缺少Django必需的CSRF令牌,请求会被后端CSRF防护拦截。
修复后的完整代码
document.addEventListener( "DOMContentLoaded", function () { const form = document.querySelector("#compose-form"); const msg = document.querySelector("#message"); form.addEventListener("submit", (event) => { event.preventDefault(); // 用const声明变量,避免全局污染 const toInput = document.querySelector("#compose-recipients"); const subjectInput = document.querySelector("#compose-subject"); const bodyInput = document.querySelector("#compose-body"); // 替换为合理的输入校验:收件人不能为空 if (!toInput.value.trim()) { msg.innerHTML = `<div class="alert alert-danger" role="alert">收件人不能为空</div>`; return; } fetch("/emails", { method: "POST", headers: { "Content-Type": "application/json", "X-CSRFToken": getCookie("csrftoken") }, body: JSON.stringify({ recipients: toInput.value, subject: subjectInput.value, body: bodyInput.value, }), }) .then((response) => { // 先校验响应状态,处理非2xx响应 if (!response.ok) { return response.json().then(err => Promise.reject(err)); } return response.json(); }) .then((result) => { if (result.status === 201) { load_mailbox("sent"); form.reset(); msg.innerHTML = ""; } }) .catch((error) => { msg.innerHTML = `<div class="alert alert-danger" role="alert"> ${error.error || "发送失败,请检查输入或重试"} </div>`; }); }); }, false ); // 获取Django CSRF令牌的辅助函数 function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; }
后端配合检查
- 确保
/emails的POST视图函数能正确解析JSON请求体:# Django视图示例 from django.http import JsonResponse import json def send_email(request): if request.method == "POST": data = json.loads(request.body) recipients = data.get("recipients") subject = data.get("subject") body = data.get("body") # 执行邮件保存/发送逻辑 if not recipients: return JsonResponse({"status": 400, "error": "收件人不能为空"}, status=400) # 成功处理后返回201 return JsonResponse({"status": 201}, status=201) - 确认Django的
settings.py中启用了CSRF中间件(默认启用),确保前端能正确获取CSRF令牌。
内容的提问来源于stack exchange,提问作者zahra
相关产品推荐
相关产品推荐

