Search in sources :

Example 1 with Email

use of org.simplejavamail.email.Email in project simple-java-mail by bbottema.

the class MailTestDemoApp method main.

public static void main(final String[] args) throws Exception {
    final EmailPopulatingBuilder emailPopulatingBuilderNormal = EmailBuilder.startingBlank();
    emailPopulatingBuilderNormal.from("lollypop", "lol.pop@somemail.com");
    // don't forget to add your own address here ->
    emailPopulatingBuilderNormal.to("C.Cane", YOUR_GMAIL_ADDRESS);
    emailPopulatingBuilderNormal.withPlainText("We should meet up!");
    emailPopulatingBuilderNormal.withHTMLText("<b>We should meet up!</b><img src='cid:thumbsup'>");
    emailPopulatingBuilderNormal.withSubject("hey");
    // add two text files in different ways and a black thumbs up embedded image ->
    emailPopulatingBuilderNormal.withAttachment("dresscode.txt", new ByteArrayDataSource("Black Tie Optional", "text/plain"));
    emailPopulatingBuilderNormal.withAttachment("location.txt", "On the moon!".getBytes(Charset.defaultCharset()), "text/plain");
    String base64String = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAABeElEQVRYw2NgoAAYGxu3GxkZ7TY1NZVloDcAWq4MxH+B+D8Qv3FwcOCgtwM6oJaDMTAUXOhmuYqKCjvQ0pdoDrCnmwNMTEwakC0H4u8GBgYC9Ap6DSD+iewAoIPm0ctyLqBlp9F8/x+YE4zpYT8T0LL16JYD8U26+B7oyz4sloPwenpYno3DchCeROsUbwa05A8eB3wB4kqgIxOAuArIng7EW4H4EhC/B+JXQLwDaI4ryZaDSjeg5mt4LCcFXyIn1fdSyXJQVt1OtMWGhoai0OD8T0W8GohZifE1PxD/o7LlsPLiFNAKRrwOABWptLAcqc6QGDAHQEOAYaAc8BNotsJAOgAUAosG1AFA/AtUoY3YEFhKMAvS2AE7iC1+WaG1H6gY3gzE36hUFJ8mqzbU1dUVBBqQBzTgIDQRkWo5qCZdpaenJ0Zx1aytrc0DDB0foIG1oAYKqC0IZK8D4n1AfA6IzwPxXpCFoGoZVEUDaRGGUTAKRgEeAAA2eGJC+ETCiAAAAABJRU5ErkJggg==";
    emailPopulatingBuilderNormal.withEmbeddedImage("thumbsup", parseBase64Binary(base64String), "image/png");
    // let's try producing and then consuming a MimeMessage ->
    Email emailNormal = emailPopulatingBuilderNormal.buildEmail();
    final MimeMessage mimeMessage = EmailConverter.emailToMimeMessage(emailNormal);
    final Email emailFromMimeMessage = EmailConverter.mimeMessageToEmail(mimeMessage);
    // note: the following statements will produce 6 new emails!
    sendMail(emailNormal);
    // should produce the exact same result as emailPopulatingBuilderNormal!
    sendMail(emailFromMimeMessage);
}
Also used : Email(org.simplejavamail.email.Email) MimeMessage(javax.mail.internet.MimeMessage) EmailPopulatingBuilder(org.simplejavamail.email.EmailPopulatingBuilder) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource)

Example 2 with Email

use of org.simplejavamail.email.Email in project simple-java-mail by bbottema.

the class MailerLiveTest method createMailSession_OutlookMessageTest.

