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);
}
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!");
}
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);
}
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;
}
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);
}
Aggregations