use of org.xwiki.mail.MailListener in project xwiki-platform by xwiki.
the class JavaIntegrationTest method sendTextMail.
@Test
public void sendTextMail() throws Exception {
// Step 1: Create a JavaMail Session
Session session = Session.getInstance(this.configuration.getAllProperties());
// Step 2: Create the Message to send
MimeMessage message = new MimeMessage(session);
message.setSubject("subject");
message.setRecipient(RecipientType.TO, new InternetAddress("john@doe.com"));
// Step 3: Add the Message Body
Multipart multipart = new MimeMultipart("mixed");
// Add text in the body
multipart.addBodyPart(this.defaultBodyPartFactory.create("some text here", Collections.<String, Object>singletonMap("mimetype", "text/plain")));
message.setContent(multipart);
// We also test using some default BCC addresses from configuration in this test
this.configuration.setBCCAddresses(Arrays.asList("bcc1@doe.com", "bcc2@doe.com"));
// Ensure we do not reuse the same message identifier for multiple similar messages in this test
MimeMessage message2 = new MimeMessage(message);
message2.saveChanges();
MimeMessage message3 = new MimeMessage(message);
message3.saveChanges();
// Step 4: Send the mail and wait for it to be sent
// Send 3 mails (3 times the same mail) to verify we can send several emails at once.
MailListener memoryMailListener = this.componentManager.getInstance(MailListener.class, "memory");
this.sender.sendAsynchronously(Arrays.asList(message, message2, message3), session, memoryMailListener);
// Note: we don't test status reporting from the listener since this is already tested in the
// ScriptingIntegrationTest test class.
// Verify that the mails have been received (wait maximum 30 seconds).
this.mail.waitForIncomingEmail(30000L, 3);
MimeMessage[] messages = this.mail.getReceivedMessages();
// Note: we're receiving 9 messages since we sent 3 with 3 recipients (2 BCC and 1 to)!
assertEquals(9, messages.length);
// Assert the email parts that are the same for all mails
assertEquals("subject", messages[0].getHeader("Subject", null));
assertEquals(1, ((MimeMultipart) messages[0].getContent()).getCount());
BodyPart textBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(0);
assertEquals("text/plain", textBodyPart.getHeader("Content-Type")[0]);
assertEquals("some text here", textBodyPart.getContent());
assertEquals("john@doe.com", messages[0].getHeader("To", null));
// Note: We cannot assert that the BCC worked since by definition BCC information are not visible in received
// messages ;) But we checked that we received 9 emails above so that's good enough.
}
use of org.xwiki.mail.MailListener in project xwiki-platform by xwiki.
the class PrepareMailRunnable method prepareMail.
/**
* Prepare the messages to send, persist them and put them on the Mail Sender Queue.
*
* @param item the queue item containing all the data for sending the mail
* @throws org.xwiki.context.ExecutionContextException when the XWiki Context fails to be set up
*/
protected void prepareMail(PrepareMailQueueItem item) throws ExecutionContextException {
Iterator<? extends MimeMessage> messageIterator = item.getMessages().iterator();
MailListener listener = item.getListener();
if (listener != null) {
listener.onPrepareBegin(item.getBatchId(), Collections.<String, Object>emptyMap());
}
// Count the total number of messages to process
long messageCounter = 0;
try {
boolean shouldStop = false;
while (!shouldStop) {
// Note that we need to have the hasNext() call after the context is ready since the implementation can
// need a valid XWiki Context.
prepareContext(item.getContext());
try {
if (messageIterator.hasNext()) {
MimeMessage mimeMessage = messageIterator.next();
prepareSingleMail(mimeMessage, item);
messageCounter++;
} else {
shouldStop = true;
}
} finally {
removeContext();
}
}
} catch (Exception e) {
if (listener != null) {
listener.onPrepareFatalError(e, Collections.<String, Object>emptyMap());
}
} finally {
if (listener != null) {
MailStatusResult result = listener.getMailStatusResult();
// so that waiting process have a chance to see an end.
if (result instanceof UpdateableMailStatusResult) {
((UpdateableMailStatusResult) result).setTotalSize(messageCounter);
}
listener.onPrepareEnd(Collections.<String, Object>emptyMap());
}
}
}
use of org.xwiki.mail.MailListener in project xwiki-platform by xwiki.
the class PrepareMailRunnable method prepareSingleMail.
private void prepareSingleMail(MimeMessage mimeMessage, PrepareMailQueueItem item) {
MailListener listener = item.getListener();
// Step 1: Try to complete message with From and Bcc from configuration if needed
completeMessage(mimeMessage);
// Ensure mimeMessage to be extended
ExtendedMimeMessage message = ExtendedMimeMessage.wrap(mimeMessage);
// Note: Message identifier is stabilized at this step by the serialization process
try {
this.mailContentStore.save(item.getBatchId(), message);
} catch (Exception e) {
// An error occurred, notify the user if a listener has been provided
if (listener != null) {
listener.onPrepareMessageError(message, e, Collections.<String, Object>emptyMap());
}
return;
}
// Step 3: Notify the user that the MimeMessage is prepared
if (listener != null) {
listener.onPrepareMessageSuccess(message, Collections.<String, Object>emptyMap());
}
// Step 4: Put the MimeMessage id on the Mail Send Queue for sending
// Extract the wiki id from the context
this.sendMailQueueManager.addToQueue(new SendMailQueueItem(message.getUniqueMessageId(), item.getSession(), listener, item.getBatchId(), extractWikiId(item)));
}
use of org.xwiki.mail.MailListener in project xwiki-platform by xwiki.
the class XWiki method sendValidationEmail.
public void sendValidationEmail(String xwikiname, String password, String email, String addfieldname, String addfieldvalue, String contentfield, XWikiContext context) throws XWikiException {
MailSenderConfiguration configuration = Utils.getComponent(MailSenderConfiguration.class);
String sender;
String content;
try {
sender = configuration.getFromAddress();
if (StringUtils.isBlank(sender)) {
String server = context.getRequest().getServerName();
if (server.matches("\\[.*\\]|(\\d{1,3}+\\.){3}+\\d{1,3}+")) {
sender = "noreply@domain.net";
} else {
sender = "noreply@" + server;
}
}
content = getXWikiPreference(contentfield, context);
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_EMAIL, XWikiException.ERROR_XWIKI_EMAIL_CANNOT_GET_VALIDATION_CONFIG, "Exception while reading the validation email config", e, null);
}
try {
VelocityContext vcontext = (VelocityContext) context.get("vcontext");
vcontext.put(addfieldname, addfieldvalue);
vcontext.put("email", email);
vcontext.put("password", password);
vcontext.put("sender", sender);
vcontext.put("xwikiname", xwikiname);
content = parseContent(content, context);
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_EMAIL, XWikiException.ERROR_XWIKI_EMAIL_CANNOT_PREPARE_VALIDATION_EMAIL, "Exception while preparing the validation email", e, null);
}
// Let's now send the message
try {
Session session = Session.getInstance(configuration.getAllProperties(), new XWikiAuthenticator(configuration));
InputStream is = new ByteArrayInputStream(content.getBytes());
MimeMessage message = new MimeMessage(session, is);
message.setFrom(new InternetAddress(sender));
message.setRecipients(Message.RecipientType.TO, email);
message.setHeader("X-MailType", "Account Validation");
MailSender mailSender = Utils.getComponent(MailSender.class);
MailListener mailListener = Utils.getComponent(MailListener.class, "database");
mailSender.sendAsynchronously(Arrays.asList(message), session, mailListener);
mailListener.getMailStatusResult().waitTillProcessed(Long.MAX_VALUE);
String errorMessage = MailStatusResultSerializer.serializeErrors(mailListener.getMailStatusResult());
if (errorMessage != null) {
throw new XWikiException(XWikiException.MODULE_XWIKI_EMAIL, XWikiException.ERROR_XWIKI_EMAIL_ERROR_SENDING_EMAIL, String.format("Error while sending the validation email. %s", errorMessage));
}
} catch (Exception e) {
throw new XWikiException(XWikiException.MODULE_XWIKI_EMAIL, XWikiException.ERROR_XWIKI_EMAIL_ERROR_SENDING_EMAIL, "Error while sending the validation email", e);
}
}
use of org.xwiki.mail.MailListener in project xwiki-platform by xwiki.
the class DatabaseMailListenerTest method onSendMessageSuccess.
@Test
public void onSendMessageSuccess() throws Exception {
MailStatusStore mailStatusStore = this.mocker.getInstance(MailStatusStore.class, "database");
MailStatus status = new MailStatus(this.batchId, this.message, MailState.PREPARE_SUCCESS);
status.setWiki("otherwiki");
when(mailStatusStore.load(this.messageId)).thenReturn(status);
MailListener listener = this.mocker.getComponentUnderTest();
listener.onPrepareBegin(batchId, Collections.<String, Object>emptyMap());
listener.onSendMessageSuccess(this.message, Collections.<String, Object>emptyMap());
verify(mailStatusStore).load(this.messageId);
verify(mailStatusStore).save(argThat(new isSameMailStatus(MailState.SEND_SUCCESS, "otherwiki")), anyMap());
MailContentStore mailContentStore = this.mocker.getInstance(MailContentStore.class, "filesystem");
verify(mailContentStore).delete(this.batchId, this.messageId);
}
Aggregations