javax.mail.internet.MimeMultipart Java Examples

The following examples show how to use javax.mail.internet.MimeMultipart. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MailWithDKIMSignTest.java    From vertx-mail-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testMailSimpleSimpleNonFileAttachmentStreamCacheInFileWithLimit(TestContext testContext) {
  System.setProperty("vertx.mail.attachment.cache.file", "true");
  this.testContext = testContext;
  Buffer fakeData = fakeStreamData();
  byte[] fakeDataBytes = fakeData.getBytes();
  ReadStream<Buffer> fakeStream = new FakeReadStream(vertx.getOrCreateContext());
  MailAttachment attachment = MailAttachment.create().setName("FakeStream")
    .setStream(fakeStream)
    .setSize(fakeDataBytes.length);
  MailMessage message = exampleMessage().setText(TEXT_BODY).setAttachment(attachment);

  DKIMSignOptions dkimOps = new DKIMSignOptions(dkimOptionsBase).setBodyLimit(50)
    .setHeaderCanonAlgo(CanonicalizationAlgorithm.SIMPLE).setBodyCanonAlgo(CanonicalizationAlgorithm.SIMPLE);
  testSuccess(dkimMailClient(dkimOps), message, () -> {
    final MimeMultipart multiPart = (MimeMultipart)wiser.getMessages().get(0).getMimeMessage().getContent();
    testContext.assertEquals(2, multiPart.getCount());
    testContext.assertEquals(TEXT_BODY, conv2nl(inputStreamToString(multiPart.getBodyPart(0).getInputStream())));
    testContext.assertTrue(Arrays.equals(fakeDataBytes, inputStreamToBytes(multiPart.getBodyPart(1).getInputStream())));
    testDKIMSign(dkimOps, testContext);
  });
}
 
Example #2
Source File: MailServiceTest.java    From Mario with Apache License 2.0 6 votes vote down vote up
/**
 * 一个附件的邮件测试
 * 
 * @throws MessagingException
 * @throws InterruptedException
 * @throws IOException
 */
@Test
public void testSendMailFiles() throws MessagingException, InterruptedException, IOException {
    SimpleMailMessage message = buildSimpleMessage();
    String[] files = new String[] { EMAIL_ATTACHMENT };
    mimeMailService.sendMailFiles(message, files);

    greenMail.waitForIncomingEmail(2000, 1);

    MimeMessage[] msgs = greenMail.getReceivedMessages();
    MimeMultipart mimeMultipart = (MimeMultipart) msgs[0].getContent();

    assertEquals(1, msgs.length);
    assertEquals(MAIL_MESSAGE_FROM, msgs[0].getFrom()[0].toString());
    assertEquals(MAIL_MESSAGE_SUBJECT, msgs[0].getSubject());
    assertEquals(2, mimeMultipart.getCount());//multipart个数
    assertTrue(GreenMailUtil.getBody(mimeMultipart.getBodyPart(0)).trim()
            .contains(MAIL_MESSAGE_CONTEXT));
    assertEquals("Hello,i am a attachment.", GreenMailUtil
            .getBody(mimeMultipart.getBodyPart(1)).trim());
}
 
Example #3
Source File: EmailSendTaskTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Deployment
public void testTextMailWithFileAttachmentsByPath() throws Exception {
  HashMap<String, Object> vars = new HashMap<String, Object>();
  vars.put("attachmentsBean", new AttachmentsBean());
  runtimeService.startProcessInstanceByKey("textMailWithFileAttachmentsByPath", vars);

  List<WiserMessage> messages = wiser.getMessages();
  assertEquals(1, messages.size());
  WiserMessage message = messages.get(0);
  MimeMultipart mm = (MimeMultipart) message.getMimeMessage().getContent();
  File[] files = new AttachmentsBean().getFiles();
  assertEquals(1 + files.length, mm.getCount());
  for (int i = 0; i < files.length; i++) {
    String attachmentFileName = mm.getBodyPart(1 + i).getDataHandler().getName();
    assertEquals(files[i].getName(), attachmentFileName);
  }
}
 
