Example usage for javax.mail.internet MimeBodyPart MimeBodyPart

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

Introduction

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

Prototype

public MimeBodyPart() 

Source Link

Document

An empty MimeBodyPart object is created.

Usage

From source file:org.topazproject.ambra.email.impl.FreemarkerTemplateMailer.java

/**
 * Mail the email formatted using the given templates
 * @param toEmailAddresses List of email addresses to which emails should be sent.  White space delimited.
 * @param fromEmailAddress fromEmailAddress
 * @param subject subject of the email/*from  ww  w .ja v a  2s  .c  om*/
 * @param context context to set the values from for the template
 * @param textTemplateFilename textTemplateFilename
 * @param htmlTemplateFilename htmlTemplateFilename
 */
public void mail(final String toEmailAddresses, final String fromEmailAddress, final String subject,
        final Map<String, Object> context, final String textTemplateFilename,
        final String htmlTemplateFilename) {
    final StringTokenizer emailTokens = new StringTokenizer(toEmailAddresses);

    while (emailTokens.hasMoreTokens()) {
        final String toEmailAddress = emailTokens.nextToken();
        final MimeMessagePreparator preparator = new MimeMessagePreparator() {
            public void prepare(final MimeMessage mimeMessage) throws MessagingException, IOException {
                final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true,
                        configuration.getDefaultEncoding());
                message.setTo(new InternetAddress(toEmailAddress));
                message.setFrom(new InternetAddress(fromEmailAddress, (String) context.get(USER_NAME_KEY)));
                message.setSubject(subject);

                // Create a "text" Multipart message
                final Multipart mp = createPartForMultipart(textTemplateFilename, context, "alternative",
                        MIME_TYPE_TEXT_PLAIN + "; charset=" + configuration.getDefaultEncoding());

                // Create a "HTML" Multipart message
                final Multipart htmlContent = createPartForMultipart(htmlTemplateFilename, context, "related",
                        MIME_TYPE_TEXT_HTML + "; charset=" + configuration.getDefaultEncoding());

                final BodyPart htmlPart = new MimeBodyPart();
                htmlPart.setContent(htmlContent);
                mp.addBodyPart(htmlPart);

                mimeMessage.setContent(mp);
            }
        };
        mailSender.send(preparator);
        if (log.isDebugEnabled()) {
            log.debug("Mail sent to:" + toEmailAddress);
        }
    }
}

From source file:org.infoglue.common.util.mail.MailService.java

/**
 * @param attachments /*w w w  . ja v  a2  s .c om*/
 *
 */
private Message createMessage(String from, String to, String bcc, String subject, String content,
        String contentType, String encoding, List attachments) throws SystemException {
    try {
        final Message message = new MimeMessage(this.session);
        String contentTypeWithEncoding = contentType + ";charset=" + encoding;

        // message.setContent(content, contentType);
        message.setFrom(createInternetAddress(from));
        //message.setRecipient(Message.RecipientType.TO,
        //      createInternetAddress(to));
        message.setRecipients(Message.RecipientType.TO, createInternetAddresses(to));
        if (bcc != null)
            message.setRecipients(Message.RecipientType.BCC, createInternetAddresses(bcc));
        // message.setSubject(subject);

        ((MimeMessage) message).setSubject(subject, encoding);
        MimeMultipart mp = new MimeMultipart();
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setDataHandler(new DataHandler(new StringDataSource(content, contentTypeWithEncoding, encoding)));
        mp.addBodyPart(mbp1);
        if (attachments != null) {
            for (Iterator it = attachments.iterator(); it.hasNext();) {
                File attachmentFile = (File) it.next();
                if (attachmentFile.exists()) {
                    MimeBodyPart attachment = new MimeBodyPart();
                    attachment.setFileName(attachmentFile.getName());
                    attachment.setDataHandler(new DataHandler(new FileDataSource(attachmentFile)));
                    mp.addBodyPart(attachment);
                }
            }
        }
        message.setContent(mp);
        // message.setText(content);
        // message.setDataHandler(new DataHandler(new
        // StringDataSource(content, contentTypeWithEncoding, encoding)));
        // message.setText(content);
        // message.setDataHandler(new DataHandler(new
        // StringDataSource(content, "text/html")));

        return message;
    } catch (MessagingException e) {
        throw new SystemException("Unable to create the message.", e);
    }
}

From source file:net.sf.jclal.util.mail.SenderEmail.java

/**
 * Send the email with the indicated parameters
 *
 * @param subject The subject/*from   w ww  .  j a  va  2 s . co m*/
 * @param content The content
 * @param reportFile The reportFile to send
 */
