Reputation: 431
I'm testing an application sending a mail with attachment in a integration environment. For this i'm setting up a fake smtp mail server (http://quintanasoft.com/dumbster/) and configure my application to use it. At the end of my test i want to check if my application has sent the email via my fake mail server and also want to know, if the content (at least the attached file) is exactly that i'm expecting.
Dumpster is wrapping these mails into its own objects just containing header key-value pairs and the body as plain text. My question is how i can easily part the mail body to get and evaluate the attached file content from it.
Upvotes: 1
Views: 2904
Reputation: 740
Attach a file that you are certain of the mime-types in javamail. Sending the email over smtp allows us to make use of the fact that there is a string of data inside the body of the email before the bytes of the file. The bytes of the file are base64 and get included in the main chunk of the characters of the email.
private static final String YOUR_ATTACMETN_DATA = "Content-Type: image/jpeg; name=Invoice.jpgContent-Transfer-Encoding: base64Content-Disposition: attachment; filename=image.jpg";
@Before
public final void setup() throws UserException{
server = SimpleSmtpServer.start();
}
@After
public final void tearDown(){
server.stop();
}
@Test
public void test_that_attachment_has_been_recieved() throws IOException, MessagingException {
email = getMessage();
YourEmailSendingClass.sendEmail(email);
Iterator<SmtpMessage> it = server.getReceivedEmail();
SmtpMessage recievedMessage = (SmtpMessage)it.next();
assertTrue(recievedMessage.getBody.contains(YOUR_ATTACHMENT_DATA)));
}
Here is another is a page of someone who did something similar to this in greater detail. http://www.lordofthejars.com/2012/04/why-does-rain-fall-from-above-why-do.html
Upvotes: 2
Reputation: 38265
As a place to start (not sure if there are easier ways to do it), consider using the JavaMail API. Try to grab the whole message (including headers) -- probably with SmtpMessage.toString()
, wrap it in some new ByteArrayInputStream(smtpMessage.toString().getBytes())
, and pass it to a javax.mail.internet.MimeMessage
.
(NOTE: I'm not that familiar with the MIME standard and I don't know if you should use the getBytes(Charset)
overload here).
Upvotes: 0