@Test
public void createMailSession_OutlookMessageTest() throws IOException, MessagingException {
    Email email = assertSendingEmail(readOutlookMessage("test-messages/HTML mail with replyto and attachment and embedded image.msg"));
    // Google SMTP overrode this, Outlook recognized it as: Benny Bottema <b.bottema@gmail.com>; on behalf of; lollypop <b.bottema@projectnibble.org>
    EmailAssert.assertThat(email).hasFromRecipient(new Recipient("lollypop", "b.bottema@projectnibble.org", null));
    EmailAssert.assertThat(email).hasSubject("hey");
    // Outlook overrode this when saving the .email to match the mail account
    EmailAssert.assertThat(email).hasRecipients(new Recipient("Bottema, Benny", "benny.bottema@aegon.nl", TO));
    EmailAssert.assertThat(email).hasReplyToRecipient(new Recipient("lollypop-replyto", "lo.pop.replyto@somemail.com", null));
    assertThat(normalizeText(email.getPlainText())).isEqualTo("We should meet up!\n");
    // Outlook overrode this value too OR converted the original HTML to RTF, from which OutlookMessageParser derived this HTML
    assertThat(normalizeText(email.getHTMLText())).contains("<html><body style=\"font-family:'Courier',monospace;font-size:10pt;\">   <br/>      <br/> <b>   We should meet up! <br/>  </b>   <br/>  <img src=\"cid:thumbsup\"> <br/> ");
    // the RTF was probably created by Outlook based on the HTML when the message was saved
    assertThat(email.getAttachments()).hasSize(2);
    assertThat(email.getEmbeddedImages()).hasSize(1);
    AttachmentResource attachment1 = email.getAttachments().get(0);
    AttachmentResource attachment2 = email.getAttachments().get(1);
    AttachmentResource embeddedImg = email.getEmbeddedImages().get(0);
    // Outlook overrode dresscode.txt, presumably because it was more than 8 character long??
    assertAttachmentMetadata(attachment1, "text/plain", "dresscode.txt");
    assertAttachmentMetadata(attachment2, "text/plain", "location.txt");
    assertAttachmentMetadata(embeddedImg, "image/png", "thumbsup");
    assertThat(normalizeText(attachment1.readAllData())).isEqualTo("Black Tie Optional");
    assertThat(normalizeText(attachment2.readAllData())).isEqualTo("On the moon!");
}
Also used : AttachmentResource(org.simplejavamail.email.AttachmentResource) EmailConverter.mimeMessageToEmail(org.simplejavamail.converter.EmailConverter.mimeMessageToEmail) Email(org.simplejavamail.email.Email) Recipient(org.simplejavamail.email.Recipient) Test(org.junit.Test)

Example 3 with Email

use of org.simplejavamail.email.Email in project simple-java-mail by bbottema.

the class MailerTest method testParser.

@Test
public void testParser() throws Exception {
    final EmailPopulatingBuilder emailPopulatingBuilderNormal = EmailHelper.createDummyEmailBuilder(true, false, false);
    // let's try producing and then consuming a MimeMessage ->
    // (bounce recipient is not part of the Mimemessage, but the Envelope and is configured on the Session, so just ignore this)
    emailPopulatingBuilderNormal.clearBounceTo();
    Email emailNormal = emailPopulatingBuilderNormal.buildEmail();
    final MimeMessage mimeMessage = EmailConverter.emailToMimeMessage(emailNormal);
    final Email emailFromMimeMessage = EmailConverter.mimeMessageToEmail(mimeMessage);
    assertThat(emailFromMimeMessage).isEqualTo(emailNormal);
}
Also used : Email(org.simplejavamail.email.Email) MimeMessage(javax.mail.internet.MimeMessage) EmailPopulatingBuilder(org.simplejavamail.email.EmailPopulatingBuilder) Test(org.junit.Test)

Example 4 with Email

use of org.simplejavamail.email.Email in project openremote by openremote.

the class EmailNotificationHandler method getTargets.

