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', '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

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.
Ellis Percival
  • 4,632
  • 2
  • 24
  • 34

2 Answers2

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.

Vaibhav Singh
  • 932
  • 7
  • 20
0

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