Example #4
Source File: MailWithDKIMSignTest.java    From vertx-mail-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testMailSimpleSimpleAttachmentStream(TestContext testContext) {
  System.setProperty("vertx.mail.attachment.cache.file", "true");
  this.testContext = testContext;
  String path = "logo-white-big.png";
  Buffer img = vertx.fileSystem().readFileBlocking(path);
  ReadStream<Buffer> stream = vertx.fileSystem().openBlocking(path, new OpenOptions());
  MailAttachment attachment = MailAttachment.create().setName(path).setStream(stream).setSize(img.length());
  MailMessage message = exampleMessage().setText(TEXT_BODY).setAttachment(attachment);

  DKIMSignOptions dkimOps = new DKIMSignOptions(dkimOptionsBase)
    .setHeaderCanonAlgo(CanonicalizationAlgorithm.SIMPLE).setBodyCanonAlgo(CanonicalizationAlgorithm.SIMPLE);
  testSuccess(dkimMailClient(dkimOps), message, () -> {
    final MimeMultipart multiPart = (MimeMultipart)wiser.getMessages().get(0).getMimeMessage().getContent();
    testContext.assertEquals(2, multiPart.getCount());
    testContext.assertEquals(TEXT_BODY, conv2nl(inputStreamToString(multiPart.getBodyPart(0).getInputStream())));
    testContext.assertTrue(Arrays.equals(img.getBytes(), inputStreamToBytes(multiPart.getBodyPart(1).getInputStream())));
    testDKIMSign(dkimOps, testContext);
  });
}
 
Example #5
Source File: MailServiceIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void testSendMultipartEmail() throws Exception {
    mailService.sendEmail("[email protected]", "testSubject", "testContent", true, false);
    verify(javaMailSender).send(messageCaptor.capture());
    MimeMessage message = messageCaptor.getValue();
    MimeMultipart mp = (MimeMultipart) message.getContent();
    MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
    ByteArrayOutputStream aos = new ByteArrayOutputStream();
    part.writeTo(aos);
    assertThat(message.getSubject()).isEqualTo("testSubject");
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
    assertThat(message.getContent()).isInstanceOf(Multipart.class);
    assertThat(aos.toString()).isEqualTo("\r\ntestContent");
    assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8");
}
 
Example #6
Source File: Mailer.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
private static Multipart getMessagePart() throws MessagingException, IOException {
    Multipart multipart = new MimeMultipart();
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText(getVal("msg.Body"));
    multipart.addBodyPart(messageBodyPart);
    if (getBoolVal("attach.reports")) {
        LOG.info("Attaching Reports as zip");
        multipart.addBodyPart(getReportsBodyPart());
    } else {
        if (getBoolVal("attach.standaloneHtml")) {
            multipart.addBodyPart(getStandaloneHtmlBodyPart());
        }
        if (getBoolVal("attach.console")) {
            multipart.addBodyPart(getConsoleBodyPart());
        }
        if (getBoolVal("attach.screenshots")) {
            multipart.addBodyPart(getScreenShotsBodyPart());
        }
    }
    messageBodyPart.setContent(getVal("msg.Body")
            .concat("\n\n\n")
            .concat(MailComponent.getHTMLBody()), "text/html");
    return multipart;
}
 
Example #7
Source File: RegistrationIT.java    From usergrid with Apache License 2.0 6 votes vote down vote up
private Message[] getMessages(String host, String user, String password) throws MessagingException, IOException {

        Session session = Session.getDefaultInstance(new Properties());
        Store store = session.getStore("imap");
        store.connect(host, user, password);

        Folder folder = store.getFolder("inbox");
        folder.open(Folder.READ_ONLY);
        Message[] msgs = folder.getMessages();

        for (Message m : msgs) {
            logger.info("Subject: " + m.getSubject());
            logger.info(
                "Body content 0 " + ((MimeMultipart) m.getContent()).getBodyPart(0).getContent());
            logger.info(
                "Body content 1 " + ((MimeMultipart) m.getContent()).getBodyPart(1).getContent());
        }
        return msgs;
    }
 
