如何使用Jython保存电子邮件图像附件

问题描述 投票:1回答:2

我正在尝试使用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(),默认情况下为编写二进制文件...

python email jython
2个回答
0
投票

对于将来的读者,这是我的解决方法。在代码中写代码:

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

0
投票

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

CODE:

#!/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"] )
© www.soinside.com 2019 - 2024. All rights reserved.