Send csv file via email django

I want to attach a csv file to an email. i wrote a get method like this :

   def get(self, request, *args, **kwargs):
        serializer = self.get_serializer(self.get_queryset(), many=True)
        file_format = request.query_params.get("file_format", "csv")

        if file_format == "csv":
            data_file = export_to_csv(
                serializer.data,
                list(self.get_serializer().Meta.fields),
                "students"),
            )
            return data_file

this API generate a link to download the csv... but when I PDB the data_file I find out it is <HttpResponse status_code=200, "text/csv"> this the export_to_csv function :

def export_to_csv(data, titles, file_name):
 #This function will export the data in the form of csv file
 response = HttpResponse(content_type="text/csv")
 response["Content-Disposition"] = "attachment; filename={}.csv".format(file_name)
 writer = csv.DictWriter(
    response,
    fieldnames=titles,
    extrasaction="ignore",
 )
 # create dict from translation of headers
 headers = {title: _(title).replace("_", " ").title() for title in titles}
 # write translated headers
 writer.writerow(headers)
 # write data to csv file
 for row in data:
    writer.writerow(row)
 return response

The question is how can I attach the generated csv to the email

Refer to this, it's a neat documentation

https://docs.djangoproject.com/en/4.1/topics/email/#django.core.mail.EmailMessage

you can attach filenames with email, that way you can send attachments.

Back to Top