You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Django发送HTML模板邮件:邮件发送成功但模板无法加载

Django HTML邮件模板加载问题解决

问题排查与修复方案

  • 优化模板渲染方式
    当前使用get_template().render()的方式可能未正确传递请求上下文,改用render_to_string更稳定,它能自动处理模板上下文,避免渲染失败。修改后的视图代码如下:

    from django.template.loader import render_to_string  # 导入render_to_string
    
    def Mail_Send(request):
        name = "Shyam"
        mydist = {'name': name}
        html_template = 'mail_template.html'
        # 用render_to_string渲染模板,传入request上下文
        render_html = render_to_string(html_template, mydist, request=request)
        
        email = EmailMessage(
            'Welcome',
            render_html,
            settings.EMAIL_HOST_USER,
            ['itsupport@synergyhospital.co.in'],
        )
        email.content_subtype = 'html'
        email.send(fail_silently=False)
        
        return render(request, "index.html", {'mailsend': 'mailsend'})
    
  • 检查模板路径配置
    确保settings.py里的TEMPLATES配置正确,templates文件夹已被Django识别:

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [BASE_DIR / 'templates'],  # 确认此处包含你的templates文件夹路径
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    
  • 确认模板文件位置
    mail_template.html需放在项目根目录下的templates文件夹内,或对应APP的templates子文件夹下(启用APP_DIRS=True时),路径不能出错。

验证方式

修改后重新触发邮件发送,检查邮件内容是否正常渲染出Hi Shyam文本;若仍有问题,可临时设置fail_silently=True,查看Django报错日志定位具体模板加载错误。

内容的提问来源于stack exchange,提问作者shyam rathod

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 14:12:44