Java Code Examples for javax.mail.internet.MimeMessage

The following examples show how to use javax.mail.internet.MimeMessage. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: SpringBootLearn   Source File: MailTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 发送静态邮箱
 * @throws Exception
 */
@Test
public void sendStaticMail() throws Exception {
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    helper.setFrom(username);
    helper.setTo("[email protected]");
    helper.setSubject("测试主题:嵌入静态资源");
    helper.setText("<html><body><img src=\"cid:weixin_qrcode\" ></body></html>", true);
    FileSystemResource file = new FileSystemResource(new File("weixin_qrcode.jpg"));
    // addInline函数中资源名称jpg需要与正文中cid:weixin_qrcode对应起来
    helper.addInline("weixin_qrcode", file);
    javaMailSender.send(mimeMessage);

}
 
Example 2
Source Project: james-project   Source File: JamesMailetContextTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void sendMailForMessageAndEnvelopeShouldEnqueueEmailWithRootState() throws Exception {
    MimeMessage message = MimeMessageBuilder.mimeMessageBuilder()
        .addFrom(mailAddress.asString())
        .addToRecipient(mailAddress.asString())
        .setText("Simple text")
        .build();

    MailAddress sender = mailAddress;
    ImmutableList<MailAddress> recipients = ImmutableList.of(mailAddress);
    testee.sendMail(sender, recipients, message);

    ArgumentCaptor<Mail> mailArgumentCaptor = ArgumentCaptor.forClass(Mail.class);
    verify(spoolMailQueue).enQueue(mailArgumentCaptor.capture());
    verifyNoMoreInteractions(spoolMailQueue);

    assertThat(mailArgumentCaptor.getValue().getState()).isEqualTo(Mail.DEFAULT);
}
 
Example 3
Source Project: james-project   Source File: ContentReplacerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void applyPatternShouldModifyWhenMatchingSubject() throws Exception {
    ContentReplacer testee = new ContentReplacer(false);

    Mail mail = mock(Mail.class);
    MimeMessage mimeMessage = mock(MimeMessage.class);
    when(mail.getMessage())
        .thenReturn(mimeMessage);
    when(mimeMessage.getSubject())
        .thenReturn("test aa o");
    when(mimeMessage.getContentType())
        .thenReturn("text/plain");

    ImmutableList<ReplacingPattern> patterns = ImmutableList.of(new ReplacingPattern(Pattern.compile("test"), false, "TEST"),
        new ReplacingPattern(Pattern.compile("a"), true, "e"),
        new ReplacingPattern(Pattern.compile("o"), false, "o"));
    ReplaceConfig replaceConfig = ReplaceConfig.builder()
            .addAllSubjectReplacingUnits(patterns)
            .build();
    testee.replaceMailContentAndSubject(mail, replaceConfig, Optional.of(StandardCharsets.UTF_8));

    verify(mimeMessage).setSubject("TEST ee o", StandardCharsets.UTF_8.name());
}
 
Example 4
Source Project: commons-email   Source File: EmailTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCorrectContentTypeForPNG() throws Exception
{
    email.setHostName(strTestMailServer);
    email.setSmtpPort(getMailServerPort());
    email.setFrom("[email protected]");
    email.addTo("[email protected]");
    email.setSubject("test mail");

    email.setCharset("ISO-8859-1");
    final File png = new File("./target/test-classes/images/logos/maven-feather.png");
    email.setContent(png, "image/png");
    email.buildMimeMessage();
    final MimeMessage msg = email.getMimeMessage();
    msg.saveChanges();
    assertEquals("image/png", msg.getContentType());
}
 
Example 5
Source Project: scipio-erp   Source File: MimeMessageWrapper.java    License: Apache License 2.0 6 votes vote down vote up
public synchronized void setMessage(MimeMessage message) {
    if (message != null) {
        // serialize the message
        this.message = message;
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            message.writeTo(baos);
            baos.flush();
            serializedBytes = baos.toByteArray();
            this.contentType = message.getContentType();

            // see if this is a multi-part message
            Object content = message.getContent();
            if (content instanceof Multipart) {
                Multipart mp = (Multipart) content;
                this.parts = mp.getCount();
            } else {
                this.parts = 0;
            }
        } catch (IOException | MessagingException e) {
            Debug.logError(e, module);
        }
    }
}
 
