Example usage for javax.mail.internet MimeBodyPart setText

List of usage examples for javax.mail.internet MimeBodyPart setText

Introduction

In this page you can find the example usage for javax.mail.internet MimeBodyPart setText.

Prototype

@Override
public void setText(String text) throws MessagingException 

Source Link

Document

Convenience method that sets the given String as this part's content, with a MIME type of "text/plain".

Usage

From source file:org.apache.james.transport.mailets.StripAttachmentTest.java

@Test
public void testSimpleAttachment2() throws MessagingException, IOException {
    Mailet mailet = new StripAttachment();

    FakeMailetConfig mci = new FakeMailetConfig("Test", FakeMailContext.defaultContext());
    mci.setProperty("directory", "./");
    mci.setProperty("remove", "all");
    mci.setProperty("notpattern", "^(winmail\\.dat$)");
    mailet.init(mci);/*from  ww  w .j  a  va2 s  .  co m*/

    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));

    MimeMultipart mm = new MimeMultipart();
    MimeBodyPart mp = new MimeBodyPart();
    mp.setText("simple text");
    mm.addBodyPart(mp);
    String body = "\u0023\u00A4\u00E3\u00E0\u00E9";
    MimeBodyPart mp2 = new MimeBodyPart(
            new ByteArrayInputStream(("Content-Transfer-Encoding: 8bit\r\n\r\n" + body).getBytes("UTF-8")));
    mp2.setDisposition("attachment");
    mp2.setFileName("temp.tmp");
    mm.addBodyPart(mp2);
    String body2 = "\u0014\u00A3\u00E1\u00E2\u00E4";
    MimeBodyPart mp3 = new MimeBodyPart(
            new ByteArrayInputStream(("Content-Transfer-Encoding: 8bit\r\n\r\n" + body2).getBytes("UTF-8")));
    mp3.setDisposition("attachment");
    mp3.setFileName("winmail.dat");
    mm.addBodyPart(mp3);
    message.setSubject("test");
    message.setContent(mm);
    message.saveChanges();

    Mail mail = FakeMail.builder().mimeMessage(message).build();

    mailet.service(mail);

    ByteArrayOutputStream rawMessage = new ByteArrayOutputStream();
    mail.getMessage().writeTo(rawMessage, new String[] { "Bcc", "Content-Length", "Message-ID" });
    // String res = rawMessage.toString();

    @SuppressWarnings("unchecked")
    Collection<String> c = (Collection<String>) mail
            .getAttribute(StripAttachment.SAVED_ATTACHMENTS_ATTRIBUTE_KEY);
    Assert.assertNotNull(c);

    Assert.assertEquals(1, c.size());

    String name = c.iterator().next();

    File f = new File("./" + name);
    try {
        InputStream is = new FileInputStream(f);
        String savedFile = toString(is);
        is.close();
        Assert.assertEquals(body, savedFile);
    } finally {
        FileUtils.deleteQuietly(f);
    }
}

From source file:org.apache.james.transport.mailets.StripAttachmentTest.java

@Test
public void testSimpleAttachment3() throws MessagingException, IOException {
    Mailet mailet = initMailet();//w  w  w.  jav a2s. c  o  m

    // System.setProperty("mail.mime.decodefilename", "true");

    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));

    MimeMultipart mm = new MimeMultipart();
    MimeBodyPart mp = new MimeBodyPart();
    mp.setText("simple text");
    mm.addBodyPart(mp);
    String body = "\u0023\u00A4\u00E3\u00E0\u00E9";
    MimeBodyPart mp2 = new MimeBodyPart(
            new ByteArrayInputStream(("Content-Transfer-Encoding: 8bit\r\n\r\n" + body).getBytes("UTF-8")));
    mp2.setDisposition("attachment");
    mp2.setFileName("=?iso-8859-15?Q?=E9_++++Pubblicit=E0_=E9_vietata____Milano9052.tmp?=");
    mm.addBodyPart(mp2);
    String body2 = "\u0014\u00A3\u00E1\u00E2\u00E4";
    MimeBodyPart mp3 = new MimeBodyPart(
            new ByteArrayInputStream(("Content-Transfer-Encoding: 8bit\r\n\r\n" + body2).getBytes("UTF-8")));
    mp3.setDisposition("attachment");
    mp3.setFileName("temp.zip");
    mm.addBodyPart(mp3);
    message.setSubject("test");
    message.setContent(mm);
    message.saveChanges();

    // message.writeTo(System.out);
    // System.out.println("--------------------------\n\n\n");

    Mail mail = FakeMail.builder().mimeMessage(message).build();

    mailet.service(mail);

    ByteArrayOutputStream rawMessage = new ByteArrayOutputStream();
    mail.getMessage().writeTo(rawMessage, new String[] { "Bcc", "Content-Length", "Message-ID" });
    // String res = rawMessage.toString();

    @SuppressWarnings("unchecked")
    Collection<String> c = (Collection<String>) mail
            .getAttribute(StripAttachment.SAVED_ATTACHMENTS_ATTRIBUTE_KEY);
    Assert.assertNotNull(c);

    Assert.assertEquals(1, c.size());

    String name = c.iterator().next();
    // System.out.println("--------------------------\n\n\n");
    // System.out.println(name);

    Assert.assertTrue(name.startsWith("e_Pubblicita_e_vietata_Milano9052"));

    File f = new File("./" + name);
    try {
        InputStream is = new FileInputStream(f);
        String savedFile = toString(is);
        is.close();
        Assert.assertEquals(body, savedFile);
    } finally {
        FileUtils.deleteQuietly(f);
    }
}

From source file:org.apache.james.transport.mailets.StripAttachmentTest.java

@Test
public void testToAndFromAttributes() throws MessagingException, IOException {
    Mailet strip = new StripAttachment();
    FakeMailetConfig mci = new FakeMailetConfig("Test", FakeMailContext.defaultContext());
    mci.setProperty("attribute", "my.attribute");
    mci.setProperty("remove", "all");
    mci.setProperty("notpattern", ".*\\.tmp.*");
    strip.init(mci);/*from   w w w  . ja v  a 2 s.c  o m*/

    Mailet recover = new RecoverAttachment();
    FakeMailetConfig mci2 = new FakeMailetConfig("Test", FakeMailContext.defaultContext());
    mci2.setProperty("attribute", "my.attribute");
    recover.init(mci2);

    Mailet onlyText = new OnlyText();
    onlyText.init(new FakeMailetConfig("Test", FakeMailContext.defaultContext()));

    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));

    MimeMultipart mm = new MimeMultipart();
    MimeBodyPart mp = new MimeBodyPart();
    mp.setText("simple text");
    mm.addBodyPart(mp);
    String body = "\u0023\u00A4\u00E3\u00E0\u00E9";
    MimeBodyPart mp2 = new MimeBodyPart(new ByteArrayInputStream(
            ("Content-Transfer-Encoding: 8bit\r\nContent-Type: application/octet-stream; charset=utf-8\r\n\r\n"
                    + body).getBytes("UTF-8")));
    mp2.setDisposition("attachment");
    mp2.setFileName("=?iso-8859-15?Q?=E9_++++Pubblicit=E0_=E9_vietata____Milano9052.tmp?=");
    mm.addBodyPart(mp2);
    String body2 = "\u0014\u00A3\u00E1\u00E2\u00E4";
    MimeBodyPart mp3 = new MimeBodyPart(new ByteArrayInputStream(
            ("Content-Transfer-Encoding: 8bit\r\nContent-Type: application/octet-stream; charset=utf-8\r\n\r\n"
                    + body2).getBytes("UTF-8")));
    mp3.setDisposition("attachment");
    mp3.setFileName("temp.zip");
    mm.addBodyPart(mp3);
    message.setSubject("test");
    message.setContent(mm);
    message.saveChanges();
    Mail mail = FakeMail.builder().mimeMessage(message).build();

    Assert.assertTrue(mail.getMessage().getContent() instanceof MimeMultipart);
    Assert.assertEquals(3, ((MimeMultipart) mail.getMessage().getContent()).getCount());

    strip.service(mail);

    Assert.assertTrue(mail.getMessage().getContent() instanceof MimeMultipart);
    Assert.assertEquals(1, ((MimeMultipart) mail.getMessage().getContent()).getCount());

    onlyText.service(mail);

    Assert.assertFalse(mail.getMessage().getContent() instanceof MimeMultipart);

    Assert.assertEquals("simple text", mail.getMessage().getContent());

    // prova per caricare il mime message da input stream che altrimenti
    // javamail si comporta differentemente.
    String mimeSource = "Message-ID: <26194423.21197328775426.JavaMail.bago@bagovista>\r\nSubject: test\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=us-ascii\r\nContent-Transfer-Encoding: 7bit\r\n\r\nsimple text";

    MimeMessage mmNew = new MimeMessage(Session.getDefaultInstance(new Properties()),
            new ByteArrayInputStream(mimeSource.getBytes("UTF-8")));

    mmNew.writeTo(System.out);
    mail.setMessage(mmNew);

    recover.service(mail);

    Assert.assertTrue(mail.getMessage().getContent() instanceof MimeMultipart);
    Assert.assertEquals(2, ((MimeMultipart) mail.getMessage().getContent()).getCount());

    Object actual = ((MimeMultipart) mail.getMessage().getContent()).getBodyPart(1).getContent();
    if (actual instanceof ByteArrayInputStream) {
        Assert.assertEquals(body2, toString((ByteArrayInputStream) actual));
    } else {
        Assert.assertEquals(body2, actual);
    }

}

From source file:org.apache.jsieve.mailet.SieveMailboxMailet.java

/**
 * Deliver the original mail as an attachment with the main part being an error report.
 *
 * @param recipient/*  w  ww. j a  v  a2 s .com*/
 * @param aMail
 * @param ex
 * @throws MessagingException
 * @throws IOException 
 */
protected void handleFailure(MailAddress recipient, Mail aMail, Exception ex)
        throws MessagingException, IOException {
    String user = getUsername(recipient);

    MimeMessage originalMessage = aMail.getMessage();
    MimeMessage message = new MimeMessage(originalMessage);
    MimeMultipart multipart = new MimeMultipart();

    MimeBodyPart noticePart = new MimeBodyPart();
    noticePart.setText(new StringBuilder().append(
            "An error was encountered while processing this mail with the active sieve script for user \"")
            .append(user).append("\". The error encountered was:\r\n").append(ex.getLocalizedMessage())
            .append("\r\n").toString());
    multipart.addBodyPart(noticePart);

    MimeBodyPart originalPart = new MimeBodyPart();
    originalPart.setContent(originalMessage, "message/rfc822");
    if ((originalMessage.getSubject() != null) && (!originalMessage.getSubject().trim().isEmpty())) {
        originalPart.setFileName(originalMessage.getSubject().trim());
    } else {
        originalPart.setFileName("No Subject");
    }
    originalPart.setDisposition(MimeBodyPart.INLINE);
    multipart.addBodyPart(originalPart);

    message.setContent(multipart);
    message.setSubject("[SIEVE ERROR] " + originalMessage.getSubject());
    message.setHeader("X-Priority", "1");
    message.saveChanges();

    storeMessageInbox(user, message);
}

From source file:org.apache.lens.server.query.QueryEndNotifier.java

/** Send mail.
 *
 * @param host                      the host
 * @param port                      the port
 * @param email                     the email
 * @param mailSmtpTimeout           the mail smtp timeout
 * @param mailSmtpConnectionTimeout the mail smtp connection timeout */
