Example usage for javax.mail.internet MimeBodyPart setContent

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

Introduction

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

Prototype

@Override
public void setContent(Object o, String type) throws MessagingException 

Source Link

Document

A convenience method for setting this body part's content.

Usage

From source file:be.fedict.eid.pkira.blm.model.mail.MailHandlerBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void onMessage(Message arg0) {
    ObjectMessage objectMessage = (ObjectMessage) arg0;
    try {//from w  w w.j  a va  2 s. co m
        Mail mail = (Mail) objectMessage.getObject();

        // Get properties
        String mailProtocol = getMailProtocol();
        String mailServer = getSmtpServer();
        String mailUser = getSmtpUser();
        String mailPort = getSmtpPort();
        String mailPassword = getSmtpPassword();

        // Initialize a mail session
        Properties props = new Properties();
        props.put("mail." + mailProtocol + ".host", mailServer);
        props.put("mail." + mailProtocol + ".port", mailPort);
        Session session = Session.getInstance(props);

        // Create the message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(mail.getSender()));
        for (String recipient : mail.getRecipients()) {
            msg.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }
        msg.setSubject(mail.getSubject(), "UTF-8");

        Multipart multipart = new MimeMultipart();
        msg.setContent(multipart);

        // Set the email message text and attachment
        MimeBodyPart messagePart = new MimeBodyPart();
        messagePart.setContent(mail.getBody(), mail.getContentType());
        multipart.addBodyPart(messagePart);

        if (mail.getAttachmentData() != null) {
            ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(mail.getAttachmentData(),
                    mail.getAttachmentContentType());
            DataHandler dataHandler = new DataHandler(byteArrayDataSource);
            MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.setDataHandler(dataHandler);
            attachmentPart.setFileName(mail.getAttachmentFileName());

            multipart.addBodyPart(attachmentPart);
        }

        // Open transport and send message
        Transport transport = session.getTransport(mailProtocol);
        if (StringUtils.isNotBlank(mailUser)) {
            transport.connect(mailUser, mailPassword);
        } else {
            transport.connect();
        }
        msg.saveChanges();
        transport.sendMessage(msg, msg.getAllRecipients());
    } catch (JMSException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot handle the object message from the queue", e);
        throw new RuntimeException(e);
    } catch (MessagingException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot send a mail message", e);
        throw new RuntimeException(e);
    }
}

From source file:com.mylab.mail.OpenCmsMailService.java

public void sendMultipartMail(MessageConfig config, DataSource imageds, String image, DataSource audiods,
        String audio) throws MessagingException {
    log.debug("Sending multipart message " + config);

    Session session = getSession();/* w  w  w .j a  v  a  2  s.  c om*/
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart html = new MimeBodyPart();
    html.setContent(config.getContent(), config.getContentType());
    html.setHeader("MIME-Version", "1.0");
    html.setHeader("Content-Type", html.getContentType());
    multipart.addBodyPart(html);

    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(imageds));
    messageBodyPart.setFileName(image);
    multipart.addBodyPart(messageBodyPart);

    messageBodyPart = new MimeBodyPart();
    messageBodyPart.setDataHandler(new DataHandler(audiods));
    messageBodyPart.setFileName(audio);
    multipart.addBodyPart(messageBodyPart);

    final MimeMessage message = new MimeMessage(session);
    message.setContent(multipart);
    try {
        message.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        addRecipientsWhitelist(message, config.getTo(), config.getToName(), config.getCardconfig());
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }

    message.setSubject(config.getSubject());

    // we don't send in a new Thread so that we get the Exception
    Transport.send(message);

}

From source file:com.reizes.shiva.net.mail.Mail.java

public void sendHtmlMail(String fromName, String from, String to, String cc, String bcc, String subject,
        String content) throws UnsupportedEncodingException, MessagingException {
    boolean parseStrict = false;
    MimeMessage message = new MimeMessage(getSessoin());
    InternetAddress address = InternetAddress.parse(from, parseStrict)[0];

    if (fromName != null) {
        address.setPersonal(fromName, charset);
    }/*from   w w  w  .  ja v a  2 s. com*/

    message.setFrom(address);

    message.setRecipients(Message.RecipientType.TO, parseAddresses(to));

    if (cc != null) {
        message.setRecipients(Message.RecipientType.CC, parseAddresses(cc));
    }
    if (bcc != null) {
        message.setRecipients(Message.RecipientType.BCC, parseAddresses(bcc));
    }

    message.setSubject(subject, charset);

    message.setHeader("X-Mailer", "sendMessage");
    message.setSentDate(new java.util.Date()); //   

    Multipart multipart = new MimeMultipart();
    MimeBodyPart bodypart = new MimeBodyPart();
    bodypart.setContent(content, "text/html; charset=" + charset);
    multipart.addBodyPart(bodypart);

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

From source file:de.elomagic.mag.AbstractTest.java

protected MimeMessage createMimeMessage(String filename) throws Exception {

    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setContent("This is some text to be displayed inline", "text/plain");
    textPart.setDisposition(Part.INLINE);

    MimeBodyPart binaryPart = new MimeBodyPart();
    InputStream in = getClass().getResourceAsStream("/TestFile.pdf");
    binaryPart.setContent(getOriginalMailAttachment(), "application/pdf");
    binaryPart.setDisposition(Part.ATTACHMENT);
    binaryPart.setFileName(filename);//from  w w  w . ja  va  2 s  .  co m

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(textPart);
    mp.addBodyPart(binaryPart);

    MimeMessage message = new MimeMessage(greenMail.getImap().createSession());
    message.setRecipients(Message.RecipientType.TO,
            new InternetAddress[] { new InternetAddress("mailuser@localhost.com") });
    message.setSubject("Another test mail subject");
    message.setContent(mp);

    //
    return message; // GreenMailUtil.createTextEmail("to@localhost.com", "from@localhost.com", "subject", "body", greenMail.getImap().getServerSetup());
}

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 a v 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);
    }
}

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 va2  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:uk.ac.cam.cl.dtg.util.Mailer.java

/**
 * Utility method to allow us to send multipart messages using HTML and plain text.
 *
 * //  www .j a  va2s.com
 * @param recipient
 *            - string array of recipients that the message should be sent to
 * @param from
 *            - the e-mail address that should be used as the sending address
 * @param replyTo
 *            - (nullable) the e-mail address that should be used as the reply-to address
* @param replyToName
*            - (nullable) the name that should be used as the reply-to name
 * @param subject
 *            - The message subject
 * @param plainText
 *            - The message body
 * @param html
 *            - The message body in html
 * @throws MessagingException
 *             - if we cannot send the message for some reason.
 * @throws AddressException
 *             - if the address is not valid.
 */
public void sendMultiPartMail(final String[] recipient, final String from, @Nullable final String replyTo,
        @Nullable final String replyToName, final String subject, final String plainText, final String html)
        throws MessagingException, AddressException, UnsupportedEncodingException {
    Message msg = this.setupMessage(recipient, from, replyTo, replyToName, subject);

    // Create the text part
    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setText(plainText, "utf-8");

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

    Multipart multiPart = new MimeMultipart("alternative");
    multiPart.addBodyPart(textPart);
    multiPart.addBodyPart(htmlPart);

    msg.setContent(multiPart);

    Transport.send(msg);
}

From source file:com.meltmedia.cadmium.email.TestingMessageTransformer.java

