1

I am new to the Django Rest Framework.
I am trying to send email with attachment.

Here is my code.

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

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

View.py


def send_email():
    email = EmailMessage(
        'Title',
        ('abc', '[email protected]', '123123123'),
        '[email protected]',
        ['[email protected]']
    )
    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.', '[email protected]', ['[email protected]'], 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='[email protected]',
                               to='[email protected]', bcc='[email protected]', connection=None,
                               attachments=data, headers=self.data, cc='[email protected]', 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

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

settings.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. None of the method is working. Even create method does not invoke at all.

This is showing up on my api admin I want to change save button text to send.

This is showing up on my api admin i want to change save button text to send.

  1. I don't want to create model. which is created for showing this filed on admin i required 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.
2

2 Answers 2

1

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. Here is the python documentation for the same.

Sign up to request clarification or add additional context in comments.

2 Comments

why my overridden create is not working in View.py and in serializer.py
The screenshot which you have attached is your ModelAdmin view, that will not call your Emailviewset.
0

If you want to send mail with an attachment, you have already asked more details here Sending emails with attachment in django

1 Comment

I am not working in django am working in Django Rest Framework.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.