public static void sendMail(String host, String port, Email email, int mailSmtpTimeout,
        int mailSmtpConnectionTimeout) throws Exception {
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.timeout", mailSmtpTimeout);
    props.put("mail.smtp.connectiontimeout", mailSmtpConnectionTimeout);
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(email.getFrom()));
    for (String recipient : email.getTo().trim().split("\\s*,\\s*")) {
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
    }//from   www .  j  a  va  2  s. c o m
    if (email.getCc() != null && email.getCc().length() > 0) {
        for (String recipient : email.getCc().trim().split("\\s*,\\s*")) {
            message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(recipient));
        }
    }
    message.setSubject(email.getSubject());
    message.setSentDate(new Date());

    MimeBodyPart messagePart = new MimeBodyPart();
    messagePart.setText(email.getMessage());
    Multipart multipart = new MimeMultipart();

    multipart.addBodyPart(messagePart);
    message.setContent(multipart);
    Transport.send(message);
}

From source file:org.chenillekit.mail.services.TestMailService.java

@Test
public void test_multipartemail_sending() throws EmailException, MessagingException {
    MultiPartEmail email = new MultiPartEmail();
    email.setSubject("Test Mail 2");
    email.addTo("homburgs@gmail.com");
    email.setFrom("homburgs@gmail.com");
    email.setMsg("This is a dummy message text!");
    email.addPart("This is a dummy message part 1!", "text/plain");

    MimeMultipart mmp = new MimeMultipart();
    MimeBodyPart mbp = new MimeBodyPart();

    mbp.setText("This is a dummy MimeBodyPart 1!");

    mmp.addBodyPart(mbp);//  w ww . j  a v  a  2 s .c  om
    email.addPart(mmp);

    EmailAttachment attachment = new EmailAttachment();
    attachment.setDescription("dummy.txt");
    attachment.setURL(new ClasspathResource("dummy.txt").toURL());
    email.attach(attachment);

    MailService mailService = registry.getService(MailService.class);
    boolean sended = mailService.sendEmail(email);

    assertTrue(sended, "sended");
}

From source file:org.exoplatform.extension.social.notifications.SocialNotificationService.java

/**
 * /*from  ww  w  .  j  av  a 2  s. c  o m*/
 * @param invitedUsersList 
 */