Example #8
Source File: MimeMessageHelper.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Set the given plain text and HTML text as alternatives, offering
 * both options to the email client. Requires multipart mode.
 * <p><b>NOTE:</b> Invoke {@link #addInline} <i>after</i> {@code setText};
 * else, mail readers might not be able to resolve inline references correctly.
 * @param plainText the plain text for the message
 * @param htmlText the HTML text for the message
 * @throws MessagingException in case of errors
 */
public void setText(String plainText, String htmlText) throws MessagingException {
	Assert.notNull(plainText, "Plain text must not be null");
	Assert.notNull(htmlText, "HTML text must not be null");

	MimeMultipart messageBody = new MimeMultipart(MULTIPART_SUBTYPE_ALTERNATIVE);
	getMainPart().setContent(messageBody, CONTENT_TYPE_ALTERNATIVE);

	// Create the plain text part of the message.
	MimeBodyPart plainTextPart = new MimeBodyPart();
	setPlainTextToMimePart(plainTextPart, plainText);
	messageBody.addBodyPart(plainTextPart);

	// Create the HTML text part of the message.
	MimeBodyPart htmlTextPart = new MimeBodyPart();
	setHtmlTextToMimePart(htmlTextPart, htmlText);
	messageBody.addBodyPart(htmlTextPart);
}
 
Example #9
Source File: EmailSendTaskTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Deployment
public void testTextMailWithFileAttachments() throws Exception {
  HashMap<String, Object> vars = new HashMap<String, Object>();
  vars.put("attachmentsBean", new AttachmentsBean());
  runtimeService.startProcessInstanceByKey("textMailWithFileAttachments", vars);

  List<WiserMessage> messages = wiser.getMessages();
  assertEquals(1, messages.size());
  WiserMessage message = messages.get(0);
  MimeMultipart mm = (MimeMultipart) message.getMimeMessage().getContent();
  File[] files = new AttachmentsBean().getFiles();
  assertEquals(1 + files.length, mm.getCount());
  for (int i = 0; i < files.length; i++) {
    String attachmentFileName = mm.getBodyPart(1 + i).getDataHandler().getName();
    assertEquals(files[i].getName(), attachmentFileName);
  }
}
 
Example #10
Source File: EmailSendTaskTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Deployment
public void testTextMailWithDataSourceAttachment() throws Exception {
  String fileName = "file-name-to-be-displayed";
  String fileContent = "This is the file content";
  HashMap<String, Object> vars = new HashMap<String, Object>();
  vars.put("attachmentsBean", new AttachmentsBean());
  vars.put("fileContent", fileContent);
  vars.put("fileName", fileName);
  runtimeService.startProcessInstanceByKey("textMailWithDataSourceAttachment", vars);

  List<WiserMessage> messages = wiser.getMessages();
  assertEquals(1, messages.size());
  WiserMessage message = messages.get(0);
  MimeMultipart mm = (MimeMultipart) message.getMimeMessage().getContent();
  assertEquals(2, mm.getCount());
  String attachmentFileName = mm.getBodyPart(1).getDataHandler().getName();
  assertEquals(fileName, attachmentFileName);
}
 
Example #11
Source File: EmailSendTaskTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Test
@Deployment
public void testTextMailWithDataSourceAttachment() throws Exception {
    String fileName = "file-name-to-be-displayed";
    String fileContent = "This is the file content";
    HashMap<String, Object> vars = new HashMap<>();
    vars.put("attachmentsBean", new AttachmentsBean());
    vars.put("fileContent", fileContent);
    vars.put("fileName", fileName);
    runtimeService.startProcessInstanceByKey("textMailWithDataSourceAttachment", vars);

    List<WiserMessage> messages = wiser.getMessages();
    assertThat(messages).hasSize(1);
    WiserMessage message = messages.get(0);
    MimeMultipart mm = (MimeMultipart) message.getMimeMessage().getContent();
    assertThat(mm.getCount()).isEqualTo(2);
    String attachmentFileName = mm.getBodyPart(1).getDataHandler().getName();
    assertThat(attachmentFileName).isEqualTo(fileName);
}
 
Example #12
Source File: MailServiceIT.java    From jhipster-online with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendMultipartEmail() throws Exception {
    mailService.sendEmail("[email protected]", "testSubject", "testContent", true, false);
    verify(javaMailSender).send(messageCaptor.capture());
    MimeMessage message = messageCaptor.getValue();
    MimeMultipart mp = (MimeMultipart) message.getContent();
    MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
    ByteArrayOutputStream aos = new ByteArrayOutputStream();
    part.writeTo(aos);
    assertThat(message.getSubject()).isEqualTo("testSubject");
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getFrom()[0].toString()).isEqualTo("JHipster Online <test@localhost>");
    assertThat(message.getContent()).isInstanceOf(Multipart.class);
    assertThat(aos.toString()).isEqualTo("\r\ntestContent");
    assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8");
}
 
