use of javax.mail.BodyPart in project ddf by codice.
the class SmtpClientImplITCase method testSendWithAttachments.
@Test
public void testSendWithAttachments() throws IOException, MessagingException, ExecutionException, InterruptedException {
int port = findAvailablePort();
SimpleSmtpServer server = SimpleSmtpServer.start(port);
SmtpClientImpl emailService = new SmtpClientImpl();
emailService.setHostName(HOSTNAME);
emailService.setPortNumber(port);
File tmpFile = folder.newFile("email.txt");
try (OutputStream os = new FileOutputStream(tmpFile)) {
os.write(ATTACHMENT_TEXT.getBytes());
}
Session session = emailService.createSession();
MimeMessage mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress(FROM_ADDR));
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_ADDR));
mimeMessage.setSubject(SUBJECT);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(BODY);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(tmpFile)));
messageBodyPart.setFileName(ATTACHMENT_FILENAME);
multipart.addBodyPart(messageBodyPart);
mimeMessage.setContent(multipart);
emailService.send(mimeMessage).get();
server.stop();
assertThat(server.getReceivedEmailSize(), is(1));
Iterator emailIterator = server.getReceivedEmail();
SmtpMessage email = (SmtpMessage) emailIterator.next();
assertThat(email.getHeaderValue(SUBJECT_HEADER), is(SUBJECT));
assertThat(email.getHeaderValue(FROM_HEADER), containsString(FROM_ADDR));
assertThat(email.getHeaderValue(TO_HEADER), containsString(TO_ADDR));
assertThat(email.getBody(), containsString(BODY));
assertThat(email.getBody(), containsString(ATTACHMENT_TEXT));
assertThat(email.getBody(), containsString(ATTACHMENT_FILENAME));
}
Aggregations