private void invitedUserNotification(Map<String, List<Space>> invitedUsersList) {

    for (Map.Entry<String, List<Space>> entry : invitedUsersList.entrySet()) {

        try {
            String userId = entry.getKey();
            List<Space> spacesList = entry.getValue();
            Locale locale = Locale.getDefault();

            // get default locale of the manager
            String userLocale = this.getOrganizationService().getUserProfileHandler()
                    .findUserProfileByName(userId).getAttribute("user.language");
            Profile userProfile = getIdentityManager()
                    .getOrCreateIdentity(OrganizationIdentityProvider.NAME, userId, false).getProfile();

            if (userLocale != null && !userLocale.trim().isEmpty()) {
                locale = new Locale(userLocale);
            }

            // getMessageTemplate
            MessageTemplate messageTemplate = this.getMailMessageTemplate(
                    SocialNotificationConfiguration.MAIL_TEMPLATE_SPACE_PENDING_INVITATIONS, locale);

            GroovyTemplate g = new GroovyTemplate(messageTemplate.getSubject());

            Map binding = new HashMap();
            binding.put("userProfile", userProfile);
            binding.put("portalUrl", this.getPortalUrl());
            binding.put("invitationUrl", this.getPortalUrl() + "/portal/intranet/invitationSpace");
            binding.put("spacesList", spacesList);

            String subject = g.render(binding);

            g = new GroovyTemplate(messageTemplate.getHtmlContent());
            String htmlContent = g.render(binding);

            g = new GroovyTemplate(messageTemplate.getPlainTextContent());
            String textContent = g.render(binding);

            MailService mailService = this.getMailService();
            Session mailSession = mailService.getMailSession();
            MimeMessage message = new MimeMessage(mailSession);
            message.setFrom(this.getSenderAddress());

            // send email to invited user
            message.setRecipient(RecipientType.TO,
                    new InternetAddress(userProfile.getEmail(), userProfile.getFullName()));
            message.setSubject(subject);
            MimeMultipart content = new MimeMultipart("alternative");
            MimeBodyPart text = new MimeBodyPart();
            MimeBodyPart html = new MimeBodyPart();
            text.setText(textContent);
            html.setContent(htmlContent, "text/html; charset=ISO-8859-1");
            content.addBodyPart(text);
            content.addBodyPart(html);
            message.setContent(content);

            log.info("Sending mail to : " + userProfile.getEmail() + " : " + subject + "\n" + html);

            mailService.sendMessage(message);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

From source file:org.exoplatform.extension.social.notifications.SocialNotificationService.java

/**
 * //w  w  w  .j av a 2  s. c o m
 * @param space
 * @param managers
 * @param pendingUsers 
 */
private void pendingUserNotification(Space space, List<Profile> managerList, List<Profile> pendingUsers) {
    //TODO : use groovy template stored in JCR for mail information (cleaner, real templating)

    log.info("Sending mail to space manager : pending users");

    try {

        // loop on each manager and send mail
        // like that each manager will have the mail in its preferred language
        // ideally should be done in a different executor
        // TODO: see if we can optimize this to avoid do it for all user
        //       - send a mail to all the users in the same time (what about language)
        //       - cache the template result and send mail

        for (Profile manager : managerList) {
            Locale locale = Locale.getDefault();

            // get default locale of the manager
            String userId = manager.getIdentity().getRemoteId();
            String userLocale = this.getOrganizationService().getUserProfileHandler()
                    .findUserProfileByName(userId).getAttribute("user.language");
            if (userLocale != null && !userLocale.trim().isEmpty()) {
                locale = new Locale(userLocale);
            }

            // getMessageTemplate
            MessageTemplate messageTemplate = this.getMailMessageTemplate(
                    SocialNotificationConfiguration.MAIL_TEMPLATE_SPACE_PENDING_USERS, locale);

            GroovyTemplate g = new GroovyTemplate(messageTemplate.getSubject());

            String spaceUrl = this.getPortalUrl() + "/portal/g/:spaces:" + space.getUrl() + "/" + space.getUrl()
                    + "/settings"; //TODO: see which API to use
            String spaceAvatarUrl = null;
            if (space.getAvatarUrl() != null) {
                spaceAvatarUrl = this.getPortalUrl() + space.getAvatarUrl();
            }

            Map binding = new HashMap();
            binding.put("space", space);
            binding.put("portalUrl", this.getPortalUrl());
            binding.put("spaceSettingUrl", spaceUrl);
            binding.put("spaceAvatarUrl", spaceAvatarUrl);
            binding.put("userPendingList", pendingUsers);

            String subject = g.render(binding);

            g = new GroovyTemplate(messageTemplate.getHtmlContent());
            String htmlContent = g.render(binding);

            g = new GroovyTemplate(messageTemplate.getPlainTextContent());
            String textContent = g.render(binding);

            MailService mailService = this.getMailService();
            Session mailSession = mailService.getMailSession();
            MimeMessage message = new MimeMessage(mailSession);
            message.setFrom(this.getSenderAddress());

            // send email to manager
            message.setRecipient(RecipientType.TO,
                    new InternetAddress(manager.getEmail(), manager.getFullName()));
            message.setSubject(subject);
            MimeMultipart content = new MimeMultipart("alternative");
            MimeBodyPart text = new MimeBodyPart();
            MimeBodyPart html = new MimeBodyPart();
            text.setText(textContent);
            html.setContent(htmlContent, "text/html; charset=ISO-8859-1");
            content.addBodyPart(text);
            content.addBodyPart(html);
            message.setContent(content);

            log.info("Sending mail to" + manager.getEmail() + " : " + subject + " : " + subject + "\n" + html);

            //mailService.sendMessage(message);
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.kuali.test.utils.Utils.java

/**
 * /*  w  w w .  j  a  va2  s.c o m*/
 * @param configuration
 * @param overrideEmail
 * @param testSuite
 * @param testHeader
 * @param testResults
 * @param errorCount
 * @param warningCount
 * @param successCount 
 */
public static void sendMail(KualiTestConfigurationDocument.KualiTestConfiguration configuration,
        String overrideEmail, TestSuite testSuite, TestHeader testHeader, List<File> testResults,
        int errorCount, int warningCount, int successCount) {

    if (StringUtils.isNotBlank(configuration.getEmailSetup().getFromAddress())
            && StringUtils.isNotBlank(configuration.getEmailSetup().getMailHost())) {

        String[] toAddresses = getEmailToAddresses(configuration, testSuite, testHeader);

        if (toAddresses.length > 0) {
            Properties props = new Properties();
            props.put("mail.smtp.host", configuration.getEmailSetup().getMailHost());
            Session session = Session.getDefaultInstance(props, null);

            try {
                Message msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress(configuration.getEmailSetup().getFromAddress()));

                if (StringUtils.isBlank(overrideEmail)) {
                    for (String recipient : toAddresses) {
                        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
                    }
                } else {
                    StringTokenizer st = new StringTokenizer(overrideEmail, ",");
                    while (st.hasMoreTokens()) {
                        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(st.nextToken()));
                    }
                }

                StringBuilder subject = new StringBuilder(configuration.getEmailSetup().getSubject());
                subject.append(" - Platform: ");
                if (testSuite != null) {
                    subject.append(testSuite.getPlatformName());
                    subject.append(", TestSuite: ");
                    subject.append(testSuite.getName());
                } else {
                    subject.append(testHeader.getPlatformName());
                    subject.append(", Test: ");
                    subject.append(testHeader.getTestName());
                }

                subject.append(" - [errors=");
                subject.append(errorCount);
                subject.append(", warnings=");
                subject.append(warningCount);
                subject.append(", successes=");
                subject.append(successCount);
                subject.append("]");

                msg.setSubject(subject.toString());

                StringBuilder msgtxt = new StringBuilder(256);
                msgtxt.append("Please see test output in the following attached files:\n");

                for (File f : testResults) {
                    msgtxt.append(f.getName());
                    msgtxt.append("\n");
                }

                // create and fill the first message part
                MimeBodyPart mbp1 = new MimeBodyPart();
                mbp1.setText(msgtxt.toString());

                // create the Multipart and add its parts to it
                Multipart mp = new MimeMultipart();
                mp.addBodyPart(mbp1);

                for (File f : testResults) {
                    if (f.exists() && f.isFile()) {
                        // create the second message part
                        MimeBodyPart mbp2 = new MimeBodyPart();

                        // attach the file to the message
                        mbp2.setDataHandler(new DataHandler(new FileDataSource(f)));
                        mbp2.setFileName(f.getName());
                        mp.addBodyPart(mbp2);
                    }
                }

                // add the Multipart to the message
                msg.setContent(mp);

                // set the Date: header
                msg.setSentDate(new Date());

                Transport.send(msg);
            } catch (MessagingException ex) {
                LOG.warn(ex.toString(), ex);
            }
        }
    }
}

From source file:org.openadaptor.auxil.connector.smtp.SMTPConnection.java

/**
 * Generate body of email. It will either be a mime multipart message or text. This is
 * determined by the <code>recordsAsAttachment</code> property.
 *
 * @param body//from w ww  . j  av  a2  s  .  co m
 * @throws MessagingException
 */
public void generateMessageBody(String body) throws MessagingException {
    MimeBodyPart mbpPrefaceBody, mbpBody;
    MimeMultipart mmp;

    // Determine if records are to be send as an attachment
    if (recordsAsAttachment) {
        //Define mime parts
        mbpPrefaceBody = new MimeBodyPart();
        mbpPrefaceBody.setText(bodyPreface);
        mbpBody = new MimeBodyPart();
        if (mimeContentType != null && !(mimeContentType.length() == 0)) {
            mbpBody.setContent(body, mimeContentType);
        } else {
            mbpBody.setText(body);
        }
        //Create mime message
        mmp = new MimeMultipart();
        mmp.addBodyPart(mbpPrefaceBody);
        mmp.addBodyPart(mbpBody);
        message.setContent(mmp);
    } else if (mimeContentType != null && !(mimeContentType.length() == 0)) {
        message.setContent(bodyPreface + "\n\n" + body, mimeContentType);
    } else {
        message.setText(bodyPreface + "\n\n" + body);
    }
}