Example #13
Source File: EmailServiceTaskTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Deployment
public void testTextMailWithFileAttachmentsByPath() throws Exception {
  HashMap<String, Object> vars = new HashMap<String, Object>();
  vars.put("attachmentsBean", new AttachmentsBean());
  runtimeService.startProcessInstanceByKey("textMailWithFileAttachmentsByPath", vars);

  List<WiserMessage> messages = wiser.getMessages();
  assertEquals(1, messages.size());
  WiserMessage message = messages.get(0);
  MimeMultipart mm = (MimeMultipart) message.getMimeMessage().getContent();
  File[] files = new AttachmentsBean().getFiles();
  assertEquals(1 + files.length, mm.getCount());
  for (int i = 0; i < files.length; i++) {
    String attachmentFileName = mm.getBodyPart(1 + i).getDataHandler().getName();
    assertEquals(files[i].getName(), attachmentFileName);
  }
}
 
Example #14
Source File: EmailServiceTaskTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Deployment
public void testTextMailWithFileAttachmentsByPath() throws Exception {
    HashMap<String, Object> vars = new HashMap<String, Object>();
    vars.put("attachmentsBean", new AttachmentsBean());
    runtimeService.startProcessInstanceByKey("textMailWithFileAttachmentsByPath", vars);

    List<WiserMessage> messages = wiser.getMessages();
    assertEquals(1, messages.size());
    WiserMessage message = messages.get(0);
    MimeMultipart mm = (MimeMultipart) message.getMimeMessage().getContent();
    File[] files = new AttachmentsBean().getFiles();
    assertEquals(1 + files.length, mm.getCount());
    for (int i = 0; i < files.length; i++) {
        String attachmentFileName = mm.getBodyPart(1 + i).getDataHandler().getName();
        assertEquals(files[i].getName(), attachmentFileName);
    }
}
 
Example #15
Source File: EmailServiceTaskTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Test
@Deployment
public void testTextMailWithFileAttachmentsByPath() throws Exception {
    HashMap<String, Object> vars = new HashMap<>();
    vars.put("attachmentsBean", new AttachmentsBean());
    runtimeService.startProcessInstanceByKey("textMailWithFileAttachmentsByPath", vars);

    List<WiserMessage> messages = wiser.getMessages();
    assertThat(messages).hasSize(1);
    WiserMessage message = messages.get(0);
    MimeMultipart mm = (MimeMultipart) message.getMimeMessage().getContent();
    File[] files = new AttachmentsBean().getFiles();
    assertThat(mm.getCount()).isEqualTo(1 + files.length);
    for (int i = 0; i < files.length; i++) {
        String attachmentFileName = mm.getBodyPart(1 + i).getDataHandler().getName();
        assertThat(attachmentFileName).isEqualTo(files[i].getName());
    }
}
 