public void sendEmail(String subject, String content, File reportFile) {

    // Get system properties
    Properties properties = new Properties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", host);
    properties.put("mail.smtp.port", port);

    if (!user.isEmpty() && !pass.isEmpty()) {

        properties.setProperty("mail.user", user);

        properties.setProperty("mail.password", pass);
    }

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.addRecipients(Message.RecipientType.TO, toRecipients.toString());

        // Set Subject: header field
        message.setSubject(subject);

        // Create the message part 
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        messageBodyPart.setText(content);

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        if (attachReporFile) {

            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(reportFile)));
            messageBodyPart.setFileName(reportFile.getName());
            multipart.addBodyPart(messageBodyPart);
        }

        // Send the complete message parts
        message.setContent(multipart);

        // Send message
        Transport.send(message);

        System.out.println("Sent message successfully....");

    } catch (MessagingException e) {

        Logger.getLogger(SenderEmail.class.getName()).log(Level.SEVERE, null, e);
    }

}

From source file:org.openmrs.module.sync.SyncMailUtil.java

/**
 * Sends a message using the current mail session
 *//*from  w w w  .ja  va 2s.  c  o m*/
public static void sendMessage(String recipients, String subject, String body) throws MessageException {
    try {
        Message message = new MimeMessage(getMailSession());
        message.setSentDate(new Date());
        if (StringUtils.isNotBlank(subject)) {
            message.setSubject(subject);
        }
        if (StringUtils.isNotBlank(recipients)) {
            for (String recipient : recipients.split("\\,")) {
                message.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(recipient));
            }
        }
        if (StringUtils.isNotBlank(body)) {
            Multipart multipart = new MimeMultipart();
            MimeBodyPart contentBodyPart = new MimeBodyPart();
            contentBodyPart.setContent(body, "text/html");
            multipart.addBodyPart(contentBodyPart);
            message.setContent(multipart);
        }
        log.info("Sending email with subject <" + subject + "> to <" + recipients + ">");
        log.debug("Mail has contents: \n" + body);
        Transport.send(message);
        log.debug("Message sent without errors");
    } catch (Exception e) {
        log.error("Message could not be sent due to " + e.getMessage(), e);
        throw new MessageException(e);
    }
}

From source file:org.unitime.commons.Email.java

public void setHTML(String message) throws MessagingException {
    MimeBodyPart text = new MimeBodyPart();
    text.setContent(message, "text/html; charset=UTF-8");
    iBody.addBodyPart(text);/*  w  ww.  j a v  a2  s. com*/
}

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);// ww w  . j  a  v  a  2s.c  o 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.unitime.commons.JavaMailWrapper.java

@Override
protected void addAttachment(String name, DataHandler data) throws MessagingException {
    BodyPart attachment = new MimeBodyPart();
    attachment.setDataHandler(data);//from   w  w w .j  a  v  a2 s . c o  m
    attachment.setFileName(name);
    attachment.setHeader("Content-ID", "<" + name + ">");
    iBody.addBodyPart(attachment);
}

From source file:org.apache.hupa.server.preferences.InImapUserPreferencesStorage.java

/**
 * Opens the IMAP folder, deletes all messages which match the magic subject and
 * creates a new message with an attachment which contains the object serialized
 *//*from w  w w  .jav  a  2  s  .  co  m*/
protected static void saveUserPreferencesInIMAP(Log logger, User user, Session session, IMAPStore iStore,
        String folderName, String subject, Object object)
        throws MessagingException, IOException, InterruptedException {
    IMAPFolder folder = (IMAPFolder) iStore.getFolder(folderName);

    if (folder.exists() || folder.create(IMAPFolder.HOLDS_MESSAGES)) {
        if (!folder.isOpen()) {
            folder.open(Folder.READ_WRITE);
        }

        // Serialize the object
        ByteArrayOutputStream fout = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(fout);
        oos.writeObject(object);
        oos.close();
        ByteArrayInputStream is = new ByteArrayInputStream(fout.toByteArray());

        // Create a new message with an attachment which has the serialized object
        MimeMessage message = new MimeMessage(session);
        message.setSubject(subject);

        Multipart multipart = new MimeMultipart();
        MimeBodyPart txtPart = new MimeBodyPart();
        txtPart.setContent("This message contains configuration used by Hupa, do not delete it", "text/plain");
        multipart.addBodyPart(txtPart);
        FileItem item = createPreferencesFileItem(is, subject, HUPA_DATA_MIME_TYPE);
        multipart.addBodyPart(MessageUtils.fileitemToBodypart(item));
        message.setContent(multipart);
        message.saveChanges();

        // It seems it's not possible to modify the content of an existing message using the API
        // So I delete the previous message storing the preferences and I create a new one
        Message[] msgs = folder.getMessages();
        for (Message msg : msgs) {
            if (subject.equals(msg.getSubject())) {
                msg.setFlag(Flag.DELETED, true);
            }
        }

        // It is necessary to copy the message before saving it (the same problem in AbstractSendMessageHandler)
        message = new MimeMessage((MimeMessage) message);
        message.setFlag(Flag.SEEN, true);
        folder.appendMessages(new Message[] { message });
        folder.close(true);
        logger.info("Saved preferences " + subject + " in imap folder " + folderName + " for user " + user);
    } else {
        logger.error("Unable to save preferences " + subject + " in imap folder " + folderName + " for user "
                + user);
    }
}

