简体   繁体   English

Django rest framework: sendgird email with attachment without model only filefield to open file and send button to send email

[英]Django rest framework: sendgird email with attachment without model only filefield to open file and send button to send email

I am new to the Django Rest Framework.我是 Django Rest 框架的新手。
I am trying to send email with attachment.我正在尝试发送带有附件的 email。

Here is my code.这是我的代码。

model.py model.py


class EmailModel(models.Model):
    upload_file = models.FileField(upload_to='location/location/files', blank=False)
    class Meta:
        verbose_name = 'Applicant CSV Upload'
        verbose_name_plural = 'Applicant CSV Upload'


admin.py管理员.py

@admin.register(EmailModel)
class EmailAdmin(admin.ModelAdmin):
    class Meta:
      model = EmailModel

View.py视图.py


def send_email():
    email = EmailMessage(
        'Title',
        ('abc', 'abc@gmail.com', '123123123'),
        'abc@gmail.com',
        ['abc@gmail.com']
    )
    email.attach_file(EmailViewSet.upload_file)
    email.send()

class EmailViewSet(viewsets.ModelViewSet):
    queryset = EmailModel.objects.all()
    serializer_class = EmailSerializer
    def create(self, request, *args, **kwargs):
        send_mail(' Test Subject here', 'Test here is the message.', 'abc@gmail.com', ['abc@gmail.com'], fail_silently=False)
        response = super(EmailViewSet, self).create(request, *args, **kwargs)
        send_email()  # sending mail
        data = [{'location': request.data.get('location'), 'image': file} for file in request.FILES.getlist('image')]
        serializer = self.get_serializer(data=data, many=True)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        message = EmailMessage(subject='Applicant data', body='PFA', from_email='abc@gmail.com',
                               to='abc@gmail.com', bcc='abc@gmail.com', connection=None,
                               attachments=data, headers=self.data, cc='abc@gmail.com', reply_to=None)
        # Attach file
        # with open(attachment, 'rb') as file:
        #     message.attachments = [
        #     (attachment, file.read(), 'application/pdf')
        # ]
        return response, message.send(), Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

Serializer.py序列化程序.py

class EmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = EmailModel
        fields = ('upload_file',)

settings.py设置.py



EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey' # this is exactly the value 'apikey'
EMAIL_HOST_PASSWORD = 'here i am using my sendgrid api key directy' # this is your API key
EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = 'here i am using same gmail id on which i have created my send grid account'

In view.py and serializer.py I have mentioned every method I tried for sending email so thats why it is so mixed up.在 view.py 和 serializer.py 中,我提到了我尝试发送 email 的每种方法,这就是为什么它如此混乱。 None of the method is working.任何方法都不起作用。 Even create method does not invoke at all.甚至create方法也根本不调用。

This is showing up on my api admin I want to change save button text to send.这出现在我的 api 管理员上,我想更改保存按钮文本以发送。

这显示在我的 api 管理员上,我想更改要发送的保存按钮文本。

  1. I don't want to create model.我不想创建 model。 which is created for showing this filed on admin i required model.这是为了在管理员上显示此文件而创建的,我需要 model。
  2. Also don't want to save file in folder.也不想将文件保存在文件夹中。 which is saving.这是节省。
  3. filefiled just open the file and on my hardcoded email address send that file in email when I press save/send button. filefiled 只需打开文件并在我的硬编码 email 地址上,当我按下保存/发送按钮时,将该文件发送到 email 中。

You can create a custom admin page where you won't require models.您可以创建一个不需要模型的自定义管理页面。 This question solves that problem. 这个问题解决了这个问题。

Now when you create you custom page, in the views you can simply use the python API provided by sendgrid and do whatever you want to achieve.现在,当您创建自定义页面时,您可以在视图中简单地使用 sendgrid 提供的 python API 并做任何您想做的事情。 Here is the python documentation for the same.这是相同的python 文档

If you want to send mail with an attachment, you have already asked more details here Sending emails with attachment in django如果您想发送带有附件的邮件,您已经在此处询问了更多详细信息在 django 中发送带有附件的电子邮件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM