我想发送一封带有附件的邮箱,使用的是Django中所有扩展的SendGrid API.这是我的邮件发送代码.

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

我在try 执行此操作时遇到错误.

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

推荐答案

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

尝尝这个.

Python相关问答推荐

比较两个数据帧并并排附加结果(获取性能警告)

SQLGory-file包FilField不允许提供自定义文件名,自动将文件保存为未命名

Vectorize多个头寸的止盈/止盈回溯测试pythonpandas

按顺序合并2个词典列表

加速Python循环

为什么以这种方式调用pd.ExcelWriter会创建无效的文件格式或扩展名?

Python解析整数格式说明符的规则?

Streamlit应用程序中的Plotly条形图中未正确显示Y轴刻度

优化器的运行顺序影响PyTorch中的预测

Python Tkinter为特定样式调整所有ttkbootstrap或ttk Button填充的大小,适用于所有主题

基于另一列的GROUP-BY聚合将列添加到Polars LazyFrame

如何在Great Table中处理inf和nans

Polars map_使用多处理对UDF进行批处理

将一个双框爆炸到另一个双框的范围内

Python日志(log)模块如何在将消息发送到父日志(log)记录器之前向消息添加类实例变量

分解polars DataFrame列而不重复其他列值

将数字数组添加到Pandas DataFrame的单元格依赖于初始化

将像素信息写入文件并读取该文件

如何在开始迭代自定义迭代器类时重置索引属性?

PANDA:如何将多选列转换为索引/列