JMS BytesMessage用于发送多个文档

时间:2014-07-22 18:20:07

标签: jms attachment

我要求批量作业发送电子邮件。但是我必须以这样的方式将其分解,我需要通过消息传递将电子邮件详细信息切换到另一个系统,然后将读取已发送的消息并发送悠闲地发电子邮件。

我的电子邮件附件。我如何实现这一目标?给定电子邮件可能有多个附件。

我读过有关字节消息但是如何将它用于给定电子邮件的多个附件?

对此有何想法?

1 个答案:

答案 0 :(得分:1)

您可以发送一条包含电子邮件详细信息的JMS消息(从列表,列表,主题,文本),然后将附件作为JMS字节消息发送,每个附件消息都具有相同的自定义标识符。

发件人方

// create JMS Bytes message with mail content
// MailData class should implement java.io.Serializable)
MailData mailData = new MailData();
// emailID could be GUID or anything else that would uniquely identify mail
mailData.setEmailID(emailID);
mailData.setFrom(from);
mailData.setToList(toList);
mailData.setSubject(subject);
mailData.setText(text);

BytesMessage msg = session.createBytesMessage();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(mailData);
out.close();
bos.close();
msg.writeBytes(bos.toByteArray());
producer.send(msg);

// for the sake of simplicity, object attachment contains attachment name, MIME type
// and value as byte array
for(Attachment att : attachmentList) {
    BytesMessage msgAtt = session.createBytesMessage();
    // emailID
    msgAtt.setStringProperty("emailId", emailID);
    msgAtt.setStringProperty("fileName", att.getAttachmentName());
    msgAtt.setStringProperty("mimeType", att.getMimeType());
    // set bytes message payload to attachment content
    msgAtt.writeBytes(att.getValue());
    producer.send(msgAtt);
}

接收方

BytesMessage bytesMessage = (BytesMessage) message;
byte[] bytes = new byte[(int) bytesMessage.getBodyLength()];
bytesMessage.readBytes(bytes);
ByteArrayInputStream bis = new ByteArrayInputStream(bytesMessage);
ObjectInputStream in = new ObjectInputStream(bis);
MailData mailData = (MailData) in.readObject();
in.close();
bis.close();

// get data from queue with the same emailID
MessageConsumer consumer = session.createConsumer(queue, "emailID='"
                + mailData.getEmailID() + "'");
connection.start();
Message attMsg = null;
while((attMsg = consumer.receiveNoWait()) != null) {
    String fileName = attMsg.getStringProperty("fileName");
    String mimeType = att.getStringProperty("mimeType");
    BytesMessage bytesMessage = (BytesMessage) attMsg;
    byte[] attachmentValue = new byte[(int) bytesMessage.getBodyLength()];
    bytesMessage.readBytes(attachmentValue);
}