【问题标题】:Email send django returning error when details comes from database当详细信息来自数据库时,电子邮件发送 django 返回错误
【发布时间】:2020-06-16 13:52:46
【问题描述】:

我有一个在 django 帮助文件中发送邮件的功能,我的功能如下所示

def mail_send(data):
    result = {}
    getTemplate = EmailTemplate.objects.filter(pk=data['type']).first()
    if getTemplate != None:
        templates = Template(getTemplate.template)
        config = EmailConfiguration.objects.filter(pk=1).first()
        context = Context(
            {
                'name': data['name'],
                'password': data['password'],
                'site_name': config.site_name
            }
        )
        msg_plain = 'Login Details ' + data['name'] + ' / ' + data['password']
        msg_html = templates.render(context)
        EMAIL_USE_TLS = config.tls
        EMAIL_HOST = config.host
        EMAIL_HOST_USER = config.from_email
        EMAIL_HOST_PASSWORD = config.password
        EMAIL_PORT = config.port
        mail = send_mail(
                    data['msg'],
                    msg_plain,
                    EMAIL_HOST_USER,
                    [data['email']],
                    fail_silently=False,
                    html_message=msg_html,
                )
    else:
        result['msg'] = 'Template Not Found .Unable to send Email..'
        result['status'] = False

它返回给我这样的错误:[Errno 111] Connection denied

但是当我将所有这些设置放在 settings.py 中时,它对我来说工作正常,但我不希望这个我想来自数据库并发送邮件请建议我从昨天开始就被困在这里。我是 django 的新手所以它对我来说变得非常困难

【问题讨论】:

  • 请分享您的settings.py文件,您的邮件设置好像不正确。
  • 这是我的问题,因为我不希望设置来自设置 .py 文件,我希望来自数据库自定义邮件详细信息。
  • 检查 config.tls 的类型(应该是布尔值)和 config.port(应该是整数)。

标签: python django database django-views django-admin


【解决方案1】:

这是一个非常奇怪的设置,可能不是最好的做法。

尽管如此,Django 仍然支持你。

我们来看看send_mail的签名

send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=None)

遗憾的是我们不能在这里给它主机,但我们可以给它一个连接。

from django.core.mail import get_connection

def mail_send(data):
    ....
    connection = get_connection(
        host=config.host,
        port=config.port,
        username=config.from_email,
        password=config.password,
        use_tls=config.tls,
    )
    mail = send_mail(
        data['msg'],
        msg_plain,
        config.from_email,
        [data['email']],
        fail_silently=False,
        html_message=msg_html,
        connection=connection,
   )

【讨论】:

  • 终端 ModuleNotFoundError 中的错误:没有名为 'django.core.email' 的模块
  • 很抱歉……打错字了……应该是from django.core.mail import get_connection
猜你喜欢
  • 2014-07-12
  • 2018-07-06
  • 2017-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
相关资源
最近更新 更多