Search in sources :

Example 96 with Multipart

use of javax.mail.Multipart in project OpenOLAT by OpenOLAT.

the class MailManagerImpl method createForwardMimeMessage.

private MimeMessage createForwardMimeMessage(Address from, Address to, String subject, String body, List<DBMailAttachment> attachments, MailerResult result) {
    try {
        MimeMessage msg = createMessage(subject, from);
        if (to != null) {
            msg.addRecipient(RecipientType.TO, to);
        }
        if (attachments != null && !attachments.isEmpty()) {
            // with attachment use multipart message
            Multipart multipart = new MimeMultipart("mixed");
            // 1) add body part
            if (StringHelper.isHtml(body)) {
                Multipart alternativePart = createMultipartAlternative(body);
                MimeBodyPart wrap = new MimeBodyPart();
                wrap.setContent(alternativePart);
                multipart.addBodyPart(wrap);
            } else {
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setText(body);
                multipart.addBodyPart(messageBodyPart);
            }
            // 2) add attachments
            for (DBMailAttachment attachment : attachments) {
                // abort if attachment does not exist
                if (attachment == null || attachment.getSize() <= 0) {
                    result.setReturnCode(MailerResult.ATTACHMENT_INVALID);
                    log.error("Tried to send mail wit attachment that does not exist::" + (attachment == null ? null : attachment.getName()), null);
                    return msg;
                }
                BodyPart messageBodyPart = new MimeBodyPart();
                VFSLeaf data = getAttachmentDatas(attachment);
                DataSource source = new VFSDataSource(attachment.getName(), attachment.getMimetype(), data);
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(attachment.getName());
                multipart.addBodyPart(messageBodyPart);
            }
            // Put parts in message
            msg.setContent(multipart);
        } else {
            // without attachment everything is easy, just set as text
            if (StringHelper.isHtml(body)) {
                msg.setContent(createMultipartAlternative(body));
            } else {
                msg.setText(body, "utf-8");
            }
        }
        msg.setSentDate(new Date());
        msg.saveChanges();
        return msg;
    } catch (MessagingException | UnsupportedEncodingException e) {
        log.error("", e);
        return null;
    }
}
Also used : BodyPart(javax.mail.BodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart) VFSLeaf(org.olat.core.util.vfs.VFSLeaf) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) MessagingException(javax.mail.MessagingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DataHandler(javax.activation.DataHandler) Date(java.util.Date) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource) DBMailAttachment(org.olat.core.util.mail.model.DBMailAttachment) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 97 with Multipart

use of javax.mail.Multipart in project OpenOLAT by OpenOLAT.

the class MailManagerImpl method createMultipartAlternative.

private Multipart createMultipartAlternative(String text) throws MessagingException {
    String pureText = new NekoHTMLFilter().filter(text, true);
    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setText(pureText, "utf-8");
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setText(text, "utf-8", "html");
    Multipart multipart = new MimeMultipart("alternative");
    multipart.addBodyPart(textPart);
    multipart.addBodyPart(htmlPart);
    return multipart;
}
Also used : NekoHTMLFilter(org.olat.core.util.filter.impl.NekoHTMLFilter) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 98 with Multipart

use of javax.mail.Multipart in project xwiki-platform by xwiki.

the class ScriptMimeMessage method addPart.

/**
 * Add some content to the mail to be sent. Can be called several times to add different content type to the mail.
 *
 * @return the Mime Body Part object that was added. Returning it allows script to make modifications to that body
 *         part after it's been set (get/set some headers, etc)
 * @param mimeType the mime type of the content parameter
 * @param content the content to include in the mail. The type depends on the mimetype. For example for a mime
 *        type of {@code text/plain} or {@code text/html}, the content should be a String, for a mime type of
 *        {@code xwiki/template} it should be a {@link org.xwiki.model.reference.DocumentReference}, etc.
 *        Also accepts a {@link BodyPart} object, in which case, the mime type and parameters are not used.
 * @param parameters the list of extra parameters. This is used for example to pass alternate content for the mail
 *        using the {@code alternate} key in the HTML Mime Body Part Factory. Mail headers can also be passed using
 *        the {@code headers} key with a {@code Map&lt;String, String&gt;} value containing header keys
 *        and values.
 */
public BodyPart addPart(String mimeType, Object content, Map<String, Object> parameters) {
    BodyPart bodyPart;
    try {
        if (!(content instanceof BodyPart)) {
            MimeBodyPartFactory factory = getBodyPartFactory(mimeType, content.getClass());
            // Pass the mime type in the parameters so that generic Mime Body Part factories can use it.
            // Note that if the user has already passed a "mimetype" parameter then we don't override it!
            Map<String, Object> enhancedParameters = new HashMap<>();
            enhancedParameters.put("mimetype", mimeType);
            enhancedParameters.putAll(parameters);
            bodyPart = factory.create(content, enhancedParameters);
        } else {
            bodyPart = (BodyPart) content;
        }
        Multipart multipart = getMultipart();
        multipart.addBodyPart(bodyPart);
    } catch (Exception e) {
        // Save the exception for reporting through the script services's getError() API
        setError(e);
        bodyPart = null;
    }
    return bodyPart;
}
Also used : BodyPart(javax.mail.BodyPart) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) HashMap(java.util.HashMap) MimeBodyPartFactory(org.xwiki.mail.MimeBodyPartFactory) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) ComponentLookupException(org.xwiki.component.manager.ComponentLookupException)

Example 99 with Multipart

use of javax.mail.Multipart in project xwiki-platform by xwiki.

the class ScriptMimeMessage method getMultipart.

private Multipart getMultipart() throws MessagingException, IOException {
    Multipart multipart;
    if (isEmpty()) {
        multipart = new MimeMultipart("mixed");
        setContent(multipart);
    } else {
        Object contentObject = getContent();
        if (contentObject instanceof Multipart) {
            multipart = (Multipart) contentObject;
        } else {
            throw new MessagingException(String.format("Unknown mail content type [%s]: [%s]", contentObject.getClass().getName(), contentObject));
        }
    }
    return multipart;
}
Also used : MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) MessagingException(javax.mail.MessagingException)

Example 100 with Multipart

use of javax.mail.Multipart in project xwiki-platform by xwiki.

the class AuthenticatingIntegrationTest method sendTextMail.

@Test
public void sendTextMail() throws Exception {
    // Set the EC
    Execution execution = this.componentManager.getInstance(Execution.class);
    ExecutionContext executionContext = new ExecutionContext();
    XWikiContext xContext = new XWikiContext();
    xContext.setWikiId("wiki");
    executionContext.setProperty(XWikiContext.EXECUTIONCONTEXT_KEY, xContext);
    when(execution.getContext()).thenReturn(executionContext);
    Copier<ExecutionContext> executionContextCloner = this.componentManager.getInstance(new DefaultParameterizedType(null, Copier.class, ExecutionContext.class));
    // Just return the same execution context
    when(executionContextCloner.copy(executionContext)).thenReturn(executionContext);
    // Step 1: Create a JavaMail Session
    Properties properties = this.configuration.getAllProperties();
    assertEquals("true", properties.getProperty(DefaultMailSenderConfiguration.JAVAMAIL_SMTP_AUTH));
    Session session = Session.getInstance(properties, new XWikiAuthenticator(this.configuration));
    // 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);
    // Step 4: Send the mail
    this.sender.sendAsynchronously(Arrays.asList(message), session, null);
    // Verify that the mail has been received (wait maximum 30 seconds).
    this.mail.waitForIncomingEmail(30000L, 1);
    MimeMessage[] messages = this.mail.getReceivedMessages();
    assertEquals(1, messages.length);
    assertEquals("subject", messages[0].getHeader("Subject", null));
    assertEquals("john@doe.com", messages[0].getHeader("To", 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());
}
Also used : BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) XWikiAuthenticator(org.xwiki.mail.XWikiAuthenticator) XWikiContext(com.xpn.xwiki.XWikiContext) Properties(java.util.Properties) Execution(org.xwiki.context.Execution) ExecutionContext(org.xwiki.context.ExecutionContext) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) Copier(org.xwiki.mail.internal.thread.context.Copier) DefaultParameterizedType(org.xwiki.component.util.DefaultParameterizedType) Session(javax.mail.Session) Test(org.junit.Test) ServerSetupTest(com.icegreen.greenmail.util.ServerSetupTest)

Aggregations

Multipart (javax.mail.Multipart)148 MimeMultipart (javax.mail.internet.MimeMultipart)107 MimeBodyPart (javax.mail.internet.MimeBodyPart)92 MimeMessage (javax.mail.internet.MimeMessage)82 BodyPart (javax.mail.BodyPart)62 InternetAddress (javax.mail.internet.InternetAddress)61 MessagingException (javax.mail.MessagingException)58 Session (javax.mail.Session)44 DataHandler (javax.activation.DataHandler)42 IOException (java.io.IOException)37 Properties (java.util.Properties)37 Date (java.util.Date)30 Message (javax.mail.Message)30 FileDataSource (javax.activation.FileDataSource)27 DataSource (javax.activation.DataSource)24 InputStream (java.io.InputStream)23 File (java.io.File)21 Part (javax.mail.Part)21 Test (org.junit.Test)16 UnsupportedEncodingException (java.io.UnsupportedEncodingException)11