Example 6
Source Project: cola-cloud   Source File: MailSender.java    License: MIT License 6 votes vote down vote up
/**
 * 发送html邮件
 */
public void sendHtmlMail(MailSenderParams params) {
    MimeMessage message = null;
    try {
        message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        //helper.setFrom(new InternetAddress(this.getFrom(), MimeUtility.encodeText(this.name,"UTF-8", "B")));
        helper.setFrom(this.getFrom());
        helper.setTo(params.getMailTo());
        helper.setSubject(params.getTitle());
        helper.setText(params.getContent(), true);
        this.addAttachment(helper,params);
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("发送邮件异常! from: " + name+ "! to: " + params.getMailTo());
    }
    javaMailSender.send(message);
}
 
Example 7
Source Project: olat   Source File: MailHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
    * Create a configures mail message object that is ready to use
    * 
    * @return MimeMessage
    */
static MimeMessage createMessage() {
       Properties p = new Properties();
       p.put("mail.smtp.host", mailhost);
       p.put("mail.smtp.timeout", mailhostTimeout);
       p.put("mail.smtp.connectiontimeout", mailhostTimeout);
       p.put("mail.smtp.ssl.enable", sslEnabled);
       p.put("mail.smtp.ssl.checkserveridentity", sslCheckCertificate);
       Session mailSession;
       if (smtpAuth == null) {
           mailSession = javax.mail.Session.getInstance(p);
       } else {
           // use smtp authentication from configuration
           p.put("mail.smtp.auth", "true");
           mailSession = Session.getDefaultInstance(p, smtpAuth);
       }
       if (log.isDebugEnabled()) {
           // enable mail session debugging on console
           mailSession.setDebug(true);
       }
       return new MimeMessage(mailSession);
   }
 
Example 8
@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("[email protected]");
    assertThat(message.getContent()).isInstanceOf(Multipart.class);
    assertThat(aos.toString()).isEqualTo("\r\ntestContent");
    assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
 
Example 9
Source Project: jakduk-api   Source File: EmailService.java    License: MIT License 6 votes vote down vote up
public void sendBulk(EmailPayload emailPayload) throws MessagingException {

		// Prepare the evaluation context
		final Context ctx = new Context(emailPayload.getLocale());
		ctx.setVariables(emailPayload.getBody());

		// Prepare message using a Spring helper
		final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
		final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");

		message.setSubject(emailPayload.getSubject());
		message.setTo(emailPayload.getRecipientEmail());

		// Create the HTML body using Thymeleaf
		final String htmlContent = this.htmlTemplateEngine.process(emailPayload.getTemplateName(), ctx);
		message.setText(htmlContent, true /* isHtml */);

		// Send email
		this.mailSender.send(mimeMessage);
	}
 
Example 10
Source Project: james-project   Source File: ContactExtractorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void serviceShouldParseMultipleRecipients() throws Exception {
    String rawMessage = "From: [email protected]\r\n"
        + "To: User 1 <[email protected]>, =?UTF-8?Q?recip_>>_Fr=c3=a9d=c3=a9ric_RECIPIENT?= <[email protected]>\r\n"
        + "Subject: extract this recipient please\r\n"
        + "\r\n"
        + "Please!";
    MimeMessage message = MimeMessageUtil.mimeMessageFromString(rawMessage);
    FakeMail mail = FakeMail.builder()
        .name("mail")
        .mimeMessage(message)
        .sender(SENDER)
        .recipient("[email protected]")
        .build();
    mailet.init(mailetConfig);

    String expectedMessage = "{\"userEmail\" : \"" + SENDER + "\", \"emails\" : [ \"User 1 <[email protected]>\", \"\\\"recip >> Frédéric RECIPIENT\\\" <[email protected]>\" ]}";
    mailet.service(mail);

    assertThat(mail.getAttribute(ATTRIBUTE_NAME)).hasValueSatisfying(json ->
            assertThatJson(json.getValue().value().toString()).isEqualTo(expectedMessage));
}
 
