Search in sources :

Example 1 with MailListener

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.
}
Also used : MailListener(org.xwiki.mail.MailListener) MemoryMailListener(org.xwiki.mail.internal.MemoryMailListener) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) Session(javax.mail.Session) Test(org.junit.Test) ServerSetupTest(com.icegreen.greenmail.util.ServerSetupTest)

Example 2 with MailListener

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());
        }
    }
}
Also used : MailListener(org.xwiki.mail.MailListener) UpdateableMailStatusResult(org.xwiki.mail.internal.UpdateableMailStatusResult) MimeMessage(javax.mail.internet.MimeMessage) ExtendedMimeMessage(org.xwiki.mail.ExtendedMimeMessage) MailStatusResult(org.xwiki.mail.MailStatusResult) UpdateableMailStatusResult(org.xwiki.mail.internal.UpdateableMailStatusResult) MessagingException(javax.mail.MessagingException) ExecutionContextException(org.xwiki.context.ExecutionContextException)

Example 3 with MailListener

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)));
}
Also used : MailListener(org.xwiki.mail.MailListener) ExtendedMimeMessage(org.xwiki.mail.ExtendedMimeMessage) MessagingException(javax.mail.MessagingException) ExecutionContextException(org.xwiki.context.ExecutionContextException)

Example 4 with MailListener

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);
    }
}
Also used : MailListener(org.xwiki.mail.MailListener) InternetAddress(javax.mail.internet.InternetAddress) XWikiAuthenticator(org.xwiki.mail.XWikiAuthenticator) VelocityContext(org.apache.velocity.VelocityContext) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) MailSender(org.xwiki.mail.MailSender) ParseGroovyFromString(com.xpn.xwiki.internal.render.groovy.ParseGroovyFromString) IncludeServletAsString(com.xpn.xwiki.web.includeservletasstring.IncludeServletAsString) WikiManagerException(org.xwiki.wiki.manager.WikiManagerException) IOException(java.io.IOException) JobException(org.xwiki.job.JobException) ParseException(org.xwiki.rendering.parser.ParseException) QueryException(org.xwiki.query.QueryException) URIException(org.apache.commons.httpclient.URIException) InvocationTargetException(java.lang.reflect.InvocationTargetException) HibernateException(org.hibernate.HibernateException) ComponentLookupException(org.xwiki.component.manager.ComponentLookupException) NamingException(javax.naming.NamingException) FileNotFoundException(java.io.FileNotFoundException) MalformedURLException(java.net.MalformedURLException) MailSenderConfiguration(org.xwiki.mail.MailSenderConfiguration) ByteArrayInputStream(java.io.ByteArrayInputStream) MimeMessage(javax.mail.internet.MimeMessage) Session(javax.mail.Session)

Example 5 with MailListener

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);
}
Also used : MailListener(org.xwiki.mail.MailListener) MailStatusStore(org.xwiki.mail.MailStatusStore) MailContentStore(org.xwiki.mail.MailContentStore) MailStatus(org.xwiki.mail.MailStatus) Test(org.junit.Test)

Aggregations

MailListener (org.xwiki.mail.MailListener)19 Test (org.junit.Test)11 MailStatusStore (org.xwiki.mail.MailStatusStore)8 Session (javax.mail.Session)7 MimeMessage (javax.mail.internet.MimeMessage)6 MailStatus (org.xwiki.mail.MailStatus)6 MailStoreException (org.xwiki.mail.MailStoreException)6 ExtendedMimeMessage (org.xwiki.mail.ExtendedMimeMessage)4 MailContentStore (org.xwiki.mail.MailContentStore)4 MessagingException (javax.mail.MessagingException)3 InternetAddress (javax.mail.internet.InternetAddress)3 ExecutionContextException (org.xwiki.context.ExecutionContextException)3 DocumentReference (org.xwiki.model.reference.DocumentReference)3 ServerSetupTest (com.icegreen.greenmail.util.ServerSetupTest)2 HashMap (java.util.HashMap)2 MailSender (org.xwiki.mail.MailSender)2 MemoryMailListener (org.xwiki.mail.internal.MemoryMailListener)2 XWikiException (com.xpn.xwiki.XWikiException)1 ParseGroovyFromString (com.xpn.xwiki.internal.render.groovy.ParseGroovyFromString)1 IncludeServletAsString (com.xpn.xwiki.web.includeservletasstring.IncludeServletAsString)1