gpt4 book ai didi

python - 写入和图像附件作为头像 : Is it possible?

转载 作者:太空宇宙 更新时间:2023-11-04 11:02:14 25 4
gpt4 key购买 nike

有人处理过收到的电子邮件中的附件吗?我在想,与其让用户上传图片,不如让他们将其作为附件发送,我可以使用它上传到数据存储区。

文档有 sending attachments但我找不到任何关于接收附件的文档。 This page says :

attachments

The file attachments for the message, as a list of two-value tuples, one tuple for each attachment.

Each tuple contains a filename as the first element, and the file contents as the second element.

An attachment file must be one of the allowed file types, and the filename must end with an extension that corresponds with the type. For a list of allowed types and filename extensions, see Overview: Attachments.

我认为这也是关于发送电子邮件。

我有这段代码可以将图像保存到数据存储区:

class AvatarSave(webapp.RequestHandler):
def post(self):
q = User.all()
q.filter("userEmail =", emailAddress)
qTable = q.fetch(10)
if qTable:
for row in qTable:
avatar = images.resize(self.request.get("img"), 50, 50)
row.avatar = db.Blob(avatar)
db.put(qTable)
else:
self.response.out.write("user not found")

self.redirect('/')

直觉上,似乎message.attachment而不是 "img"会成功的。

avatar = images.resize(self.request.get(message.attachment), 50, 50)

你怎么看?谢谢。


Update2(新代码作为对 Nick Johnson 评论的回应)

class Register(InboundMailHandler):
def receive(self, message):
senderEmail = message.sender
emailTuple = parseaddr(senderEmail)
emailUserName = emailTuple[0]
emailAddress = emailTuple[1]
newAvatar = db.Blob(images.resize(goodDecode(message.attachments[0][1]), 50, 50))
newUser = User(userEmail=emailAddress,
userName=emailUserName,
avatar=newAvatar)

db.put(newUser)

Update1 问题已解决:

作为记录,对于任何有相同问题的人,请注意 attribute of messageattachments不是attachment :

message.attachment

给出 AttributeError

AttributeError: 'InboundEmailMessage' object has no attribute 'attachment'

和对象 message.attachment看起来像这样:

[('portrait.png', <EncodedPayload payload=#8461006914571150170 encoding=base64>)]

所以拉<EncodedPayload payload=#8461006914571150170 encoding=base64>的正确方法部分是

avatar = images.resize(goodDecode(message.attachments[0][1]), 50, 50)

我发布的原始代码有

avatar = images.resize(goodDecode(message.attachments[1]), 50, 50)

这显然行不通。

再次感谢 jesmithRobert Kluin寻求答案。


Update0(关于 jesmith 的回答)

就我而言,我正在拍摄图像 "img"从用户上传的表单并将其写入数据存储,如下所示:

       for row in qTable:
avatar = images.resize(self.request.get("img"), 50, 50)
row.avatar = db.Blob(avatar)
db.put(qTable)
self.redirect('/')
else:
logging.info("else user not found")
self.redirect('/user-not-found')

在您的代码中,这对应于本节,我相信:

try:
if hasattr(message, "attachment"):
for a in message.attachments:
msg.attachmentNames.append(a[0])
msg.attachmentContents.append(append(db.Blob(goodDecode(a[1])))
msg.put()
except:
logging.exception("exception decoding attachments in email from %s" % message.sender)

假设,就我而言,只有 1 个附件;如何获取附件的数据部分?

message.attachment[1]吗?

avatar = images.resize(message.attachment[1], 50, 50)

message.attachment[1]附件的数据部分?

谢谢!

最佳答案

这是我使用的传入邮件处理程序的片段:

   bodies = message.bodies(content_type='text/html')
allBodies = u"";
for body in bodies:
allBodies = allBodies + u"\n" + unicode(goodDecode(body[1]), errors="ignore")
if not allBodies:
bodies = message.bodies(content_type='text/plain')
for body in bodies:
allBodies = allBodies + u"\n" + unicode(goodDecode(body[1]), errors="ignore")

msg = EmailMessageModel()
...fill in various stuff...
msg.sender = message.sender
msg.date = datetime.datetime.now()
msg.message = allBodies
# Calling put() before dealing with attachments because it seems like that could throw various exceptions
msg.put()
event.email = True
event.put()
event.project.email = True
event.project.put()
# attachments is a list of element pairs containing file names and contents.

try:
if hasattr(message, 'attachments'):
for a in message.attachments:
msg.attachmentNames.append(a[0])
msg.attachmentContents.append(db.Blob(goodDecode(a[1])))
msg.put()
except:
logging.exception("Exception decoding attachments in email from %s" % message.sender)

请注意,goodDecode 是我编写的一个函数,因为底层 GAE 解码中存在一个错误(它将所有内容小写,从而破坏了 base64 编码的文本):

def goodDecode(encodedPayload):
if not hasattr(encodedPayload, 'encoding'):
return encodedPayload
encoding = encodedPayload.encoding
payload = encodedPayload.payload
if encoding and encoding.lower() != '7bit':
payload = payload.decode(encoding)
return payload

这可能不再需要了,因为我很确定他们修复了那个错误。

在我的例子中,我将附件填充到数据库中:

class EmailMessageModel(db.Model):
....various stuff...
sender = db.StringProperty()
date = db.DateTimeProperty()
message = db.TextProperty()
attachmentNames = db.StringListProperty()
attachmentContents = db.ListProperty(db.Blob)

当我想显示这封电子邮件时,我正在使用:

<h2>{{ e.sender }} {{ e.date|date:"M j, Y f A " }} GMT</h2>
<p>From: {{ e.sender }}<br/>Date: {{ e.date|date:"M j, Y f A" }} GMT ({{ e.date|timesince }} ago)<br/>Subject: {{ e.subject }}</p>
{% if e.attachmentNames %}
<p>Attachments:
{% for a in e.attachmentNames %}
<a href="/admin/attachment?email={{ e.key }}&index={{ forloop.counter0 }}" target="_blank">{{ a }}</a>
{% endfor %}
</p>
{% endif %}
<div style='background-color: white'>{{ e.message }}</div>

附件处理程序是:

class AttachmentHandler(webapp.RequestHandler):
def get(self):
email = EmailMessageModel.get(self.request.get('email'))
index = self.request.get('index')
if index:
index = int(index)
filename = email.attachmentNames[index]
self.response.headers['Content-Type'] = str(mimetypes.guess_type(filename)[0]) or 'application/octet-stream'
self.response.out.write(email.attachmentContents[index])

(所以,基本上,我让浏览器弄清楚如何处理附件。)

希望这对您有所帮助!

关于python - 写入和图像附件作为头像 : Is it possible?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4357022/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com