Example 11
Source Project: appengine-tck   Source File: MailHandlerServlet.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Stores subject and headers into memcache for test to confirm mail delivery.
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Session session = Session.getDefaultInstance(new Properties(), null);
    try {
        MimeMessage message = new MimeMessage(session, req.getInputStream());
        MimeProperties mp = new MimeProperties(message);

        List<String> headers = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        Enumeration e = message.getAllHeaderLines();
        while (e.hasMoreElements()) {
            String headerLine = (String) e.nextElement();
            headers.add(headerLine);
            sb.append("\n").append(headerLine);
        }
        log.info("HEADERS: " + sb.toString());

        mp.headers = headers.toString();
        TestBase.putTempData(mp);
    } catch (MessagingException me) {
        throw new IOException("Error while processing email.", me);
    }
}
 
Example 12
Source Project: ehcache3-samples   Source File: MailService.java    License: Apache License 2.0 6 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name());
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMail().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent email to User '{}'", to);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.warn("Email could not be sent to user '{}'", to, e);
        } else {
            log.warn("Email could not be sent to user '{}': {}", to, e.getMessage());
        }
    }
}
 
Example 13
Source Project: teammates   Source File: JavamailService.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public MimeMessage parseToEmail(EmailWrapper wrapper) throws MessagingException, IOException {
    Session session = Session.getDefaultInstance(new Properties(), null);
    MimeMessage email = new MimeMessage(session);
    if (wrapper.getSenderName() == null || wrapper.getSenderName().isEmpty()) {
        email.setFrom(new InternetAddress(wrapper.getSenderEmail()));
    } else {
        email.setFrom(new InternetAddress(wrapper.getSenderEmail(), wrapper.getSenderName()));
    }
    email.setReplyTo(new Address[] { new InternetAddress(wrapper.getReplyTo()) });
    email.addRecipient(Message.RecipientType.TO, new InternetAddress(wrapper.getRecipient()));
    if (wrapper.getBcc() != null && !wrapper.getBcc().isEmpty()) {
        email.addRecipient(Message.RecipientType.BCC, new InternetAddress(wrapper.getBcc()));
    }
    email.setSubject(wrapper.getSubject());
    email.setContent(wrapper.getContent(), "text/html");
    return email;
}
 
Example 14
@Test
public void verifyEmailClickLinkRequiredActionsCleared() throws IOException, MessagingException {
    try (Closeable u = new UserAttributeUpdater(testRealm().users().get(testUserId))
            .setEmailVerified(true)
            .setRequiredActions()
            .update()) {
        testRealm().users().get(testUserId).executeActionsEmail(Arrays.asList(RequiredAction.VERIFY_EMAIL.name()));

        Assert.assertEquals(1, greenMail.getReceivedMessages().length);
        MimeMessage message = greenMail.getLastReceivedMessage();

        String verificationUrl = getPasswordResetEmailLink(message);

        driver.manage().deleteAllCookies();

        driver.navigate().to(verificationUrl);

        accountPage.setAuthRealm(testRealm().toRepresentation().getRealm());
        accountPage.navigateTo();

        loginPage.assertCurrent();
        loginPage.login("[email protected]", "password");

        accountPage.assertCurrent();
    }
}
 
Example 15
Source Project: spring4-understanding   Source File: JavaMailSenderTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void javaMailSenderWithParseExceptionOnMimeMessagePreparator() {
	MockJavaMailSender sender = new MockJavaMailSender();
	MimeMessagePreparator preparator = new MimeMessagePreparator() {
		@Override
		public void prepare(MimeMessage mimeMessage) throws MessagingException {
			mimeMessage.setFrom(new InternetAddress(""));
		}
	};
	try {
		sender.send(preparator);
	}
	catch (MailParseException ex) {
		// expected
		assertTrue(ex.getCause() instanceof AddressException);
	}
}
 
Example 16
Source Project: james-project   Source File: JamesMailetContext.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Place a mail on the spool for processing
 *
 * @param message the message to send
 * @throws MessagingException if an exception is caught while placing the mail on the spool
 */