Example #16
Source File: GMailSender.java    From vocefiscal-android with Apache License 2.0 6 votes vote down vote up
public GMailSender() 
{ 
  host = "smtp.gmail.com"; // default smtp server 
  port = "465"; // default smtp port 
  sport = "465"; // default socketfactory port 

  user = ""; // username 
  pass = ""; // password 
  from = ""; // email sent from 
  subject = ""; // email subject 
  body = ""; // email body 

  debuggable = false; // debug mode on or off - default off 
  auth = true; // smtp authentication - default on 

  multipart = new MimeMultipart(); 

  // There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added. 
  MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); 
  mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); 
  mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); 
  mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); 
  mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); 
  mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); 
  CommandMap.setDefaultCommandMap(mc); 
}
 
Example #17
Source File: EmailServiceTaskTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Deployment
public void testTextMailWithFileAttachmentsByPath() throws Exception {
  HashMap<String, Object> vars = new HashMap<String, Object>();
  vars.put("attachmentsBean", new AttachmentsBean());
  runtimeService.startProcessInstanceByKey("textMailWithFileAttachmentsByPath", vars);

  List<WiserMessage> messages = wiser.getMessages();
  assertEquals(1, messages.size());
  WiserMessage message = messages.get(0);
  MimeMultipart mm = (MimeMultipart) message.getMimeMessage().getContent();
  File[] files = new AttachmentsBean().getFiles();
  assertEquals(1 + files.length, mm.getCount());
  for (int i = 0; i < files.length; i++) {
    String attachmentFileName = mm.getBodyPart(1 + i).getDataHandler().getName();
    assertEquals(files[i].getName(), attachmentFileName);
  }
}
 
Example #18
Source File: EmailServiceTaskTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Deployment
public void testTextMailWithFileAttachments() throws Exception {
  HashMap<String, Object> vars = new HashMap<String, Object>();
  vars.put("attachmentsBean", new AttachmentsBean());
  runtimeService.startProcessInstanceByKey("textMailWithFileAttachments", vars);

  List<WiserMessage> messages = wiser.getMessages();
  assertEquals(1, messages.size());
  WiserMessage message = messages.get(0);
  MimeMultipart mm = (MimeMultipart) message.getMimeMessage().getContent();
  File[] files = new AttachmentsBean().getFiles();
  assertEquals(1 + files.length, mm.getCount());
  for (int i = 0; i < files.length; i++) {
    String attachmentFileName = mm.getBodyPart(1 + i).getDataHandler().getName();
    assertEquals(files[i].getName(), attachmentFileName);
  }
}
 
Example #19
Source File: Solution.java    From JavaRushTasks with MIT License 6 votes vote down vote up
public static void setAttachment(Message message, String filename) throws MessagingException {
    // Create a multipar message
    Multipart multipart = new MimeMultipart();
    BodyPart messageBodyPart = new MimeBodyPart();

    //Set File
    DataSource source = new FileDataSource(filename);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);

    //Add "file part" to multipart
    multipart.addBodyPart(messageBodyPart);

    //Set multipart to message
    message.setContent(multipart);
}
 
Example #20
Source File: MessageAlteringUtils.java    From james-project with Apache License 2.0 6 votes vote down vote up
/**
 * Builds the message of the newMail in case it has to be altered.
 */
private MimeMessage alteredMessage() throws MessagingException {
    MimeMessage originalMessage = originalMail.getMessage();
    MimeMessage newMessage = new MimeMessage(Session.getDefaultInstance(System.getProperties(), null));

    // Copy the relevant headers
    copyRelevantHeaders(originalMessage, newMessage);

    String head = new MimeMessageUtils(originalMessage).getMessageHeaders();
    try {
        MimeMultipart multipart = generateMultipartContent(originalMessage, head);

        newMessage.setContent(multipart);
        newMessage.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType());
        return newMessage;
    } catch (Exception ioe) {
        throw new MessagingException("Unable to create multipart body", ioe);
    }
}
 
