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.xwiki.mail.internal.factory.html.HTMLMimeBodyPartFactory.java

/**
 * @return Multipart part of the email, define the HTML as a multipart/alternative
 *///w  ww . j a  v  a  2 s. c  o m
private MimeBodyPart createAlternativePart(MimeBodyPart htmlBodyPart, MimeBodyPart textBodyPart)
        throws MessagingException {
    MimeMultipart alternativeMultiPart = new MimeMultipart("alternative");

    // Note: it's important to have the text before the HTML, from low fidelity to high fidelity according to the
    // MIME specification. Otherwise some readers will display text even though there's HTML in your mail message.
    alternativeMultiPart.addBodyPart(textBodyPart);
    alternativeMultiPart.addBodyPart(htmlBodyPart);

    MimeBodyPart alternativePartWrapper = new MimeBodyPart();
    alternativePartWrapper.setContent(alternativeMultiPart);
    return alternativePartWrapper;
}

From source file:org.sigmah.server.mail.MailSenderImpl.java

@Override
public void sendFile(Email email, String fileName, InputStream fileStream) throws EmailException {
    final String user = email.getAuthenticationUserName();
    final String password = email.getAuthenticationPassword();

    final Properties properties = new Properties();
    properties.setProperty(MAIL_TRANSPORT_PROTOCOL, TRANSPORT_PROTOCOL);
    properties.setProperty(MAIL_SMTP_HOST, email.getHostName());
    properties.setProperty(MAIL_SMTP_PORT, Integer.toString(email.getSmtpPort()));

    final StringBuilder toBuilder = new StringBuilder();
    for (final String to : email.getToAddresses()) {
        if (toBuilder.length() > 0) {
            toBuilder.append(',');
        }//from  www.  j a v a2 s  .co m
        toBuilder.append(to);
    }

    final StringBuilder ccBuilder = new StringBuilder();
    if (email.getCcAddresses().length > 0) {
        for (final String cc : email.getCcAddresses()) {
            if (ccBuilder.length() > 0) {
                ccBuilder.append(',');
            }
            ccBuilder.append(cc);
        }
    }

    final Session session = javax.mail.Session.getInstance(properties);
    try {
        final DataSource attachment = new ByteArrayDataSource(fileStream,
                FileType.fromExtension(FileType.getExtension(fileName), FileType._DEFAULT).getContentType());

        final Transport transport = session.getTransport();

        if (password != null) {
            transport.connect(user, password);
        } else {
            transport.connect();
        }

        final MimeMessage message = new MimeMessage(session);

        // Configures the headers.
        message.setFrom(new InternetAddress(email.getFromAddress(), false));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toBuilder.toString(), false));
        if (email.getCcAddresses().length > 0) {
            message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccBuilder.toString(), false));
        }

        message.setSubject(email.getSubject(), email.getEncoding());

        // Html body part.
        final MimeMultipart textMultipart = new MimeMultipart("alternative");

        final MimeBodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(email.getContent(), "text/html; charset=\"" + email.getEncoding() + "\"");
        textMultipart.addBodyPart(htmlBodyPart);

        final MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setContent(textMultipart);

        // Attachment body part.
        final MimeBodyPart attachmentPart = new MimeBodyPart();
        attachmentPart.setDataHandler(new DataHandler(attachment));
        attachmentPart.setFileName(fileName);
        attachmentPart.setDescription(fileName);

        // Mail multipart content.
        final MimeMultipart contentMultipart = new MimeMultipart("related");
        contentMultipart.addBodyPart(textBodyPart);
        contentMultipart.addBodyPart(attachmentPart);

        message.setContent(contentMultipart);
        message.saveChanges();

        // Sends the mail.
        transport.sendMessage(message, message.getAllRecipients());

    } catch (UnsupportedEncodingException ex) {
        throw new EmailException(
                "An error occured while encoding the mail content to '" + email.getEncoding() + "'.", ex);

    } catch (IOException ex) {
        throw new EmailException("An error occured while reading the attachment of an email.", ex);

    } catch (MessagingException ex) {
        throw new EmailException("An error occured while sending an email.", ex);
    }
}

From source file:org.pentaho.platform.repository.subscription.SubscriptionEmailContent.java

public boolean send() {
    String cc = null;/*  w  ww. j av  a2s .  c o  m*/
    String bcc = null;
    String from = props.getProperty("mail.from.default");
    String to = props.getProperty("to");
    boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth"));
    String subject = props.getProperty("subject");
    String body = props.getProperty("body");

    logger.info("Going to send an email to " + to + " from " + from + "with the subject '" + subject
            + "' and the body " + body);

    try {
        // Get a Session object
        Session session;

        if (authenticate) {
            Authenticator authenticator = new EmailAuthenticator();
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // if debugging is not set in the email config file, then default to false
        if (!props.containsKey("mail.debug")) { //$NON-NLS-1$
            session.setDebug(false);
        }

        // construct the message
        MimeMessage msg = new MimeMessage(session);
        Multipart multipart = new MimeMultipart();

        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        } else {
            // There should be no way to get here
            logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        if (body != null) {
            MimeBodyPart textBodyPart = new MimeBodyPart();
            textBodyPart.setContent(body, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
            multipart.addBodyPart(textBodyPart);
        }

        // need to create a multi-part message...
        // create the Multipart and add its parts to it

        // create and fill the first message part
        IPentahoStreamSource source = attachment;
        if (source == null) {
            logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$
            return false;
        }
        DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source);

        // create the second message part
        MimeBodyPart attachmentBodyPart = new MimeBodyPart();

        // attach the file to the message
        attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
        attachmentBodyPart.setFileName(attachmentName);

        multipart.addBodyPart(attachmentBodyPart);

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

        msg.setHeader("X-Mailer", SubscriptionEmailContent.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        return true;
        // TODO: persist the content set for a while...
    } catch (SendFailedException e) {
        logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$

    } catch (AuthenticationFailedException e) {
        logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$
    } catch (Throwable e) {
        logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$
    }
    return false;
}

From source file:com.github.thorqin.toolkit.mail.MailService.java

private void sendMail(Mail mail) {
    long beginTime = System.currentTimeMillis();
    Properties props = new Properties();
    final Session session;
    props.put("mail.smtp.auth", String.valueOf(setting.auth));
    // If want to display SMTP protocol detail then uncomment following statement
    // props.put("mail.debug", "true");
    props.put("mail.smtp.host", setting.host);
    props.put("mail.smtp.port", setting.port);
    if (setting.secure.equals(SECURE_STARTTLS)) {
        props.put("mail.smtp.starttls.enable", "true");

    } else if (setting.secure.equals(SECURE_SSL)) {
        props.put("mail.smtp.socketFactory.port", setting.port);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
    }//from  ww  w  .ja  va 2s  .  c  om
    if (!setting.auth)
        session = Session.getInstance(props);
    else
        session = Session.getInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(setting.user, setting.password);
            }
        });

    if (setting.debug)
        session.setDebug(true);

    MimeMessage message = new MimeMessage(session);
    StringBuilder mailTo = new StringBuilder();
    try {
        if (mail.from != null)
            message.setFrom(new InternetAddress(mail.from));
        else if (setting.from != null)
            message.setFrom(new InternetAddress(setting.from));
        if (mail.to != null) {
            for (String to : mail.to) {
                if (mailTo.length() > 0)
                    mailTo.append(",");
                mailTo.append(to);
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }
        }
        if (mail.subject != null)
            message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?=");
        message.setSentDate(new Date());

        BodyPart bodyPart = new MimeBodyPart();
        if (mail.htmlBody != null)
            bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8");
        else if (mail.textBody != null)
            bodyPart.setText(mail.textBody);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);

        if (mail.attachments != null) {
            for (String attachment : mail.attachments) {
                BodyPart attachedBody = new MimeBodyPart();
                File attachedFile = new File(attachment);
                DataSource source = new FileDataSource(attachedFile);
                attachedBody.setDataHandler(new DataHandler(source));
                attachedBody.setDisposition(MimeBodyPart.ATTACHMENT);
                String filename = attachedFile.getName();
                attachedBody.setFileName(
                        "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?=");
                multipart.addBodyPart(attachedBody);
            }
        }

        message.setContent(multipart);
        message.saveChanges();
        Transport transport = session.getTransport("smtp");
        transport.connect();

        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        if (setting.trace && tracer != null) {
            Tracer.Info info = new Tracer.Info();
            info.catalog = "mail";
            info.name = "send";
            info.put("sender", StringUtils.join(message.getFrom()));
            info.put("recipients", mail.to);
            info.put("SMTPServer", setting.host);
            info.put("SMTPAccount", setting.user);
            info.put("subject", mail.subject);
            info.put("startTime", beginTime);
            info.put("runningTime", System.currentTimeMillis() - beginTime);
            tracer.trace(info);
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Send mail failed!", ex);
    }
}

From source file:eagle.common.email.EagleMailClient.java

private boolean _send(String from, String to, String cc, String title, String content,
        List<MimeBodyPart> attachments) {
    MimeMessage mail = new MimeMessage(session);
    try {// w w w.  ja v a  2 s .com
        mail.setFrom(new InternetAddress(from));
        mail.setSubject(title);
        if (to != null) {
            mail.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        }
        if (cc != null) {
            mail.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
        }

        //mail.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(DEFAULT_BCC_ADDRESS));

        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setContent(content, "text/html;charset=utf-8");

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(mimeBodyPart);

        for (MimeBodyPart attachment : attachments) {
            multipart.addBodyPart(attachment);
        }

        mail.setContent(multipart);
        //         mail.setContent(content, "text/html;charset=utf-8");
        LOG.info(String.format("Going to send mail: from[%s], to[%s], cc[%s], title[%s]", from, to, cc, title));
        Transport.send(mail);
        return true;
    } catch (AddressException e) {
        LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e);
        return false;
    } catch (MessagingException e) {
        LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e);
        return false;
    }
}

From source file:org.apache.axiom.om.impl.MIMEOutputUtils.java

/**
 * @deprecated This method is only useful in conjunction with
 *             {@link #writeBodyPart(OutputStream, MimeBodyPart, String)}, which is deprecated.
 *//*from w  ww. ja v a  2 s  .c  o m*/
public static MimeBodyPart createMimeBodyPart(String contentID, DataHandler dataHandler,
        OMOutputFormat omOutputFormat) throws MessagingException {
    String contentType = dataHandler.getContentType();

    // Get the content-transfer-encoding
    String contentTransferEncoding = "binary";
    if (dataHandler instanceof ConfigurableDataHandler) {
        ConfigurableDataHandler configurableDataHandler = (ConfigurableDataHandler) dataHandler;
        contentTransferEncoding = configurableDataHandler.getTransferEncoding();
    }

    if (isDebugEnabled) {
        log.debug("Create MimeBodyPart");
        log.debug("  Content-ID = " + contentID);
        log.debug("  Content-Type = " + contentType);
        log.debug("  Content-Transfer-Encoding = " + contentTransferEncoding);
    }

    boolean useCTEBase64 = omOutputFormat != null && Boolean.TRUE
            .equals(omOutputFormat.getProperty(OMOutputFormat.USE_CTE_BASE64_FOR_NON_TEXTUAL_ATTACHMENTS));
    if (useCTEBase64) {
        if (!CommonUtils.isTextualPart(contentType) && "binary".equals(contentTransferEncoding)) {
            if (isDebugEnabled) {
                log.debug(
                        " changing Content-Transfer-Encoding from " + contentTransferEncoding + " to base-64");
            }
            contentTransferEncoding = "base64";
        }

    }

    // Now create the mimeBodyPart for the datahandler and add the appropriate content headers
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setDataHandler(dataHandler);
    mimeBodyPart.addHeader("Content-ID", "<" + contentID + ">");
    mimeBodyPart.addHeader("Content-Type", contentType);
    mimeBodyPart.addHeader("Content-Transfer-Encoding", contentTransferEncoding);
    return mimeBodyPart;
}

From source file:bioLockJ.module.agent.MailAgent.java