@Override
public void sendMail(MimeMessage message) throws MessagingException {
    MailAddress sender = new MailAddress((InternetAddress) message.getFrom()[0]);
    Collection<MailAddress> recipients = new HashSet<>();
    Address[] addresses = message.getAllRecipients();
    if (addresses != null) {
        for (Address address : addresses) {
            // Javamail treats the "newsgroups:" header field as a
            // recipient, so we want to filter those out.
            if (address instanceof InternetAddress) {
                recipients.add(new MailAddress((InternetAddress) address));
            }
        }
    }
    sendMail(sender, recipients, message);
}
 
Example 17
@Test
public void isMdnSentAutomaticallyShouldManageItsMimeType() throws Exception {
    MimeMessage message = MimeMessageUtil.defaultMimeMessage();
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart scriptPart = new MimeBodyPart();
    scriptPart.setDataHandler(
            new DataHandler(
                    new ByteArrayDataSource(
                            "Disposition: MDN-sent-automatically",
                            "text/plain")
                    ));
    scriptPart.setHeader("Content-Type", "text/plain");
    multipart.addBodyPart(scriptPart);
    message.setContent(multipart);
    message.saveChanges();
    
    FakeMail fakeMail = FakeMail.builder()
            .name("mail")
            .sender("[email protected]")
            .mimeMessage(message)
            .build();

    assertThat(new AutomaticallySentMailDetectorImpl().isMdnSentAutomatically(fakeMail)).isFalse();
}
 
Example 18
Source Project: jbpm-work-items   Source File: SendMailWorkitemHandler.java    License: Apache License 2.0 6 votes vote down vote up
public Message sendMessage(Gmail service,
                           String to,
                           String from,
                           String subject,
                           String bodyText,
                           Document attachment)
        throws MessagingException, IOException {
    MimeMessage mimeMessage = createEmailWithAttachment(to,
                                                        from,
                                                        subject,
                                                        bodyText,
                                                        attachment);
    Message message = service.users().messages().send(from,
                                                      createMessageWithEmail(mimeMessage)).execute();

    return message;
}
 
Example 19
Source Project: disconf   Source File: MailBean.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 发送html邮件
 *
 * @throws MessagingException
 * @throws AddressException
 */
public void sendHtmlMail(String from, String[] to, String title, String text)
        throws AddressException, MessagingException {

    long start = System.currentTimeMillis();

    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "GBK");

    InternetAddress[] toArray = new InternetAddress[to.length];
    for (int i = 0; i < to.length; i++) {
        toArray[i] = new InternetAddress(to[i]);
    }

    messageHelper.setFrom(new InternetAddress(from));
    messageHelper.setTo(toArray);
    messageHelper.setSubject(title);
    messageHelper.setText(text, true);
    mimeMessage = messageHelper.getMimeMessage();
    mailSender.send(mimeMessage);
    long end = System.currentTimeMillis();
    LOG.info("send mail start:" + start + " end :" + end);
}
 
Example 20
Source Project: jhipster-online   Source File: MailServiceIT.java    License: 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 <[email protected]>");
    assertThat(message.getContent()).isInstanceOf(Multipart.class);
    assertThat(aos.toString()).isEqualTo("\r\ntestContent");
    assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
 