Example #21
Source File: MailerImplTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private String getInlineAttachment(String cid, MimeMultipart multipart) throws IOException, MessagingException {
    for (int i = 0; i < multipart.getCount(); i++) {
        BodyPart bodyPart = multipart.getBodyPart(i);
        if (bodyPart.getContent() instanceof MimeMultipart) {
            for (int j = 0; j < ((MimeMultipart) bodyPart.getContent()).getCount(); j++) {
                BodyPart nested = ((MimeMultipart) bodyPart.getContent()).getBodyPart(j);
                if (nested.getHeader("Content-ID") != null && nested.getHeader("Content-ID")[0].equalsIgnoreCase(cid)) {
                    assertThat(nested.getDisposition()).isEqualTo("inline");
                    assertThat(nested.getContentType()).startsWith(TEXT_CONTENT_TYPE);
                    return read(nested);
                }
            }
        }
    }
    return null;
}
 
Example #22
Source File: EmailSendTaskTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Deployment
public void testTextMailWithFileAttachments() throws Exception {
    HashMap<String, Object> vars = new HashMap<String, Object>();
    vars.put("attachmentsBean", new AttachmentsBean());
    runtimeService.startProcessInstanceByKey("textMailWithFileAttachments", vars);

    List<WiserMessage> messages = wiser.getMessages();
    assertEquals(1, messages.size());
    WiserMessage message = messages.get(0);
    MimeMultipart mm = (MimeMultipart) message.getMimeMessage().getContent();
    File[] files = new AttachmentsBean().getFiles();
    assertEquals(1 + files.length, mm.getCount());
    for (int i = 0; i < files.length; i++) {
        String attachmentFileName = mm.getBodyPart(1 + i).getDataHandler().getName();
        assertEquals(files[i].getName(), attachmentFileName);
    }
}
 
Example #23
Source File: MultiContentHandler.java    From ogham with Apache License 2.0 6 votes vote down vote up
@Override
public void setContent(MimePart message, Multipart multipart, Email email, Content content) throws ContentHandlerException {
	try {
		MultiContent multiContent = (MultiContent) content;
		MimeMultipart mp = new MimeMultipart("alternative");
		for (Content c : multiContent.getContents()) {
			delegate.setContent(message, mp, email, c);
		}
		// add the part
		MimeBodyPart part = new MimeBodyPart();
		part.setContent(mp);
		multipart.addBodyPart(part);
	} catch (MessagingException e) {
		throw new ContentHandlerException("Failed to generate alternative content", content, e);
	}
}
 
Example #24
Source File: MailServiceIT.java    From jhipster-online with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendMultipartHtmlEmail() throws Exception {
    mailService.sendEmail("[email protected]", "testSubject", "testContent", true, true);
    verify(javaMailSender).send(messageCaptor.capture());
    MimeMessage message = messageCaptor.getValue();
    MimeMultipart mp = (MimeMultipart) message.getContent();
    MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
    ByteArrayOutputStream aos = new ByteArrayOutputStream();
    part.writeTo(aos);
    assertThat(message.getSubject()).isEqualTo("testSubject");
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getFrom()[0].toString()).isEqualTo("JHipster Online <test@localhost>");
    assertThat(message.getContent()).isInstanceOf(Multipart.class);
    assertThat(aos.toString()).isEqualTo("\r\ntestContent");
    assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
 
