0

I have a model that stores some pdf files. I want to mail a pdf file as an attachment when a user requests to do so. I tried a way to do it like this

@api_view(['POST'])
def send_pdf_to_user(request):
    
    id = request.data.get('id')
    
    try:
        query = Civil.objects.get(id=id)
        
        file = query.pdf_file
        
        email = EmailMessage(
        'Subject here', 'Here is the message.', 'from@me.com', ['user@gmail.com'])
        email.attach_file(file)
        email.send()
        
        return Response(status=200)
    except Exception as e:
      print(e)
      
      return Response({str(e)}, status=400)

but received this error

expected str, bytes or os.PathLike object, not FieldFile

The file when printed gives this which is the path where the file is being stored

civil/random.pdf

Please suggest to me the way to mail pdfs which are pre stored in the database.

1 Answers1

0

Following the exception that was produced I noticed that email.attach() was asking for a string type and a file field was given to it. Also the full path of the file was needed not just civil/random.pdf. So, I took the comment from Art above and wrote the below code and now it is working.

@api_view(['POST'])
def send_pdf_to_user(request):
    
    id = request.data.get('id')
    
    try:
        query = Civil.objects.get(id=id)
        
        file = query.pdf_file.file # Art suggested this
        
        print(f'\nThis is the file {file}\n')
        
        email = EmailMessage(
        'Subject here', 'Here is the message.', 'from@me.com', ['user@gmail.com'])
        email.attach_file(str(file)) # converted the file path to str
        email.send()
        
        return Response(status=200)
    except Exception as e:
      print("this is the exception",e)
      
      return Response({str(e)}, status=400)