Django:在视图中设置电子邮件设置

时间:2017-05-08 21:32:07

标签: python django configuration django-views django-email

我正在尝试使用来自Google的SMTP发送电子邮件。我已经发送了一封电子邮件,将设置变量放在“settings.py”文件中,但是我需要在视图中配置这些变量并使用我的“Config”模型进行设置。

这是我的型号代码:

class Config(models.Model):
    email_sender    = models.CharField(max_length = 100, default = '', blank = True)
    email_password  = models.CharField(max_length = 30, default = '', blank = True)
    smtp_server     = models.CharField(max_length = 100, default = '', blank = True)
    smtp_port       = models.PositiveIntegerField(default = 587, blank = True)

这是我的观看代码:

def send_custom_mail(request):
    config = Config.objects.get(pk = 1)
    EMAIL_HOST = config.smtp_server
    EMAIL_PORT = config.smtp_port
    EMAIL_HOST_USER = config.email_sender
    EMAIL_HOST_PASSWORD = config.email_password
    EMAIL_USE_TLS = True
    DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
    subject = 'test'
    msg = '<p>Test: <strong>Mensaje</strong>></p>'
    mail_from = config.email_sender
    mail_to = ['{}'.format(email)]
    from django.core.mail import EmailMessage
    email2send  = EmailMessage(subject, msg, mail_from, to=mail_to)
    email2send.content_subtype = "html"  # Main content is now text/html
    email2send.send()

我的问题:我在视图中设置变量时,不会发送电子邮件。

我需要在dinamically配置这些变量,所以我不能在setting.py文件中写它。

3 个答案:

答案 0 :(得分:1)

我对在视图中覆盖设置感到有些困惑;从来没有见过它的用例。

我通常使用的策略是回退到较低级别的功能。

我建议您使用send_mail()函数和get_connection()来实现您的需求。

Haven未对此代码进行测试,但认为它看起来像这样:

from django.core import mail

connection = mail.get_connection(
    host = config.smtp_server,
    port = config.smtp_port,
    username = config.email_sender,
    password = config.email_password ,
    (... etc etc ...)
)

# Manually open the connection
connection.open()

# Send the message
subject = 'test'
msg = 'Test:Mensaje'
mail_to = ['test@test.com']
email2send  = EmailMessage(
    subject, 
    msg, t
    o=mail_to
    connection=connection
)

# Send the email using the custom connection
email2send.send()

# Close the connection
connection.close()

(注意首次设置EmailMessage以通过自定义连接发送电子邮件时的connection=connection。)

Django Email Backends文档很好地解释了这一点,这似乎比覆盖设置更直接。

答案 1 :(得分:0)

我找到了这个解决方案,但我不知道这是否是解决此问题的最佳方法:

使用此:https://docs.djangoproject.com/en/1.11/_modules/django/test/utils/#override_settings

在我看来,我会覆盖设置变量:

from django.core.mail import EmailMessage
from django.test.utils import override_settings

@override_settings(EMAIL_HOST = Config.objects.get(pk = 1).smtp_server)
@override_settings(EMAIL_HOST_USER = Config.objects.get(pk = 1).email_sender)
@override_settings(EMAIL_PORT = Config.objects.get(pk = 1).smtp_port)
def send_custom_mail(request):
subject = 'test'
    msg = 'Test:Mensaje'
    mail_to = ['test@test.com']
    email2send  = EmailMessage(subject, msg, to=mail_to)
    email2send.content_subtype = "html"  # Main content is now text/html
    email2send.send()

在这个方法中,我使用&#34; django.test.utils&#34;把装饰者&#34; @override_settings()&#34;在&#34; send_custom_mail&#34;之前功能。它覆盖了设置,让我从保存在名为Config的模型中的邮件中发送电子邮件。

实际上,我不确定它是否是最好的方法,因为&#34; django.test&#34;模块用于单元测试,但我想分享我的解决方案。

答案 2 :(得分:0)

def email_sending(mail_subject, message,to, mail_obj=None):
if not mail_obj:
    try:

        mail_obj = AdminEMailsModel.objects.filter(default_email=True)[0]

    except Exception as e:
        print(e)
        try:
            if not mail_obj:
                mail_obj= AdminEMailsModel.objects.all()[0]

        except Exception as e:
            print(e)
            return
backend = EmailBackend(host=mail_obj.host_address, port=mail_obj.port_no, username=mail_obj.email,
                       password=mail_obj.password, use_tls=mail_obj.use_tls, fail_silently=False)
email = EmailMultiAlternatives(
    mail_subject, message, from_email=mail_obj.email, to=to, connection=backend
)

email.attach_alternative(message, 'text/html')
email.send()

return
  

直接在需要发送电子邮件以注册电子邮件时可以调用此功能   如果此代码对您有用,请放弃投票