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:com.synyx.greetingcard.mail.OpenCmsMailService.java

public void sendMultipartMail(MessageConfig config, DataSource ds, String filename) throws MessagingException {
    log.debug("Sending multipart message " + config);

    Session session = getSession();//from   ww w  .  j a  va 2s.c  o  m
    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(ds));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);

    final MimeMessage message = new MimeMessage(session);
    message.setContent(multipart);
    try {
        message.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(config.getTo(), config.getToName()));
    } 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:org.openmrs.notification.mail.MailMessageSender.java

/**
 * Creates a MimeMultipart, so that we can have an attachment.
 *
 * @param message/*from   w  w  w.ja  v  a 2s .  c  o m*/
 * @return
 */
private MimeMultipart createMultipart(Message message) throws Exception {
    MimeMultipart toReturn = new MimeMultipart();

    MimeBodyPart textContent = new MimeBodyPart();
    textContent.setContent(message.getContent(), message.getContentType());

    MimeBodyPart attachment = new MimeBodyPart();
    attachment.setContent(message.getAttachment(), message.getAttachmentContentType());
    attachment.setFileName(message.getAttachmentFileName());

    toReturn.addBodyPart(textContent);
    toReturn.addBodyPart(attachment);

    return toReturn;
}

From source file:gwtupload.sendmailsample.server.SendMailSampleServlet.java

@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    try {//from  w ww .j  a  v  a  2s  .co  m
        String from = null, to = null, subject = "", body = "";
        // create a new multipart content
        MimeMultipart multiPart = new MimeMultipart();
        for (FileItem item : sessionFiles) {
            if (item.isFormField()) {
                if ("from".equals(item.getFieldName()))
                    from = item.getString();
                if ("to".equals(item.getFieldName()))
                    to = item.getString();
                if ("subject".equals(item.getFieldName()))
                    subject = item.getString();
                if ("body".equals(item.getFieldName()))
                    body = item.getString();
            } else {
                // add the file part to multipart content
                MimeBodyPart part = new MimeBodyPart();
                part.setFileName(item.getName());
                part.setDataHandler(
                        new DataHandler(new ByteArrayDataSource(item.get(), item.getContentType())));
                multiPart.addBodyPart(part);
            }
        }

        // add the text part to multipart content
        MimeBodyPart txtPart = new MimeBodyPart();
        txtPart.setContent(body, "text/plain");
        multiPart.addBodyPart(txtPart);

        // configure smtp server
        Properties props = System.getProperties();
        props.put("mail.smtp.host", SMTP_SERVER);
        // create a new mail session and the mime message
        MimeMessage mime = new MimeMessage(Session.getInstance(props));
        mime.setText(body);
        mime.setContent(multiPart);
        mime.setSubject(subject);
        mime.setFrom(new InternetAddress(from));
        for (String rcpt : to.split("[\\s;,]+"))
            mime.addRecipient(Message.RecipientType.TO, new InternetAddress(rcpt));
        // send the message
        Transport.send(mime);
    } catch (MessagingException e) {
        throw new UploadActionException(e.getMessage());
    }
    return "Your mail has been sent successfuly.";
}

From source file:org.roda.core.util.EmailUtility.java

/**
 * @param from/*  w  w w  .j  av a2 s.c o  m*/
 * @param recipients
 * @param subject
 * @param message
 * @throws MessagingException
 */
public void sendMail(String from, String recipients[], String subject, String message)
        throws MessagingException {
    boolean debug = false;

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", this.smtpHost);

    // create some properties and get the default Session
    Session session = Session.getDefaultInstance(props, null);
    session.setDebug(debug);

    // create a message
    Message msg = new MimeMessage(session);

    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++) {
        addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Optional : You can also set your custom headers in the Email if you
    // want
    // msg.addHeader("MyHeaderName", "myHeaderValue");

    String htmlMessage = String.format(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<html><body><pre>%s</pre></body></html>",
            StringEscapeUtils.escapeHtml4(message));

    MimeMultipart mimeMultipart = new MimeMultipart();
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setContent(htmlMessage, "text/html;charset=UTF-8");
    mimeMultipart.addBodyPart(mimeBodyPart);

    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(mimeMultipart);
    // msg.setContent(message, "text/plain;charset=UTF-8");
    Transport.send(msg);
}