public MimeBodyPart newSentToBodyPart(MimeMessage message) throws MessagingException {
    // get information about the original message.
    Address[] originalFromRecipient = message.getFrom();
    Address[] originalToRecipient = message.getRecipients(Message.RecipientType.TO);
    Address[] originalCcRecipient = message.getRecipients(Message.RecipientType.CC);
    Address[] originalBccRecipient = message.getRecipients(Message.RecipientType.BCC);
    String originalSubject = message.getSubject();

    // create the html for the string buffer.
    StringBuffer html = new StringBuffer();
    html.append("<html><body><table style=\"width: 100%;\"><tr><td>header</td><td>value</td></tr>");
    html.append("<tr><td>Subject:</td><td>").append(escape(originalSubject)).append("</td></tr>");

    // iterate over the addresses.
    if (originalFromRecipient != null) {
        for (int i = 0; i < originalFromRecipient.length; i++) {
            html.append("<tr><td>FROM:</td><td>").append(escape(originalFromRecipient[i])).append("</td></tr>");
        }/* w  w  w . j av  a  2  s. c  om*/
    }
    if (originalToRecipient != null) {
        for (int i = 0; i < originalToRecipient.length; i++) {
            html.append("<tr><td>TO:</td><td>").append(escape(originalToRecipient[i])).append("</td></tr>");
        }
    }
    if (originalCcRecipient != null) {
        for (int i = 0; i < originalCcRecipient.length; i++) {
            html.append("<tr><td>CC:</td><td>").append(escape(originalCcRecipient[i])).append("</td></tr>");
        }
    }
    if (originalBccRecipient != null) {
        for (int i = 0; i < originalBccRecipient.length; i++) {
            html.append("<tr><td>BCC:</td><td>").append(escape(originalBccRecipient[i])).append("</td></tr>");
        }
    }
    html.append("</table></body></html>");

    MimeBodyPart sentToBodyPart = new MimeBodyPart();
    sentToBodyPart.setContent(html.toString(), "text/html");
    sentToBodyPart.setHeader("Content-ID", "original-addresses");
    sentToBodyPart.setDisposition("inline");

    return sentToBodyPart;
}

From source file:org.wandora.piccolo.actions.SendEmail.java

public void doAction(User user, javax.servlet.ServletRequest request, javax.servlet.ServletResponse response,
        Application application) {/*ww  w .ja v  a2  s  .  c  o  m*/
    try {

        Properties props = new Properties();
        props.put("mail.smtp.host", smtpServer);
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage message = new MimeMessage(session);
        if (subject != null)
            message.setSubject(subject);
        if (from != null)
            message.setFrom(new InternetAddress(from));
        Vector<String> recipients = new Vector<String>();
        if (recipient != null) {
            String[] rs = recipient.split(",");
            String r = null;
            for (int i = 0; i < rs.length; i++) {
                r = rs[i];
                if (r != null)
                    recipients.add(r);
            }
        }

        MimeMultipart multipart = new MimeMultipart();

        Template template = application.getTemplate(emailTemplate, user);
        HashMap context = new HashMap();
        context.put("request", request);
        context.put("message", message);
        context.put("recipients", recipients);
        context.put("emailhelper", new MailHelper());
        context.put("multipart", multipart);
        context.putAll(application.getDefaultContext(user));

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        template.process(context, baos);

        MimeBodyPart mimeBody = new MimeBodyPart();
        mimeBody.setContent(new String(baos.toByteArray(), template.getEncoding()), template.getMimeType());
        //            mimeBody.setContent(baos.toByteArray(),template.getMimeType());
        multipart.addBodyPart(mimeBody);
        message.setContent(multipart);

        Transport transport = session.getTransport("smtp");
        transport.connect(smtpServer, smtpUser, smtpPass);
        Address[] recipientAddresses = new Address[recipients.size()];
        for (int i = 0; i < recipientAddresses.length; i++) {
            recipientAddresses[i] = new InternetAddress(recipients.elementAt(i));
        }
        transport.sendMessage(message, recipientAddresses);
    } catch (Exception e) {
        logger.writelog("WRN", e);
    }
}

From source file:org.sakaiproject.kernel.messaging.email.EmailMessageListener.java

/**
 * Attaches a file as a body part to the multipart message
 *
 * @param multipart/*from  w ww  .j  ava2s  .  c  o  m*/
 * @param attachment
 * @throws MessagingException
 */
private void addPart(Multipart multipart, Message msg) throws MessagingException {
    MimeBodyPart part = new MimeBodyPart();
    part.setContent(msg.getBody(), msg.getType());
    multipart.addBodyPart(part);
}