如何使用django“ Rest Framwork”发送电子邮件?

时间:2018-11-21 03:09:14

标签: python django django-rest-framework

我正在使用小型Rest API项目 而且效果很好。

但是我必须以某种方式在其中进行发送电子邮件的功能。

所以我像这样在settings.py中添加了电子邮件配置

// settings.py

# SMTP Mail service with decouple
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = "smtp.gmail.com"
EMAIL_HOST_USER = config('EM_ACCOUNT')
EMAIL_HOST_PASSWORD = config('EM_PASSWORD')
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

// views.py

from rest_framework import viewsets
from consult.models import Consult
from consult.serializers import ConsultSerializer
from django.core.mail import EmailMessage


class ConsultViewSet(viewsets.ModelViewSet):
    queryset = Consult.objects.all()
    serializer_class = ConsultSerializer


def send_email(request):
    email = EmailMessage(
        'Title',
        (ConsultSerializer.name, ConsultSerializer.email, ConsultSerializer.phone),
        'my-email',
        ['my-receive-email']
    )
    email.attach_file(ConsultSerializer.file)
    email.send()

// models.py

from django.db import models


# Create your models here.
class Consult(models.Model):
    name = models.CharField(max_length=16)
    position = models.CharField(max_length=16, null=True)
    group = models.CharField(max_length=50)
    email = models.CharField(max_length=50, null=True)
    phone = models.CharField(max_length=14)
    describe = models.TextField(blank=True, null=True)
    file = models.FileField(blank=True, null=True)
    create_date = models.DateTimeField(auto_now_add=True)
    update_date = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'Consult'

// serializers.py

from rest_framework import serializers
from .models import Consult


class ConsultSerializer(serializers.ModelSerializer):
    class Meta:
        model = Consult
        fields = ('id', 'name', 'position', 'group', 'email', 'phone', 'describe', 'file', 'create_date')

是的。那就是我所有的代码。 而且我在视图中设置了send_mail函数。

老实说我要自动发送邮件功能 当在我的数据库中查询数据时。但我只能找到普通的django解释。

创建数据后可以帮我设置自动发送邮件的功能吗?

2 个答案:

答案 0 :(得分:4)

实际上,最好使用Signals而不是覆盖create()方法。例如,您可以在models.py文件中使用以下代码:

@receiver(post_save, sender=settings.CONSULT_MODEL)
def send_mail_on_create(sender, instance=None, created=False, **kwargs):
    if created:
        send_email() # call send mail function

这是因为当您创建模型的实例并执行您希望执行的任何操作时,它将接收到信号。您还可以将post_save更改为pre_save和/或其他可用的默认信号,甚至定义自己的信号并从模型create()函数内部发送。

答案 1 :(得分:1)

方法1 :覆盖 ConsultViewSet

create() 方法
def send_email():
    email = EmailMessage(
        'Title',
        (ConsultSerializer.name, ConsultSerializer.email, ConsultSerializer.phone),
        'my-email',
        ['my-receive-email']
    )
    email.attach_file(ConsultSerializer.file)
    email.send()


class ConsultViewSet(viewsets.ModelViewSet):
    queryset = Consult.objects.all()
    serializer_class = ConsultSerializer

    def create(self, request, *args, **kwargs):
        response = super(ConsultViewSet, self).create(request, *args, **kwargs)
        send_email()  # sending mail
        return response