Python Sendgrid отправка электронной почты со всеми расширениями файл вложение django

Я хочу отправить письмо с вложением, используя SendGrid API со всеми расширениями в Django. Вот мой код для отправки почты.

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 open(atchfile, 'rb') as f:
                data = f.read()
                f.close() 
            encoded_file = base64.b64encode(data).decode()
            attachedFile = Attachment(
                FileContent(encoded_file),
                FileName(atchfile),
                FileType(atchfile),
                Disposition(atchfile)
            )            
            message.attachment = attachedFile               
            sg = SendGridAPIClient('0000000000000000000000000000000')
            sg.send(message)
           
            return HttpResponseRedirect('submitTicket')
except Exception as e:
    print("Exception = ", e)
    return render(request, 'submitTicket.html')

Я получаю следующую ошибку при попытке выполнить это.

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

Думаю, проблема в том, что метод open не принимает InMemoryUploadedFile в качестве аргумента. Обычно он ожидает путь для открытия.

Однако, поскольку ваш atchfile является InMemoryUploadedFile, который наследуется от File, вы можете вызвать open на самом файле. Поэтому я думаю, что вместо этого вы можете сделать следующее:

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

Попробуйте это.

Вернуться на верх