在DJango Restful框架(DRF)中发送带有附加文件的电子邮件

2024-05-02 11:44:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想将文件附加到电子邮件并将其发送到特定的电子邮件地址

我正在使用DJango Restful框架创建API端点

我试着按照文档和一些指南去做,但我还是遇到了麻烦

我得到这个错误:

enter image description here

def send_comment_mail_notification(request, space, target_email):
       message = request.POST.get('description', '')
       subject = request.POST.get('comment_cat', '')
       from_mail = space.email 
       to = target_email
       msg = EmailMessage(subject, message, from_mail, [to],)

       image = request.FILES['file']
       msg.attach(image.name, image.read(), image.content_type)
       msg.content_subtype = "html"
       msg.send()
           

这是我的模特

class Comment(BaseModel):
    comment_cat = models.ForeignKey(
        "admincat_user.CommentCategory", on_delete=models.CASCADE)
    description = models.TextField(max_length=512)
    file = models.FileField(upload_to="./comment", blank=True, null=True)

这是我的Seriliazers.py

class CommentSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Comment
        fields = "__all__"
        read_only_fields = ("created_at", "updated_at")

这是我的看法

class CommentViewSet(BaseViewSet):
    permission_classes = (BelongToSpace,)
    serializer_class = serializers.CommentSerializer
    queryset = models.Comment.objects.all()

    def callback(self, **kwargs):
        send_comment_mail_notification(self.request, self.space, "a.a@emial.com")

我的URL.py

routes.register('comments', views.CommentViewSet, 'comments')

拜托,我错过了什么,或者需要做什么才能让它工作