From source file:voldemort.coordinator.HttpGetAllRequestExecutor.java

public void writeResponse(Map<ByteArray, List<Versioned<byte[]>>> versionedResponses) throws Exception {
    // multiPartKeys is the outer multipart
    MimeMultipart multiPartKeys = new MimeMultipart();
    ByteArrayOutputStream keysOutputStream = new ByteArrayOutputStream();

    for (Entry<ByteArray, List<Versioned<byte[]>>> entry : versionedResponses.entrySet()) {
        ByteArray key = entry.getKey();// w w  w.  j a v  a2  s  .  co m
        String contentLocationKey = "/" + this.storeName + "/" + new String(Base64.encodeBase64(key.get()));

        // Create the individual body part - for each key requested
        MimeBodyPart keyBody = new MimeBodyPart();
        try {
            // Add the right headers
            keyBody.addHeader(CONTENT_TYPE, "multipart/binary");
            keyBody.addHeader(CONTENT_TRANSFER_ENCODING, "binary");
            keyBody.addHeader(CONTENT_LOCATION, contentLocationKey);
        } catch (MessagingException me) {
            logger.error("Exception while constructing key body headers", me);
            keysOutputStream.close();
            throw me;
        }
        // multiPartValues is the inner multipart
        MimeMultipart multiPartValues = new MimeMultipart();
        for (Versioned<byte[]> versionedValue : entry.getValue()) {

            byte[] responseValue = versionedValue.getValue();

            VectorClock vectorClock = (VectorClock) versionedValue.getVersion();
            String serializedVC = CoordinatorUtils.getSerializedVectorClock(vectorClock);

            // Create the individual body part - for each versioned value of
            // a key
            MimeBodyPart valueBody = new MimeBodyPart();
            try {
                // Add the right headers
                valueBody.addHeader(CONTENT_TYPE, "application/octet-stream");
                valueBody.addHeader(CONTENT_TRANSFER_ENCODING, "binary");
                valueBody.addHeader(VoldemortHttpRequestHandler.X_VOLD_VECTOR_CLOCK, serializedVC);
                valueBody.setContent(responseValue, "application/octet-stream");

                multiPartValues.addBodyPart(valueBody);
            } catch (MessagingException me) {
                logger.error("Exception while constructing value body part", me);
                keysOutputStream.close();
                throw me;
            }

        }
        try {
            // Add the inner multipart as the content of the outer body part
            keyBody.setContent(multiPartValues);
            multiPartKeys.addBodyPart(keyBody);
        } catch (MessagingException me) {
            logger.error("Exception while constructing key body part", me);
            keysOutputStream.close();
            throw me;
        }

    }
    try {
        multiPartKeys.writeTo(keysOutputStream);
    } catch (Exception e) {
        logger.error("Exception while writing mutipart to output stream", e);
        throw e;
    }

    ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();
    responseContent.writeBytes(keysOutputStream.toByteArray());

    // Create the Response object
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);

    // Set the right headers
    response.setHeader(CONTENT_TYPE, "multipart/binary");
    response.setHeader(CONTENT_TRANSFER_ENCODING, "binary");

    // Copy the data into the payload
    response.setContent(responseContent);
    response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());

    // Update the stats
    if (this.coordinatorPerfStats != null) {
        long durationInNs = System.nanoTime() - startTimestampInNs;
        this.coordinatorPerfStats.recordTime(Tracked.GET_ALL, durationInNs);
    }

    // Write the response to the Netty Channel
    this.getRequestMessageEvent.getChannel().write(response);

    keysOutputStream.close();
}

From source file:org.data2semantics.yasgui.selenium.FailNotification.java

private void sendMail(String subject, String content, String fileName) {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(baseTest.props.getMailUserName(),
                    baseTest.props.getMailPassWord());
        }/*from w ww.  j av a 2s  .  c  o  m*/
    });

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(baseTest.props.getMailUserName()));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(baseTest.props.getMailSendTo()));
        message.setSubject(subject);
        message.setContent(content, "text/html; charset=utf-8");

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        // message body
        messageBodyPart.setContent(content, "text/html; charset=utf-8");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        // attachment
        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(fileName);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("screenshot.png");
        multipart.addBodyPart(messageBodyPart);
        message.setContent(multipart);

        Transport.send(message);

        System.out.println("Email send");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}