From source file:com.formkiq.core.service.notification.ExternalMailSender.java

/**
 * Send Reset Email./*  w  w w . j av  a  2 s. c o m*/
 * @param to {@link String}
 * @param email {@link String}
 * @param subject {@link String}
 * @param text {@link String}
 * @param html {@link String}
 * @throws MessagingException MessagingException
 */
private void sendResetEmail(final String to, final String email, final String subject, final String text,
        final String html) throws MessagingException {

    String hostname = this.systemProperties.getSystemHostname();
    String resetToken = this.userservice.generateResetToken(to);

    StringSubstitutor s = new StringSubstitutor(
            ImmutableMap.of("hostname", hostname, "to", to, "email", email, "resettoken", resetToken));

    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setText(s.replace(text), "UTF-8");

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

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

    MimeMessage msg = this.mail.createMimeMessage();
    msg.setContent(mp);

    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

    msg.setSubject(subject);

    this.mail.send(msg);
}

From source file:ro.agrade.jira.qanda.listeners.DirectEmailMessageHandler.java

@Override
protected void sendMail(String[] recipients, String subject, String message, String from)
        throws MessagingException {

    SMTPMailServer server = mailServerManager.getDefaultSMTPMailServer();
    if (server == null) {
        LOG.debug("Email server is not configured. QandA is unable to send mails ...");
        return;/*www  . j  ava2s.co  m*/
    }
    LOG.debug("Email message: initializing.");
    //Set the host smtp address
    Properties props = new Properties();

    String proto = server.getMailProtocol().getProtocol();

    props.put("mail.transport.protocol", proto);
    props.put("mail." + proto + ".host", server.getHostname());
    props.put("mail." + proto + ".port", server.getPort());

    String username = server.getUsername();
    String password = server.getPassword();

    Authenticator auth = null;

    if (username != null && password != null) {
        auth = new SMTPAuthenticator(username, password);
        props.put("mail." + proto + ".auth", "true");
    }
    Session session;
    try {
        session = auth != null ? Session.getDefaultInstance(props, auth) : Session.getDefaultInstance(props);
    } catch (SecurityException ex) {
        LOG.warn("Could not get default session. Attempting to create a new one.");
        session = auth != null ? Session.getInstance(props, auth) : Session.getInstance(props);
    }

    // create a message
    MimeMessage msg = new MimeMessage(session);
    Multipart multipart = new MimeMultipart();

    if (from == null) {
        from = server.getDefaultFrom();
    }
    // set the from address
    if (from != null) {
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
    }

    if (recipients != null && recipients.length > 0) {
        // set TO address(es)
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
    }

    // Setting the Subject
    msg.setSubject(subject);

    // Setting text content
    MimeBodyPart contentPart = new MimeBodyPart();
    contentPart.setContent(message, "text/html; charset=utf-8");
    multipart.addBodyPart(contentPart);

    msg.setContent(multipart);
    Transport.send(msg);
    LOG.debug("Email message sent successfully.");
}

From source file:com.linkedin.r2.message.rest.QueryTunnelUtil.java

/**
 * Helper function to create multi-part MIME
 *
 * @param entity         the body of a request
 * @param entityContentType content type of the body
 * @param query          a query part of a request
 *
 * @return a ByteString that represents a multi-part encoded entity that contains both
 *///from   w  w w  .j a v a 2  s  .  com
private static MimeMultipart createMultiPartEntity(final ByteString entity, final String entityContentType,
        String query) throws MessagingException {
    MimeMultipart multi = new MimeMultipart(MIXED);

    // Create current entity with the associated type
    MimeBodyPart dataPart = new MimeBodyPart();

    ContentType contentType = new ContentType(entityContentType);
    if (MULTIPART.equals(contentType.getBaseType())) {
        MimeMultipart nested = new MimeMultipart(new DataSource() {
            @Override
            public InputStream getInputStream() throws IOException {
                return entity.asInputStream();
            }

            @Override
            public OutputStream getOutputStream() throws IOException {
                return null;
            }

            @Override
            public String getContentType() {
                return entityContentType;
            }

            @Override
            public String getName() {
                return null;
            }
        });
        dataPart.setContent(nested, contentType.getBaseType());

    } else {
        dataPart.setContent(entity.copyBytes(), contentType.getBaseType());
    }
    dataPart.setHeader(HEADER_CONTENT_TYPE, entityContentType);

    // Encode query params as form-urlencoded
    MimeBodyPart argPart = new MimeBodyPart();
    argPart.setContent(query, FORM_URL_ENCODED);
    argPart.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED);

    multi.addBodyPart(argPart);
    multi.addBodyPart(dataPart);
    return multi;
}

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

@Override
public void setBody(String message, String type) throws MessagingException {
    MimeBodyPart text = new MimeBodyPart();
    text.setContent(message, type);
    iBody.addBodyPart(text);/* ww w .j a v  a2 s  .  c o  m*/
}

From source file:com.anteam.alert.email.service.EmailAntlert.java

@Override
public boolean send(AntlertMessage antlertMsg) {

    MimeMessage mimeMsg; // MIME

    // from?to?//ww  w.  java2s  . c o  m
    mimeMsg = new javax.mail.internet.MimeMessage(mailSession);

    try {
        // ?
        mimeMsg.setFrom(sender);
        // 
        mimeMsg.setRecipients(RecipientType.TO, receivers);
        // 
        mimeMsg.setSubject(antlertMsg.getTitle(), CHARSET);

        // 
        MimeBodyPart messageBody = new MimeBodyPart();
        messageBody.setContent(antlertMsg.getContent(), CONTENT_MIME_TYPE);

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBody);
        mimeMsg.setContent(multipart);

        // ??
        mimeMsg.setSentDate(new Date());
        mimeMsg.saveChanges();

        // ??
        Transport.send(mimeMsg);
    } catch (MessagingException e) {
        logger.error("???", e);
        return false;
    }
    return true;
}

From source file:edu.ku.brc.helpers.EMailHelper.java

/**
 * Send an email. Also sends it as a gmail if applicable, and does password checking.
 * @param host host of SMTP server/*from w  w  w . j a  v a2  s.c  o  m*/
 * @param uName username of email account
 * @param pWord password of email account
 * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email
 * @param toEMailAddr the email addr of who this is going to
 * @param subject the Textual subject line of the email
 * @param bodyText the body text of the email (plain text???)
 * @param fileAttachment and optional file to be attached to the email
 * @return true if the msg was sent, false if not
 */
public static ErrorType sendMsg(final String host, final String uName, final String pWord,
        final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText,
        final String mimeType, final String port, final String security, final File fileAttachment) {
    String userName = uName;
    String password = pWord;

    if (StringUtils.isEmpty(toEMailAddr)) {
        UIRegistry.showLocalizedError("EMailHelper.NO_TO_ERR");
        return ErrorType.Error;
    }

    if (StringUtils.isEmpty(fromEMailAddr)) {
        UIRegistry.showLocalizedError("EMailHelper.NO_FROM_ERR");
        return ErrorType.Error;
    }

    //if (isGmailEmail())
    //{
    //    return sendMsgAsGMail(host, userName, password, fromEMailAddr, toEMailAddr, subject, bodyText, mimeType, port, security, fileAttachment);
    //}

    Boolean fail = false;
    ArrayList<String> userAndPass = new ArrayList<String>();

    boolean isSSL = security.equals("SSL");

    String[] keys = { "mail.smtp.host", "mail.smtp.port", "mail.smtp.auth", "mail.smtp.starttls.enable",
            "mail.smtp.socketFactory.port", "mail.smtp.socketFactory.class", "mail.smtp.socketFactory.fallback",
            "mail.imap.auth.plain.disable", };
    Properties props = System.getProperties();
    for (String key : keys) {
        props.remove(key);
    }

    props.put("mail.smtp.host", host); //$NON-NLS-1$

    if (StringUtils.isNotEmpty(port) && StringUtils.isNumeric(port)) {
        props.put("mail.smtp.port", port); //$NON-NLS-1$ //$NON-NLS-2$
    } else {
        props.remove("mail.smtp.port");
    }

    if (StringUtils.isNotEmpty(security)) {
        if (security.equals("TLS")) {
            props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$
            props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

        } else if (isSSL) {
            props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$

            String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            props.put("mail.smtp.socketFactory.port", port);
            props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.put("mail.smtp.socketFactory.fallback", "false");
            props.put("mail.imap.auth.plain.disable", "true");
        }
    }

    Session session = null;
    if (isSSL) {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(uName, pWord);
            }
        });

    } else {
        session = Session.getInstance(props, null);
    }

    session.setDebug(instance.isDebugging);
    if (instance.isDebugging) {
        log.debug("Host:     " + host); //$NON-NLS-1$
        log.debug("UserName: " + userName); //$NON-NLS-1$
        log.debug("Password: " + password); //$NON-NLS-1$
        log.debug("From:     " + fromEMailAddr); //$NON-NLS-1$
        log.debug("To:       " + toEMailAddr); //$NON-NLS-1$
        log.debug("Subject:  " + subject); //$NON-NLS-1$
        log.debug("Port:     " + port); //$NON-NLS-1$
        log.debug("Security: " + security); //$NON-NLS-1$
    }

    try {

        // create a message
        MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(fromEMailAddr));

        if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$
        {
            StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$
            InternetAddress[] address = new InternetAddress[st.countTokens()];
            int i = 0;
            while (st.hasMoreTokens()) {
                String toStr = st.nextToken().trim();
                address[i++] = new InternetAddress(toStr);
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        } else {
            try {
                InternetAddress[] address = { new InternetAddress(toEMailAddr) };
                msg.setRecipients(Message.RecipientType.TO, address);

            } catch (javax.mail.internet.AddressException ex) {
                UIRegistry.showLocalizedError("EMailHelper.TO_ADDR_ERR", toEMailAddr);
                return ErrorType.Error;
            }
        }
        msg.setSubject(subject);

        //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\"");

        // create the second message part
        if (fileAttachment != null) {
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\"");
            //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\"");

            MimeBodyPart mbp2 = new MimeBodyPart();

            // attach the file to the message
            FileDataSource fds = new FileDataSource(fileAttachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());

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

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

        } else {
            // add the Multipart to the message
            msg.setContent(bodyText, mimeType);
        }

        final int TRIES = 1;

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

        Exception exception = null;
        // send the message
        int cnt = 0;
        do {
            cnt++;
            SMTPTransport t = isSSL ? null : (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$
            try {
                if (isSSL) {
                    Transport.send(msg);

                } else {
                    t.connect(host, userName, password);
                    t.sendMessage(msg, msg.getAllRecipients());
                }

                fail = false;

            } catch (SendFailedException mex) {
                mex.printStackTrace();
                exception = mex;

            } catch (MessagingException mex) {
                if (mex.getCause() instanceof UnknownHostException) {
                    instance.lastErrorMsg = null;
                    fail = true;
                    UIRegistry.showLocalizedError("EMailHelper.UNK_HOST", host);

                } else if (mex.getCause() instanceof ConnectException) {
                    instance.lastErrorMsg = null;
                    fail = true;
                    UIRegistry.showLocalizedError(
                            "EMailHelper." + (StringUtils.isEmpty(port) ? "CNCT_ERR1" : "CNCT_ERR2"), port);

                } else {
                    mex.printStackTrace();
                    exception = mex;
                }

            } catch (Exception mex) {
                mex.printStackTrace();
                exception = mex;

            } finally {
                if (t != null) {
                    log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$
                    t.close();
                }
            }

            if (exception != null) {
                fail = true;

                instance.lastErrorMsg = exception.toString();

                //wrong username or password, get new one
                if (exception.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$
                {
                    UIRegistry.showLocalizedError("EMailHelper.UP_ERROR", userName);

                    userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow());

                    if (userAndPass == null) { //the user is done
                        instance.lastErrorMsg = null;
                        return ErrorType.Cancel;
                    }
                    userName = userAndPass.get(0);
                    password = userAndPass.get(1);
                }

            }
            exception = null;

        } while (fail && cnt < TRIES);

    } catch (Exception mex) {
        //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
        instance.lastErrorMsg = mex.toString();

        mex.printStackTrace();
        Exception ex = null;
        if (mex instanceof MessagingException && (ex = ((MessagingException) mex).getNextException()) != null) {
            ex.printStackTrace();
            instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
        }
        return ErrorType.Error;

    }

    if (fail) {
        return ErrorType.Error;
    } //else

    return ErrorType.OK;
}