Example #25
Source File: MailServiceIntTest.java    From Full-Stack-Development-with-JHipster with MIT License 6 votes vote down vote up
@Test
public void testSendMultipartHtmlEmail() throws Exception {
    mailService.sendEmail("[email protected]", "testSubject", "testContent", true, true);
    verify(javaMailSender).send((MimeMessage) messageCaptor.capture());
    MimeMessage message = (MimeMessage) messageCaptor.getValue();
    MimeMultipart mp = (MimeMultipart) message.getContent();
    MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
    ByteArrayOutputStream aos = new ByteArrayOutputStream();
    part.writeTo(aos);
    assertThat(message.getSubject()).isEqualTo("testSubject");
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
    assertThat(message.getContent()).isInstanceOf(Multipart.class);
    assertThat(aos.toString()).isEqualTo("\r\ntestContent");
    assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
 
Example #26
Source File: GreenMailUtil.java    From greenmail with Apache License 2.0 6 votes vote down vote up
public static boolean hasNonTextAttachments(Part m) {
    try {
        Object content = m.getContent();
        if (content instanceof MimeMultipart) {
            MimeMultipart mm = (MimeMultipart) content;
            for (int i = 0; i < mm.getCount(); i++) {
                BodyPart p = mm.getBodyPart(i);
                if (hasNonTextAttachments(p)) {
                    return true;
                }
            }
            return false;
        } else {
            return !m.getContentType().trim().toLowerCase().startsWith("text");
        }
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example #27
Source File: Converter7BitTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
void convertTo7BitShouldAlertTextPartHeaders() throws Exception {
    MimeMessage mimeMessage = MimeMessageUtil.mimeMessageFromString(
            fileContent("eml/multipart-8bit.eml"));

    testee.convertTo7Bit(mimeMessage);

    BodyPart textPart = ((MimeMultipart) mimeMessage.getContent())
        .getBodyPart(0);

    SoftAssertions.assertSoftly(Throwing.consumer(softly -> {
       assertThat(textPart.getHeader(CONTENT_TRANSFER_ENCODING))
           .containsOnly(QUOTED_PRINTABLE);
       assertThat(textPart.getHeader(X_MIME_AUTOCONVERTED))
           .containsOnly("from 8bit to quoted-printable by Mock Server");
    }));
}
 
Example #28
Source File: NntpUtil.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
public  static String getArticleBody(NNTPClient client, long articleNumber)
	throws IOException {
	String articleBody = null;
	//We convert the full message into a MIME message for getting exactly the text message clean
	Reader reader = (DotTerminatedMessageReader) client.retrieveArticle(articleNumber);
	if (reader != null) {
		InputStream inputStream = new ByteArrayInputStream(CharStreams.toString(reader).getBytes(Charsets.UTF_8));
		try {
			Session session = Session.getInstance(new Properties());	//For parsing the messages correctly
			MimeMessage message = new MimeMessage(session, inputStream);
			Object contentObject = message.getContent();
			if(!(contentObject instanceof MimeMultipart))
				articleBody = (String)contentObject;
			else
				articleBody = getBodyPart((MimeMultipart) contentObject);
			
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} else {
		return articleBody;
	}
	return articleBody;
}
 
Example #29
Source File: MailTest.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
private Message createMimeMessage( String specialCharacters, File attachedFile ) throws Exception {
  Session session = Session.getInstance( new Properties() );
  Message message = new MimeMessage( session );

  MimeMultipart multipart = new MimeMultipart();
  MimeBodyPart attachedFileAndContent = new MimeBodyPart();
  attachedFile.deleteOnExit();
  // create a data source
  URLDataSource fds = new URLDataSource( attachedFile.toURI().toURL() );
  // get a data Handler to manipulate this file type;
  attachedFileAndContent.setDataHandler( new DataHandler( fds ) );
  // include the file in the data source
  String tempFileName = attachedFile.getName();
  message.setSubject( specialCharacters );
  attachedFileAndContent.setFileName( tempFileName );
  attachedFileAndContent.setText( specialCharacters );

  multipart.addBodyPart( attachedFileAndContent );
  message.setContent( multipart );

  return message;
}
 
Example #30
Source File: MailServerImpl.java    From webcurator with Apache License 2.0 6 votes vote down vote up
public void sendHTML(Mailable email) throws MessagingException {
    Session mailSession = Session.getInstance(this.mailConfig, null);
    MimeMessage message = new MimeMessage(mailSession);
    MimeMultipart multipart = new MimeMultipart("alternative");
    BodyPart bp = new MimeBodyPart();
    bp.setContent(email.getMessage(), "text/plain; charset=UTF-8");
    BodyPart bp2 = new MimeBodyPart();
    bp2.setContent(email.getMessage(), "text/html; charset=UTF-8");
    
    multipart.addBodyPart(bp2);
    multipart.addBodyPart(bp);
    message.setContent(multipart);
    message.setSentDate(new java.util.Date());
    message.setFrom(new InternetAddress(email.getSender()));
    message.setSubject(email.getSubject());
    //FIXME if more than one recipient break it appart before setting the recipient field
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(email.getRecipients()));
    Transport.send(message);
}