我有一种情况,我需要在电子邮件的正文中而不是在标题中附加文件。例如,在Microsoft Outlook中,如果消息类型设置为Rich Text,则可以将文件作为附件拖放到电子邮件正文中。我如何使用Spring Integration MessageBuilder?到目前为止,这是我用来发送附件,但文件附在电子邮件中的标题不在正文中。
Message<?> msg = MessageBuilder.withPayload("")
.setHeader(MailHeaders.SUBJECT, subject )
.setHeader(MailHeaders.ATTACHMENT_FILENAME, args[0].toString())
.build();
如果有人给我代码示例会很有帮助!提前致谢
答案 0 :(得分:3)
您的代码显示您忽略了邮件本身的关键部分payload
JavaMailSender
(您可能已经拥有)使用您所连接的MimeMessage
和org.springframework.mail.javamail.JavaMailSender
构建常规org.springframework.mail.javamail.MimeMessageHelper
,如
public void sendEmail(){
MimeMessage message = mailSender.createMimeMessage(); //mailSender is an instance of JavaMailSender from 1.
try{
MimeMessageHelper helper = new MimeMessageHelper(message,true);
//set the fields
helper.setFrom("J'onn Doe");
helper.setTo("SpamRecce");
helper.setSubject("")
helper.setText("Text goes here")
//load attachment file using spring's help. Basic interface is called a Resource and there are many implementations. Here, I've used the ClassPathResource which means your attachment file must be in your classpath
ClassPathResource theAttachment = new ClassPathResource("My File.Doc");
helper.addAttachment("Add the desired filename here.doc",theAttachment);
}
catch(MessagingException me){
Logger.getAnonymousLogger.info("Something bad happened!);
me.printStacktrace();
}
mailSender.send(message);
}
我不知道您的实施细节但我相信发送电子邮件的端点应该是终止端点,即电子邮件可以直接从该端点发送,您不需要发送到另一个频道。
但是,如果仍然需要将消息刷新到另一个频道,则需要重写您在那里阅读的代码:
Message<MimeMessage> msg = MessageBuilder.withPayload(message)
.setHeader(MailHeaders.SUBJECT, subject )
.setHeader(MailHeaders.ATTACHMENT_FILENAME, args[0].toString())
.build();