Example 21
Source Project: Moss   Source File: MailNotifierTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void should_send_mail_using_default_template() throws IOException, MessagingException {
    Map<String, Object> details = new HashMap<>();
    details.put("Simple Value", 1234);
    details.put("Complex Value", singletonMap("Nested Simple Value", "99!"));

    StepVerifier.create(notifier.notify(
        new InstanceStatusChangedEvent(instance.getId(), instance.getVersion(), StatusInfo.ofDown(details))))
                .verifyComplete();

    ArgumentCaptor<MimeMessage> mailCaptor = ArgumentCaptor.forClass(MimeMessage.class);
    verify(sender).send(mailCaptor.capture());

    MimeMessage mail = mailCaptor.getValue();

    assertThat(mail.getSubject()).isEqualTo("application-name (cafebabe) is DOWN");
    assertThat(mail.getRecipients(Message.RecipientType.TO)).containsExactly(new InternetAddress("[email protected]"));
    assertThat(mail.getRecipients(Message.RecipientType.CC)).containsExactly(new InternetAddress("[email protected]"));
    assertThat(mail.getFrom()).containsExactly(new InternetAddress("SBA <[email protected]>"));
    assertThat(mail.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");

    String body = extractBody(mail.getDataHandler());
    assertThat(body).isEqualTo(loadExpectedBody("expected-default-mail"));
}
 
Example 22
Source Project: Project   Source File: SpitterMailServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
* <p>描述:富文本email</p>
* @param to
* @param spittle
* @throws MessagingException
 */
public void sendRichEmail(String to, Spittle spittle) throws MessagingException {
	MimeMessage message = mailSender.createMimeMessage();
	MimeMessageHelper helper = new MimeMessageHelper(message, true);
	String spitterName = spittle.getSpitter().getFullName();
	helper.setFrom("[email protected]");
	helper.setTo(to);
	helper.setSubject("New spittle from " + spitterName);
	helper.setText("<html><body><img src='cid:spitterLogo'>"
			+ "<h4>"+spitterName+" says:</h4>"
			+ "<i>"+spittle.getText()+"</i>"
			+ "</body></html>", true);
	ClassPathResource couponImage = new ClassPathResource("/collateral/coupon.jpg");
	helper.addInline("spitterLogo", couponImage);
	mailSender.send(message);
}
 
Example 23
Source Project: pentaho-kettle   Source File: MailTest.java    License: 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 24
Source Project: spring-boot-demo   Source File: MailServiceImpl.java    License: MIT License 6 votes vote down vote up
/**
 * 发送带附件的邮件
 *
 * @param to       收件人地址
 * @param subject  邮件主题
 * @param content  邮件内容
 * @param filePath 附件地址
 * @param cc       抄送地址
 * @throws MessagingException 邮件发送异常
 */
@Override
public void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content, true);
    if (ArrayUtil.isNotEmpty(cc)) {
        helper.setCc(cc);
    }
    FileSystemResource file = new FileSystemResource(new File(filePath));
    String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
    helper.addAttachment(fileName, file);

    mailSender.send(message);
}
 
Example 25
Source Project: scipio-erp   Source File: JavaMailContainer.java    License: Apache License 2.0 5 votes vote down vote up
protected void processMessage(Message message, Session session) {
    if (message instanceof MimeMessage) {
        MimeMessageWrapper wrapper = new MimeMessageWrapper(session, (MimeMessage) message);
        try {
            ServiceMcaUtil.evalRules(dispatcher, wrapper, userLogin);
        } catch (GenericServiceException e) {
            Debug.logError(e, "Problem processing message", module);
        }
    }
}
 
Example 26
Source Project: cuba   Source File: EmailerTest.java    License: Apache License 2.0 5 votes vote down vote up
private MimeBodyPart getInlineAttachment(MimeMessage msg) throws IOException, MessagingException {
    assertTrue(msg.getContent() instanceof MimeMultipart);
    MimeMultipart mimeMultipart = (MimeMultipart) msg.getContent();

    Object content2 = mimeMultipart.getBodyPart(0).getContent();
    assertTrue(content2 instanceof MimeMultipart);
    MimeMultipart textBodyPart = (MimeMultipart) content2;

    return (MimeBodyPart) textBodyPart.getBodyPart(1);
}
 
Example 27
Source Project: activiti6-boot2   Source File: EmailServiceTaskTest.java    License: Apache License 2.0 5 votes vote down vote up
@Deployment
public void testSendEmail() throws Exception {
  
  String from = "[email protected]";
  boolean male = true;
  String recipientName = "John Doe";
  String recipient = "[email protected]";
  Date now = new Date();
  String orderId = "123456";
  
  Map<String, Object> vars = new HashMap<String, Object>();
  vars.put("sender", from);
  vars.put("recipient", recipient);
  vars.put("recipientName", recipientName);
  vars.put("male", male);
  vars.put("now", now);
  vars.put("orderId", orderId);
  
  runtimeService.startProcessInstanceByKey("sendMailExample", vars);
  
  List<WiserMessage> messages = wiser.getMessages();
  assertEquals(1, messages.size());
  
  WiserMessage message = messages.get(0);
  MimeMessage mimeMessage = message.getMimeMessage();
  
  assertEquals("Your order " + orderId + " has been shipped", mimeMessage.getHeader("Subject", null));
  assertEquals(from, mimeMessage.getHeader("From", null));
  assertTrue(mimeMessage.getHeader("To", null).contains(recipient));
}
 