@Override
public List<Notification.Target> getTargets(Notification.Source source, String sourceId, List<Notification.Target> targets, AbstractNotificationMessage message) {
    List<Notification.Target> mappedTargets = new ArrayList<>();
    if (targets != null) {
        targets.forEach(target -> {
            Notification.TargetType targetType = target.getType();
            String targetId = target.getId();
            switch(targetType) {
                case TENANT:
                case USER:
                    // Find all users in this tenant or by id
                    User[] users = targetType == Notification.TargetType.TENANT ? managerIdentityService.getIdentityProvider().queryUsers(new UserQuery().tenant(new TenantPredicate(targetId))) : managerIdentityService.getIdentityProvider().queryUsers(new UserQuery().ids(targetId));
                    if (users.length == 0) {
                        if (targetType == Notification.TargetType.USER) {
                            LOG.info("User not found: " + targetId);
                        } else {
                            LOG.info("No users found in target realm: " + targetId);
                        }
                        return;
                    }
                    mappedTargets.addAll(Arrays.stream(users).filter(user -> !Boolean.parseBoolean(user.getAttributes().getOrDefault(KEYCLOAK_USER_ATTRIBUTE_EMAIL_NOTIFICATIONS_DISABLED, Collections.singletonList("false")).get(0))).map(user -> {
                        Notification.Target userAssetTarget = new Notification.Target(Notification.TargetType.USER, user.getId());
                        userAssetTarget.setData(new EmailNotificationMessage.Recipient(user.getFullName(), user.getEmail()));
                        return userAssetTarget;
                    }).collect(Collectors.toList()));
                    break;
                case CUSTOM:
                    // Nothing to do here
                    mappedTargets.add(new Notification.Target(targetType, targetId));
                    break;
                case ASSET:
                    // Find descendant assets with email attribute
                    List<Asset<?>> assets = assetStorageService.findAll(new AssetQuery().select(new AssetQuery.Select().attributes(Asset.EMAIL.getName())).paths(new PathPredicate(targetId)).attributes(new AttributePredicate(new StringPredicate(Asset.EMAIL.getName()), new ValueEmptyPredicate().negate(true))));
                    if (assets.isEmpty()) {
                        LOG.fine("No assets with email attribute descendants of target asset");
                        return;
                    }
                    mappedTargets.addAll(assets.stream().map(asset -> {
                        Notification.Target assetTarget = new Notification.Target(Notification.TargetType.ASSET, asset.getId());
                        assetTarget.setData(new EmailNotificationMessage.Recipient(asset.getName(), asset.getEmail().orElse(null)));
                        return assetTarget;
                    }).collect(Collectors.toList()));
                    break;
            }
        });
    }
    EmailNotificationMessage email = (EmailNotificationMessage) message;
    // Map to/cc/bcc into a custom target for traceability in sent notifications
    List<String> addresses = new ArrayList<>();
    if (email.getTo() != null) {
        addresses.addAll(email.getTo().stream().map(EmailNotificationMessage.Recipient::getAddress).map(address -> "to:" + address).collect(Collectors.toList()));
        email.setTo((List<EmailNotificationMessage.Recipient>) null);
    }
    if (email.getCc() != null) {
        addresses.addAll(email.getCc().stream().map(EmailNotificationMessage.Recipient::getAddress).map(address -> "cc:" + address).collect(Collectors.toList()));
        email.setCc((List<EmailNotificationMessage.Recipient>) null);
    }
    if (email.getBcc() != null) {
        addresses.addAll(email.getBcc().stream().map(EmailNotificationMessage.Recipient::getAddress).map(address -> "bcc:" + address).collect(Collectors.toList()));
        email.setBcc((List<EmailNotificationMessage.Recipient>) null);
    }
    if (!addresses.isEmpty()) {
        mappedTargets.add(new Notification.Target(Notification.TargetType.CUSTOM, String.join(";", addresses)));
    }
    return mappedTargets;
}
Also used : AssetStorageService(org.openremote.manager.asset.AssetStorageService) Arrays(java.util.Arrays) AbstractNotificationMessage(org.openremote.model.notification.AbstractNotificationMessage) KEYCLOAK_USER_ATTRIBUTE_EMAIL_NOTIFICATIONS_DISABLED(org.openremote.manager.security.ManagerKeycloakIdentityProvider.KEYCLOAK_USER_ATTRIBUTE_EMAIL_NOTIFICATIONS_DISABLED) EmailPopulatingBuilder(org.simplejavamail.email.EmailPopulatingBuilder) TransportStrategy(org.simplejavamail.mailer.config.TransportStrategy) MapAccess.getInteger(org.openremote.container.util.MapAccess.getInteger) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) Notification(org.openremote.model.notification.Notification) UserQuery(org.openremote.model.query.UserQuery) Recipient(org.simplejavamail.email.Recipient) org.openremote.model.query.filter(org.openremote.model.query.filter) EmailNotificationMessage(org.openremote.model.notification.EmailNotificationMessage) MapAccess.getBoolean(org.openremote.container.util.MapAccess.getBoolean) TextUtil(org.openremote.model.util.TextUtil) NotificationSendResult(org.openremote.model.notification.NotificationSendResult) User(org.openremote.model.security.User) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) Asset(org.openremote.model.asset.Asset) MailerBuilder(org.simplejavamail.mailer.MailerBuilder) AssetQuery(org.openremote.model.query.AssetQuery) Mailer(org.simplejavamail.mailer.Mailer) ContainerService(org.openremote.model.ContainerService) Logger(java.util.logging.Logger) Constants(org.openremote.model.Constants) Collectors(java.util.stream.Collectors) Container(org.openremote.model.Container) List(java.util.List) EmailBuilder(org.simplejavamail.email.EmailBuilder) Email(org.simplejavamail.email.Email) Collections(java.util.Collections) EmailNotificationMessage(org.openremote.model.notification.EmailNotificationMessage) User(org.openremote.model.security.User) AssetQuery(org.openremote.model.query.AssetQuery) ArrayList(java.util.ArrayList) Recipient(org.simplejavamail.email.Recipient) Notification(org.openremote.model.notification.Notification) UserQuery(org.openremote.model.query.UserQuery) Asset(org.openremote.model.asset.Asset)

Example 5 with Email

use of org.simplejavamail.email.Email in project xwiki-platform by xwiki.

