1

我正在尝试使用 Jython 2.5.3 获取附加到电子邮件的图像。我收到了电子邮件(使用 Python imap 库的 Jython 版本)。我可以通过遍历部件来获取附件,使用 get_content_type() 找到正确的部件类型:

image, img_ext = None, None
for part in self.mail.get_payload():
    part_type, part_ext = part.get_content_type().split('/')
    part_type = part_type.lower().strip()
    part_ext = part_ext.lower().strip()
    if part_type == 'image':
        image =  part.get_payload(decode=True)
        img_ext = part_ext
 return image, img_ext

'image' 作为一大块字节返回,在常规 Python 中,我会直接将其写入文件。但是,当我在 Jython 中尝试相同的操作时,出现以下错误:

TypeError: write(): 1st arg can't be coerced to java.nio.ByteBuffer[], java.nio.ByteBuffer

让 Jython 将我的大数据块识别为字节数组的正确方法是什么?

PS:写代码使用tempfile.mkstmp(),默认写二进制...

4

2 回答 2

0

对于未来的读者,这就是我解决它的方法。在 tha 编写的代码中:

from org.python.core.util import StringUtil
from java.nio import ByteBuffer


tmp, filename = tempfile.mkstemp(suffix = "." + extension, text=True)
bytes = StringUtil().toBytes(attachment)
bb = ByteBuffer.wrap(bytes)
tmp.write(bb)
tmp.close()
于 2013-01-20T01:36:21.627 回答
0

这是我使用 gmail smtp 添加图像附件的代码

代码:

#!/usr/bin/env python
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os

USERNAME = "___YOUR SMTP EMAIL HERE___"
PASSWORD = "__YOUR SMTP PASSWORD HERE___"

def sendMail(to, subject, text, files=[]):
    assert type(to)==list
    assert type(files)==list

    msg = MIMEMultipart()
    msg['From'] = USERNAME
    msg['To'] = COMMASPACE.join(to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach( MIMEText(text) )

    for file in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(file,"rb").read() )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"'
                       % os.path.basename(file))
        msg.attach(part)

    server = smtplib.SMTP('smtp.gmail.com:587')
    server.ehlo_or_helo_if_needed()
    server.starttls()
    server.ehlo_or_helo_if_needed()
    server.login(USERNAME,PASSWORD)
    server.sendmail(USERNAME, to, msg.as_string())
    server.quit()

sendMail( ["___EMAIL TO RECEIVE THE MESSAGE__"],
        "Alarm notification",
        "Someone has entered the room, picture attached",
        ["/home/pi/webcam.jpg"] )
于 2019-12-11T21:02:47.520 回答