Example 28
@Override
protected void sendEventImpl(_SubscriptionEvent ev) {
    try {
        Optional<MimeMessage> msg = formatter.get(ev);
        if (!msg.isPresent()) {
            log.info("Formatter did not return message, ignoring notification");
            return;
        }

        send(msg.get());
        log.info("Email bridge: sending event {} to {} - success", ev.getType(), getIdentity());
    } catch (IOException | MessagingException e) {
        log.error("Could not send notification to {} about event {}", getIdentity(), ev.getType(), e);
    }
}
 
Example 29
Source Project: FlexibleLogin   Source File: ForgotPasswordCommand.java    License: MIT License 5 votes vote down vote up
private MimeMessage buildMessage(User player, String email, String newPassword, MailConfig emailConfig,
                                 Session session) throws MessagingException, UnsupportedEncodingException {
    String serverName = Sponge.getServer().getBoundAddress()
            .map(sa -> sa.getAddress().getHostAddress())
            .orElse("Minecraft Server");
    ImmutableMap<String, String> variables = ImmutableMap.of("player", player.getName(),
            "server", serverName,
            "password", newPassword);

    MimeMessage message = new MimeMessage(session);
    String senderEmail = emailConfig.getAccount();

    //sender email with an alias
    message.setFrom(new InternetAddress(senderEmail, emailConfig.getSenderName()));
    message.setRecipient(RecipientType.TO, new InternetAddress(email, player.getName()));
    message.setSubject(emailConfig.getSubject(serverName, player.getName()).toPlain());

    //current time
    message.setSentDate(Calendar.getInstance().getTime());
    String textContent = emailConfig.getText(serverName, player.getName(), newPassword).toPlain();

    //html part
    BodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(textContent, "text/html; charset=UTF-8");

    //plain text
    BodyPart textPart = new MimeBodyPart();
    textPart.setContent(textContent.replaceAll("(?s)<[^>]*>(\\s*<[^>]*>)*", " "), "text/plain; charset=UTF-8");

    Multipart alternative = new MimeMultipart("alternative");
    alternative.addBodyPart(htmlPart);
    alternative.addBodyPart(textPart);
    message.setContent(alternative);
    return message;
}
 
Example 30
Source Project: quarkus   Source File: MailerImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testAttachmentAsStreamLegacy() throws MessagingException, IOException {
    String payload = UUID.randomUUID().toString();
    byte[] bytes = payload.getBytes(StandardCharsets.UTF_8);
    Iterable<Byte> iterable = () -> new Iterator<Byte>() {
        private int index = 0;

        @Override
        public boolean hasNext() {
            return bytes.length > index;
        }

        @Override
        public Byte next() {
            return bytes[index++];
        }
    };

    legacyMailer.send(Mail.withText(TO, "Test", "testAttachmentAsStream")
            .addAttachment("my-file.txt", Flowable.fromIterable(iterable), TEXT_CONTENT_TYPE))
            .toCompletableFuture().join();
    assertThat(wiser.getMessages()).hasSize(1);
    WiserMessage actual = wiser.getMessages().get(0);
    assertThat(getContent(actual)).contains("testAttachment");
    MimeMessage msg = actual.getMimeMessage();
    assertThat(msg.getSubject()).isEqualTo("Test");
    assertThat(msg.getFrom()[0].toString()).isEqualTo(FROM);
    String value = getAttachment("my-file.txt", (MimeMultipart) actual.getMimeMessage().getContent());
    assertThat(value).isEqualTo(payload);
}