Python Sendgrid send email with all extension file attachment django

Question:

I want to send an email with an attachment using SendGrid API with all extensions in Django. Here is my code for mail sending.

views.py

def submitTicket(request):
try:
    if request.method == 'POST':
        name = request.POST.get('name')
        email = request.POST.get('email')
        subject = request.POST.get('subject')
        comment = request.POST.get('comment')
        atchfile = request.FILES['fileinput']
        allinfo =  " Name : " + name + "n E-Mail : " + email + "n Comment : " + comment
        recipients_list = ['[email protected]']
        if allinfo:
            message = Mail(from_email='[email protected]',
                                        to_emails=recipients_list,
                                        subject=subject, 
                                        html_content=allinfo)

            with atchfile.open() as f:
                data = f.read()
                f.close() 
            encoded_file = base64.b64encode(data).decode()
            attachedFile = Attachment(
                FileContent(encoded_file),
                FileName(atchfile.name),
                FileType(atchfile.content_type),
                Disposition('attachment')
            )            
            message.attachment = attachedFile               
            sg = SendGridAPIClient('0000000000000000000000000000000')
            sg.send(message)
           
            return HttpResponseRedirect('submitTicket')
except Exception as e:
    print("Exception = ", e)
    return render(request, 'submitTicket.html')

I am getting below error while trying to perform this.

TypeError at /submitTicket expected str, bytes or os.PathLike object, not InMemoryUploadedFile

Asked By: Helly Soni

||

Answers:

I think the issue is that the open method does not take an InMemoryUploadedFile as an argument. It normally expects a path to open.

However, because your atchfile is an InMemoryUploadedFile which inherits from File you can actually call open on the file itself. So I think you can do this instead:

            with atchfile.open() as f:
                data = f.read()
                f.close() 
Answered By: philnash
 attachedFile = Attachment(
                    FileContent(encoded_file),
                    FileName(atchfile.name),
                    FileType(atchfile.content_type),
                    Disposition('attachment')
                )

Try this.

Answered By: Caption America
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.