private Multipart getContent() throws Exception {
    final Multipart multipart = new MimeMultipart();
    final BodyPart messageBodyPart = new MimeBodyPart();
    final List<BodyPart> attachments = getAttachments();
    messageBodyPart.setText(getSummary());
    multipart.addBodyPart(messageBodyPart);
    for (final BodyPart bp : attachments) {
        multipart.addBodyPart(bp);/*from w w w  .  j  a v  a 2s  .c  o m*/
    }

    return multipart;
}

From source file:net.duckling.ddl.service.mail.impl.MailServiceImpl.java

public void sendMail(Mail mail) {
    LOG.debug("sendEmail() to: " + mail.getRecipient());
    try {/*from w w  w.j  a  v  a2  s.  c o  m*/
        Session session = Session.getInstance(m_bag.m_mailProperties, m_bag.m_authenticator);
        session.setDebug(false);
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(m_bag.m_fromAddress);
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mail.getRecipient()));
        msg.setSubject(mail.getSubject());
        msg.setSentDate(new Date());

        Multipart mp = new MimeMultipart();

        MimeBodyPart txtmbp = new MimeBodyPart();
        txtmbp.setContent(mail.getMessage(), EMAIL_CONTENT_TYPE);
        mp.addBodyPart(txtmbp);

        List<String> attachments = mail.getAttachments();
        for (Iterator<String> it = attachments.iterator(); it.hasNext();) {
            MimeBodyPart mbp = new MimeBodyPart();
            String filename = it.next();
            FileDataSource fds = new FileDataSource(filename);
            mbp.setDataHandler(new DataHandler(fds));
            mbp.setFileName(MimeUtility.encodeText(fds.getName()));
            mp.addBodyPart(mbp);
        }

        msg.setContent(mp);

        if ((m_bag.m_fromAddress != null) && (m_bag.m_fromAddress.getAddress() != null)
                && (m_bag.m_fromAddress.getAddress().indexOf("@") != -1)) {
            cheat(msg,
                    m_bag.m_fromAddress.getAddress().substring(m_bag.m_fromAddress.getAddress().indexOf("@")));
        }

        Transport.send(msg);

        LOG.info("Successfully send the mail to " + mail.getRecipient());

    } catch (Throwable e) {

        LOG.error("Exception occured while trying to send notification to: " + mail.getRecipient(), e);
        LOG.debug("Details:", e);
    }
}

From source file:org.eclipse.ecr.automation.core.mail.Composer.java

public Mailer.Message newMixedMessage(String templateContent, Object ctx, String textType,
        List<Blob> attachments) throws Exception {
    if (textType == null) {
        textType = "plain";
    }/*from ww  w . j a v a  2 s.c o  m*/
    Mailer.Message msg = mailer.newMessage();
    MimeMultipart mp = new MimeMultipart();
    MimeBodyPart body = new MimeBodyPart();
    String result = render(templateContent, ctx);
    body.setText(result, "UTF-8", textType);
    mp.addBodyPart(body);
    for (Blob blob : attachments) {
        MimeBodyPart a = new MimeBodyPart();
        a.setDataHandler(new DataHandler(new BlobDataSource(blob)));
        a.setFileName(blob.getFilename());
        mp.addBodyPart(a);
    }
    msg.setContent(mp);
    return msg;
}

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

private BodyPart createBodyPart(final String mimeType, final String htmlTemplateFilename,
        final Map<String, Object> context) throws IOException, MessagingException {
    final BodyPart htmlPage = new MimeBodyPart();
    final Template htmlTemplate = configuration.getTemplate(htmlTemplateFilename);
    final String encoding = configuration.getDefaultEncoding();
    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(100);
    final Writer writer = new BufferedWriter(new OutputStreamWriter(outputStream, encoding));
    htmlTemplate.setOutputEncoding(encoding);
    htmlTemplate.setEncoding(encoding);//from  w w  w  .  j  a  v  a2s  .co  m
    try {
        htmlTemplate.process(context, writer);
    } catch (TemplateException e) {
        throw new MailPreparationException(
                "Can't generate " + mailContentTypes.get(mimeType) + " subscription mail", e);
    }

    htmlPage.setDataHandler(new BodyPartDataHandler(outputStream, mimeType));
    return htmlPage;
}