简体   繁体   English

如何为带有附件的Java MimeMessage对象创建测试数据?

[英]How to create test data for Java MimeMessage objects with attachments?

I want to persist mails in a database. 我想将邮件保留在数据库中。 To test it, I try to generate some test MimeMessage objects with and without attachments. 为了测试它,我尝试生成一些带有和不带有附件的测试MimeMessage对象。 I add the attachments like this: 我添加附件如下:

MimeMessage message = new MimeMessage(Session.getDefaultInstance(props, null));
Multipart multipart = new MimeMultiPart();
MimeBodyPart bodyPart = new MimeBodyPart();

bodyPart.attachFile("./files/test.txt");
bodyPart.setFileName("test.txt");

multipart.addBodyPart(bodyPart);
message.setContent(multipart);
message.saveChanges();

Now I want to serialize this MimeMessage with its writeTo(OutputStream) method. 现在,我想使用其writeTo(OutputStream)方法序列化此MimeMessage。 That call results in a FileNotFoundException: 该调用导致FileNotFoundException:

java.io.FileNotFoundException: ./files/test.txt: open failed: ENOENT (No such file or directory)

It seems like the writeTo() -Method is searching for the attached files. 似乎writeTo() - writeTo()正在搜索附件。 Shouldn't the files already be contained inside the MimeMessage-Object, through the attachFile() -call in my test data generator? 通过我的测试数据生成器中的attachFile()文件是否应该已经包含在MimeMessage-Object中? Do I have to do something with the MimeMessage-Object to be able to serialize it like that? 我是否需要对MimeMessage-Object进行某些操作才能将其序列化?

Try using a File object, where you can check if that file exists. 尝试使用File对象,您可以在其中检查该文件是否存在。

private static BodyPart createAttachment(filepath) {
    File file = new File(filepath);
    if (file.exists()) {
        DataSource source = new FileDataSource(file);
        DataHandler handler = new DataHandler(source);
        BodyPart attachment = new MimeBodyPart();
        attachment.setDataHandler(handler);
        attachment.setFileName(file.getName());
        return attachment;
    }
    return null; // or throw exception
}

I noticed that you're providing a relative path to a file (starting with a dot "."). 我注意到您正在提供文件的相对路径(以点“。”开头)。 That only works if the file is in the same directory (or a subdirectory in your case) where your application is executing from. 仅当文件位于应用程序执行所在的同一目录(或您的情况下的子目录)中时,此方法才有效。 Try using an absolute path instead. 尝试改用绝对路径

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM