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:com.fiveamsolutions.nci.commons.util.MailUtils.java

/**
 * Send an email./*w w w  .jav a 2s  .com*/
 * @param u the recipient of the message
 * @param title the subject of the message
 * @param html the html content of the message
 * @param plainText the plain text content of the message
 * @throws MessagingException on error.
 */
public static void sendEmail(AbstractUser u, String title, String html, String plainText)
        throws MessagingException {
    if (!isMailEnabled()) {
        LOG.info("sending email to " + u.getEmail() + " with title " + title);
        LOG.info("plain text: " + plainText);
        LOG.info("html: " + html);
        return;
    }
    MimeMessage msg = new MimeMessage(getMailSession());
    msg.setFrom(new InternetAddress(getFromAddress()));
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(u.getEmail()));
    msg.setSubject(title);
    Multipart mp = new MimeMultipart("alternative");
    BodyPart bp = new MimeBodyPart();
    bp.setContent(html, "text/html");
    mp.addBodyPart(bp);

    bp = new MimeBodyPart();
    bp.setContent(plainText, "text/plain");
    mp.addBodyPart(bp);

    msg.setContent(mp);

    Transport.send(msg);
}

From source file:org.tizzit.util.mail.MailHelper.java

/**
 * Send an email in html-format in iso-8859-1-encoding
 * //from  w ww  .  j a  v a 2 s .  c  o m
 * @param subject the subject of the new mail
 * @param htmlMessage the content of the mail as html
 * @param alternativeTextMessage the content of the mail as text
 * @param from the sender-address
 * @param to the receiver-address
 * @param cc the address of the receiver of a copy of this mail
 * @param bcc the address of the receiver of a blind-copy of this mail
 */
public static void sendHtmlMail2(String subject, String htmlMessage, String alternativeTextMessage, String from,
        String to, String cc, String bcc) {
    try {
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(from));
        if (cc != null && !cc.equals(""))
            msg.setRecipients(Message.RecipientType.CC, cc);
        if (bcc != null && !bcc.equals(""))
            msg.setRecipients(Message.RecipientType.BCC, bcc);
        msg.addRecipients(Message.RecipientType.TO, to);
        msg.setSubject(subject, "ISO8859_1");
        msg.setSentDate(new Date());

        MimeMultipart multiPart = new MimeMultipart("alternative");
        MimeBodyPart htmlPart = new MimeBodyPart();
        MimeBodyPart textPart = new MimeBodyPart();

        textPart.setText(alternativeTextMessage, "ISO8859_1");
        textPart.setHeader("MIME-Version", "1.0");
        //textPart.setHeader("Content-Type", textPart.getContentType());
        textPart.setHeader("Content-Type", "text/plain;charset=\"ISO-8859-1\"");

        htmlPart.setContent(htmlMessage, "text/html;charset=\"ISO8859_1\"");
        htmlPart.setHeader("MIME-Version", "1.0");
        htmlPart.setHeader("Content-Type", "text/html;charset=\"ISO-8859-1\"");
        //htmlPart.setHeader("Content-Type", htmlPart.getContentType());

        multiPart.addBodyPart(textPart);
        multiPart.addBodyPart(htmlPart);

        multiPart.setSubType("alternative");

        msg.setContent(multiPart);
        msg.setHeader("MIME-Version", "1.0");
        msg.setHeader("Content-Type", multiPart.getContentType());

        Transport.send(msg);
    } catch (Exception e) {
        log.error("Error sending html-mail: " + e.getLocalizedMessage());
    }
}

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

public void addAttachement(final FormFile file) throws MessagingException {
    BodyPart attachement = new MimeBodyPart();
    attachement.setDataHandler(new DataHandler(new DataSource() {
        @Override//from w w  w  . j a v  a2  s  .c o  m
        public OutputStream getOutputStream() throws IOException {
            throw new IOException("No output stream.");
        }

        @Override
        public String getName() {
            return file.getFileName();
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return file.getInputStream();
        }

        @Override
        public String getContentType() {
            return file.getContentType();
        }
    }));
    attachement.setFileName(file.getFileName());
    iBody.addBodyPart(attachement);
}

From source file:org.nuxeo.ecm.automation.core.mail.Composer.java

public Mailer.Message newMixedMessage(String templateContent, Object ctx, String textType,
        List<Blob> attachments) throws TemplateException, IOException, MessagingException {
    if (textType == null) {
        textType = "plain";
    }/*from  www .  j  a va 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:ste.xtest.mail.BugFreeFileTransport.java

@Test
public void send_multipart_message() throws Exception {
    Session session = Session.getInstance(config);

    Message message = new MimeMessage(Session.getInstance(config));
    message.setFrom(new InternetAddress("from@domain.com"));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress("to@domain.com"));
    message.setSubject("the subject");
    MimeMultipart multipart = new MimeMultipart("related");

    BodyPart messageBodyPart = new MimeBodyPart();
    String htmlText = "<H1>hello world</H1><img src=\"cid:image\">";
    messageBodyPart.setContent(htmlText, "text/html");
    multipart.addBodyPart(messageBodyPart);
    messageBodyPart = new MimeBodyPart();
    DataSource fds = new FileDataSource("src/test/resources/images/6096.png");

    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image>");

    multipart.addBodyPart(messageBodyPart);
    message.setContent(multipart);//from  www . j  av  a  2  s .co  m

    session.getTransport().sendMessage(message, message.getAllRecipients());

    then(FileUtils.readFileToString(new File(TMP.getRoot(), "message"))).contains("From: from@domain.com\r")
            .contains("To: to@domain.com\r").contains("Subject: the subject\r").contains("hello world")
            .contains("Content-ID: <image>");
}

From source file:org.fireflow.service.email.send.MailSenderImpl.java

/**
 * TODO ?/*from  w ww.ja v a  2 s  .c  o  m*/
 * @param mailSession
 * @param mailMessage
 * @return
 * @throws MessagingException 
 * @throws AddressException 
 * @throws ServiceInvocationException
 */
private MimeMessage createMimeMessage(Session mailSession, MailMessage mailMessage)
        throws AddressException, MessagingException {
    MimeMessage mimeMsg = new MimeMessage(mailSession);

    //1?set from
    //Assert.notNull(mailMessage.getFrom(),"From address must not be null");
    mimeMsg.setFrom(new InternetAddress(mailMessage.getFrom()));

    //2?set mailto
    List<String> mailToList = mailMessage.getMailToList();
    InternetAddress[] addressList = new InternetAddress[mailToList.size()];
    for (int i = 0; i < mailToList.size(); i++) {
        String mailTo = mailToList.get(i);
        addressList[i] = new InternetAddress(mailTo);
    }
    mimeMsg.setRecipients(Message.RecipientType.TO, addressList);

    //3?set cc
    List<String> ccList = mailMessage.getCarbonCopyList();
    if (ccList != null && ccList.size() > 0) {
        addressList = new InternetAddress[ccList.size()];
        for (int i = 0; i < ccList.size(); i++) {
            String mailTo = ccList.get(i);
            addressList[i] = new InternetAddress(mailTo);
        }
        mimeMsg.setRecipients(Message.RecipientType.CC, addressList);
    }

    //4?set subject
    mimeMsg.setSubject(mailMessage.getSubject(), mailServiceDef.getCharset());

    //5?set sentDate
    if (this.sentDate != null) {
        mimeMsg.setSentDate(sentDate);
    }

    //6?set email body
    Multipart multiPart = new MimeMultipart();
    MimeBodyPart bp = new MimeBodyPart();
    if (mailMessage.getBodyIsHtml())
        bp.setContent(mailMessage.getBody(),
                CONTENT_TYPE_HTML + CONTENT_TYPE_CHARSET_SUFFIX + mailServiceDef.getCharset());
    else
        bp.setText(mailMessage.getBody(), mailServiceDef.getCharset());

    multiPart.addBodyPart(bp);
    mimeMsg.setContent(multiPart);

    //7?set attachment
    //TODO ?

    return mimeMsg;
}

From source file:com.nokia.helium.core.EmailDataSender.java

/**
 * Send xml data//from   w  w w. j ava2s. c om
 * 
 * @param String purpose of this email
 * @param String file to send
 * @param String mime type
 * @param String subject of email
 * @param String header of mail
 * @param boolean compress data if true
 */
public void sendData(String purpose, File fileToSend, String mimeType, String subject, String header,
        boolean compressData) throws EmailSendException {
    try {
        log.debug("sendData:Send file: " + fileToSend + " and mimetype: " + mimeType);
        if (fileToSend != null && fileToSend.exists()) {
            InternetAddress[] toAddresses = getToAddressList();
            Properties props = new Properties();
            if (smtpServerAddress != null) {
                log.debug("sendData:smtp address: " + smtpServerAddress);
                props.setProperty("mail.smtp.host", smtpServerAddress);
            }
            Session mailSession = Session.getDefaultInstance(props, null);
            MimeMessage message = new MimeMessage(mailSession);
            message.setSubject(subject == null ? "" : subject);
            MimeMultipart multipart = new MimeMultipart("related");
            BodyPart messageBodyPart = new MimeBodyPart();
            ByteArrayDataSource dataSrc = null;
            String fileName = fileToSend.getName();
            if (compressData) {
                log.debug("Sending compressed data");
                dataSrc = compressFile(fileToSend);
                dataSrc.setName(fileName + ".gz");
                messageBodyPart.setFileName(fileName + ".gz");
            } else {
                log.debug("Sending uncompressed data:");
                dataSrc = new ByteArrayDataSource(new FileInputStream(fileToSend), mimeType);

                message.setContent(FileUtils.readFileToString(fileToSend), "text/html");
                multipart = null;
            }
            String headerToSend = null;
            if (header == null) {
                headerToSend = "";
            }
            messageBodyPart.setHeader("helium-bld-data", headerToSend);
            messageBodyPart.setDataHandler(new DataHandler(dataSrc));

            if (multipart != null) {
                multipart.addBodyPart(messageBodyPart); // add to the
                // multipart
                message.setContent(multipart);
            }
            try {
                message.setFrom(getFromAddress());
            } catch (AddressException e) {
                throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e);
            } catch (LDAPException e) {
                throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e);
            }
            message.addRecipients(Message.RecipientType.TO, toAddresses);
            log.info("Sending email alert: " + subject);
            Transport.send(message);
        }
    } catch (MessagingException e) {
        String fullErrorMessage = "Failed sending e-mail: " + purpose;
        if (e.getMessage() != null) {
            fullErrorMessage += ": " + e.getMessage();
        }
        throw new EmailSendException(fullErrorMessage, e);
    } catch (IOException e) {
        String fullErrorMessage = "Failed sending e-mail: " + purpose;
        if (e.getMessage() != null) {
            fullErrorMessage += ": " + e.getMessage();
        }
        // We are Ignoring the errors as no need to fail the build.
        throw new EmailSendException(fullErrorMessage, e);
    }
}

From source file:com.haulmont.cuba.core.app.EmailSender.java

protected MimeBodyPart createAttachmentPart(SendingAttachment attachment) throws MessagingException {
    DataSource source = new MyByteArrayDataSource(attachment.getContent());

    String mimeType = FileTypesHelper.getMIMEType(attachment.getName());
    String encodedFileName = encodeAttachmentName(attachment);

    String contentId = attachment.getContentId();
    if (contentId == null) {
        contentId = encodedFileName;//from w  w w.  j a va2 s.c o  m
    }

    String disposition = attachment.getDisposition() != null ? attachment.getDisposition() : Part.INLINE;
    String charset = MimeUtility.mimeCharset(
            attachment.getEncoding() != null ? attachment.getEncoding() : StandardCharsets.UTF_8.name());
    String contentTypeValue = String.format("%s; charset=%s; name=\"%s\"", mimeType, charset, encodedFileName);

    MimeBodyPart attachmentPart = new MimeBodyPart();
    attachmentPart.setDataHandler(new DataHandler(source));
    attachmentPart.setHeader("Content-ID", "<" + contentId + ">");
    attachmentPart.setHeader("Content-Type", contentTypeValue);
    attachmentPart.setFileName(encodedFileName);
    attachmentPart.setDisposition(disposition);

    return attachmentPart;
}

From source file:org.entermedia.email.PostMail.java

public void postMail(List<InternetAddress> recipients, List<InternetAddress> blindrecipients, String subject,
        String inHtml, String inText, String from, List inAttachments, Map inProperties)
        throws MessagingException {
    // Set the host smtp address
    Properties props = new Properties();
    // create some properties and get the default Session
    props.put("mail.smtp.host", fieldSmtpServer);
    props.put("mail.smtp.port", String.valueOf(getPort()));
    props.put("mail.smtp.auth", new Boolean(fieldSmtpSecured).toString());
    if (isSslEnabled()) {
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    }/*from  ww w  .j a  va2s .co  m*/
    Session session = null;
    if (isEnableTls()) {
        props.put("mail.smtp.starttls.enable", "true");
        session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(getSmtpUsername(), getSmtpPassword());
            }
        });
    } else if (fieldSmtpSecured) {
        SmtpAuthenticator auth = new SmtpAuthenticator();
        session = Session.getInstance(props, auth);
    } else {
        session = Session.getInstance(props);
    }
    // session.setDebug(debug);

    // create a message
    Message msg = new MimeMessage(session);
    MimeMultipart mp = null;
    // msg.setDataHandler(new DataHandler(new ByteArrayDataSource(message,
    // "text/html")));

    if (inAttachments != null && inAttachments.size() == 0) {
        inAttachments = null;
    }

    if (inText != null && inHtml != null || inAttachments != null) {
        // Create an "Alternative" Multipart message
        mp = new MimeMultipart("mixed");

        if (inText != null) {
            BodyPart messageBodyPart = new MimeBodyPart();

            messageBodyPart.setContent(inText, "text/plain");
            mp.addBodyPart(messageBodyPart);
        }
        if (inHtml != null) {
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent(inHtml, "text/html");
            mp.addBodyPart(messageBodyPart);
        }
        if (inAttachments != null) {
            for (Iterator iterator = inAttachments.iterator(); iterator.hasNext();) {
                String filename = (String) iterator.next();

                File file = new File(filename);

                if (file.exists() && !file.isDirectory()) {
                    // create the second message part
                    MimeBodyPart mbp = new MimeBodyPart();

                    FileDataSource fds = new FileDataSource(file);
                    mbp.setDataHandler(new DataHandler(fds));

                    mbp.setFileName(fds.getName());

                    mp.addBodyPart(mbp);
                }
            }
        }

        msg.setContent(mp);

    } else if (inHtml != null) {
        msg.setContent(inHtml, "text/html");
    } else {
        msg.setContent(inText, "text/plain");
    }
    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);
    //msg.setRecipient(RecipientType.BCC, addressFrom);
    msg.setSentDate(new Date());
    if (recipients == null || recipients.isEmpty()) {
        throw new MessagingException("No recipients specified");
    }
    InternetAddress[] addressTo = recipients.toArray(new InternetAddress[recipients.size()]);

    msg.setRecipients(Message.RecipientType.TO, addressTo);

    //add bcc
    if (blindrecipients != null && !blindrecipients.isEmpty()) {
        InternetAddress[] addressBcc = blindrecipients.toArray(new InternetAddress[blindrecipients.size()]);
        msg.setRecipients(Message.RecipientType.BCC, addressBcc);
    }

    // Optional : You can also set your custom headers in the Email if you
    // Want
    // msg.addHeader("MyHeaderName", "myHeaderValue");
    // Setting the Subject and Content Type
    msg.setSubject(subject);

    // Transport tr = session.getTransport("smtp");
    // tr.connect(serverandport[0], null, null);
    // msg.saveChanges(); // don't forget this
    // tr.sendMessage(msg, msg.getAllRecipients());
    // tr.close();
    // msg.setContent(msg, "text/plain");

    Transport.send(msg);
    log.info("sent email " + subject);
}

From source file:com.aurel.track.util.emailHandling.MailBuilder.java

private void includeImageLogo(MimeMultipart mimeMultipart) {
    BodyPart messageBodyPart;/*w  w  w  . j  a v a 2  s . c o  m*/
    ArrayList<String> imageFiles = new ArrayList<String>();
    imageFiles.add("tracklogo.gif");
    // more images can be added here
    ArrayList<String> cids = new ArrayList<String>();
    cids.add("logo");
    // for each image there should be a cid here

    URL imageURL = null;
    for (int i = 0; i < imageFiles.size(); ++i) {
        try {
            DataSource ds = null;
            messageBodyPart = new MimeBodyPart();
            InputStream in = null;
            in = ImageAction.class.getClassLoader().getResourceAsStream(imageFiles.get(i));
            int length = imageFiles.get(i).length();
            String type = imageFiles.get(i).substring(length - 4, length - 1);
            if (in != null) {
                ds = new ByteArrayDataSource(in, "image/" + type);
                System.err.println(type);
            } else {
                String theResource = "/WEB-INF/classes/resources/MailTemplates/" + imageFiles.get(i);
                imageURL = servletContext.getResource(theResource);
                ds = new URLDataSource(imageURL);
            }
            messageBodyPart.setDataHandler(new DataHandler(ds));
            messageBodyPart.setHeader("Content-ID", cids.get(i));
            messageBodyPart.setDisposition("inline");
            // add it
            mimeMultipart.addBodyPart(messageBodyPart);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            // what shall we do here?
        }
    }
}