the class NotificationsIT method testNotificationsEmails.

@Test
public void testNotificationsEmails() throws Exception {
    getUtil().login(SECOND_USER_NAME, SECOND_USER_PASSWORD);
    NotificationsUserProfilePage p;
    p = NotificationsUserProfilePage.gotoPage(SECOND_USER_NAME);
    p.getApplication(SYSTEM).setCollapsed(false);
    p.setEventTypeState(SYSTEM, CREATE, EMAIL_FORMAT, BootstrapSwitch.State.ON);
    getUtil().login(FIRST_USER_NAME, FIRST_USER_PASSWORD);
    DocumentReference page1 = new DocumentReference("xwiki", NOTIFICATIONS_EMAIL_TEST, "Page1");
    DocumentReference page2 = new DocumentReference("xwiki", NOTIFICATIONS_EMAIL_TEST, "Page2");
    // Yes we wait on a timer, but it is to be sure the following events will be stored AFTER the settings have been
    // changed.
    Thread.sleep(1000);
    getUtil().createPage(NOTIFICATIONS_EMAIL_TEST, "Page1", "Content 1", "Title 1");
    getUtil().createPage(NOTIFICATIONS_EMAIL_TEST, "Page2", "Content 2", "Title 2");
    // Trigger the notification email job
    getUtil().login(SUPERADMIN_USER_NAME, SUPERADMIN_PASSWORD);
    SchedulerHomePage schedulerHomePage = SchedulerHomePage.gotoPage();
    schedulerHomePage.clickJobActionTrigger("Notifications daily email");
    this.mail.waitForIncomingEmail(1);
    assertEquals(1, this.mail.getReceivedMessages().length);
    MimeMessage message = this.mail.getReceivedMessages()[0];
    // Convert to org.simplejavamail.email because it is more simple to read
    Email email = EmailConverter.mimeMessageToEmail(message);
    assertTrue(email.getSubject().endsWith("event(s) on the wiki"));
    assertEquals("test@xwiki.org", email.getFromRecipient().getAddress());
    assertNotNull(email.getText());
    assertNotNull(email.getTextHTML());
    assertNotNull(email.getAttachments());
    assertFalse(email.getAttachments().isEmpty());
    // Events inside an email comes in random order, so we just verify that all the expected content is there
    String plainTextContent = prepareMail(email.getText());
    String expectedContent;
    expectedContent = prepareMail(IOUtils.toString(getClass().getResourceAsStream("/expectedMail1.txt")));
    assertTrue(String.format("Email is supposed to contain: [\n%s\n], but all we have is [\n%s\n].", expectedContent, plainTextContent), plainTextContent.contains(expectedContent));
    expectedContent = prepareMail(IOUtils.toString(getClass().getResourceAsStream("/expectedMail2.txt")));
    assertTrue(String.format("Email is supposed to contain: [\n%s\n], but all we we have is [\n%s\n].", expectedContent, plainTextContent), plainTextContent.contains(expectedContent));
    getUtil().rest().delete(page1);
    getUtil().rest().delete(page2);
}
Also used : NotificationsUserProfilePage(org.xwiki.platform.notifications.test.po.NotificationsUserProfilePage) SchedulerHomePage(org.xwiki.scheduler.test.po.SchedulerHomePage) Email(org.simplejavamail.email.Email) MimeMessage(javax.mail.internet.MimeMessage) DocumentReference(org.xwiki.model.reference.DocumentReference) AbstractTest(org.xwiki.test.ui.AbstractTest) Test(org.junit.Test) ServerSetupTest(com.icegreen.greenmail.util.ServerSetupTest)

Aggregations

Email (org.simplejavamail.email.Email)10 Test (org.junit.Test)7 MimeMessage (javax.mail.internet.MimeMessage)6 EmailPopulatingBuilder (org.simplejavamail.email.EmailPopulatingBuilder)5 EmailConverter.mimeMessageToEmail (org.simplejavamail.converter.EmailConverter.mimeMessageToEmail)4 Recipient (org.simplejavamail.email.Recipient)4 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 ServerSetupTest (com.icegreen.greenmail.util.ServerSetupTest)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 List (java.util.List)1 Level (java.util.logging.Level)1 Logger (java.util.logging.Logger)1 Collectors (java.util.stream.Collectors)1 ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)1 MapAccess.getBoolean (org.openremote.container.util.MapAccess.getBoolean)1 MapAccess.getInteger (org.openremote.container.util.MapAccess.getInteger)1 AssetStorageService (org.openremote.manager.asset.AssetStorageService)1 ManagerIdentityService (org.openremote.manager.security.ManagerIdentityService)1