簡體   English   中英

Python Sendgrid 發送 email 帶所有擴展文件附件 django

[英]Python Sendgrid send email with all extension file attachment django

我想使用帶有 Django 中所有擴展名的 SendGrid API 發送帶有附件的 email。 這是我的郵件發送代碼。

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')

我在嘗試執行此操作時遇到錯誤。

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

我認為問題在於open方法沒有將InMemoryUploadedFile作為參數。 它通常期望打開一個路徑。

但是,因為您的atchfile是從File繼承的InMemoryUploadedFile ,您實際上可以在文件本身上調用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')
                )

嘗試這個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM