Search code examples
pythondjangosendgrid-api-v3

Python Sendgrid send email with all extension file attachment django


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 = ['abc@gmail.com']
        if allinfo:
            message = Mail(from_email='xxx@gmail.com',
                                        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


Solution

  •  attachedFile = Attachment(
                        FileContent(encoded_file),
                        FileName(atchfile.name),
                        FileType(atchfile.content_type),
                        Disposition('attachment')
                    )
    

    Try this.