Django中如何邮件发送数据库媒体文件夹存储的PDF文件
解决Django发送数据库存储PDF附件的问题
错误原因
email.attach_file()方法要求传入字符串/字节类型的文件路径,但你直接传递了Django的FieldFile对象,因此触发expected str, bytes or os.PathLike object, not FieldFile错误。
解决方案1:使用FieldFile的绝对路径(本地存储场景)
通过FieldFile.path属性获取文件在服务器文件系统中的完整绝对路径,直接传入attach_file():
@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.path) email.send() return Response(status=200) except Exception as e: print(e) return Response({'error': str(e)}, status=400)
解决方案2:直接读取文件内容(通用场景,支持云存储)
如果你的PDF存储在云服务(如AWS S3),file.path可能无法直接访问,改用attach()方法读取文件内容并附加:
@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( filename=file.name, # 获取文件原始名称 content=file.read(), mimetype='application/pdf' ) email.send() return Response(status=200) except Exception as e: print(e) return Response({'error': str(e)}, status=400)
注意事项
- 确保Django的
MEDIA_ROOT和MEDIA_URL配置正确,保证本地文件路径可访问。 - 若使用云存储,需安装对应后端依赖(如
boto3用于S3),确保Django能正常读取云存储文件。
内容的提问来源于stack exchange,提问作者Ritankar Bhattacharjee
相关产品推荐
相关产品推荐

