3

我正在尝试使 EMAIL_HOST 设置在管理员中可配置,我将创建一个包含必填字段的模型,例如:

  • EMAIL_HOST
  • EMAIL_HOST_USER
  • EMAIL_HOST_PASSWORD
  • EMAIL_PORT

但是如何使用 send_mail 在视图中使用这些字段?

4

3 回答 3

3

如果要使用send_mail,则必须创建自己的电子邮件后端,该后端使用您的自定义设置,然后将其传递给send_mail属性connection

于 2013-03-03T16:29:23.637 回答
0

在独立于 Django 设置的管理页面中使用自定义配置的 SMTP 设置发送邮件:

from django.core import mail
from django.core.mail.backends.smtp import EmailBackend
from <'Your SMTP setting in admin'> import <'Your model'>

def send_mail(subject, contact_list, body): 
    try:
        con = mail.get_connection()
        con.open()
        print('Django connected to the SMTP server')
        mail_setting = <'Your model'>.objects.last()
        host = mail_setting.host
        host_user = mail_setting.host_user
        host_pass = mail_setting.host_pass
        host_port = mail_setting.host_port
        mail_obj = EmailBackend(
            host=host,
            port=host_port,
            password=host_pass,
            username=host_user,
            use_tls=True,
            timeout=10)
        msg = mail.EmailMessage(
            subject=subject,
            body=body,
            from_email=host_user,
            to=[contact_list],
            connection=con)
        mail_obj.send_messages([msg])
        print('Message has been sent.')
        mail_obj.close()
        return True

    except Exception as _error:
        print('Error in sending mail >> {}'.format(_error))
        return False
于 2018-04-09T11:25:30.877 回答
0

这对我有用

from django.core.mail import EmailMessage
from django.core.mail.backends.smtp import EmailBackend

config = Configuration.objects.get(**lookup_kwargs)

try:

    backend = EmailBackend(
        host=config.host,
        port=config.port,
        password=config.password,
        username=config.username,
        use_tls=config.use_tls,
        fail_silently=config.fail_silently
    )

    mail = EmailMessage(
        subject="subject",
        body="body",
        from_email=config.username,
        to=["email@gmail.com"],
        connection=backend,
    )
    mail.send()

except Exception as err:
    print(err)
于 2021-08-13T08:54:04.397 回答