Example usage for javax.mail.internet MimeMessage setDataHandler

List of usage examples for javax.mail.internet MimeMessage setDataHandler

Introduction

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

Prototype

@Override
public synchronized void setDataHandler(DataHandler dh) throws MessagingException 

Source Link

Document

This method provides the mechanism to set this part's content.

Usage

From source file:org.protocoderrunner.apprunner.api.PNetwork.java

@ProtocoderScript
@APIMethod(description = "Send an E-mail. It requires passing a EmailConf object", example = "")
@APIParam(params = { "url", "function(data)" })
public void sendEmail(String from, String to, String subject, String text, final EmailConf emailSettings)
        throws AddressException, MessagingException {

    if (emailSettings == null) {
        return;//from w w  w  .  j  ava  2 s  .c o m
    }

    // final String host = "smtp.gmail.com";
    // final String address = "@gmail.com";
    // final String pass = "";

    Multipart multiPart;
    String finalString = "";

    Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", emailSettings.ttl);
    props.put("mail.smtp.host", emailSettings.host);
    props.put("mail.smtp.user", emailSettings.user);
    props.put("mail.smtp.password", emailSettings.password);
    props.put("mail.smtp.port", emailSettings.port);
    props.put("mail.smtp.auth", emailSettings.auth);

    Log.i("Check", "done pops");
    final Session session = Session.getDefaultInstance(props, null);
    DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain"));
    final MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.setDataHandler(handler);
    Log.i("Check", "done sessions");

    multiPart = new MimeMultipart();

    InternetAddress toAddress;
    toAddress = new InternetAddress(to);
    message.addRecipient(Message.RecipientType.TO, toAddress);
    Log.i("Check", "added recipient");
    message.setSubject(subject);
    message.setContent(multiPart);
    message.setText(text);

    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                MLog.i("check", "transport");
                Transport transport = session.getTransport("smtp");
                MLog.i("check", "connecting");
                transport.connect(emailSettings.host, emailSettings.user, emailSettings.password);
                MLog.i("check", "wana send");
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();

                MLog.i("check", "sent");

            } catch (AddressException e) {
                e.printStackTrace();
            } catch (MessagingException e) {
                e.printStackTrace();
            }

        }
    });
    t.start();

}

From source file:com.flexive.shared.FxMailUtils.java

/**
 * Sends an email//from  w w w. j ava2s .co m
 *
 * @param SMTPServer      IP Address of the SMTP server
 * @param subject         subject of the email
 * @param textBody        plain text
 * @param htmlBody        html text
 * @param to              recipient
 * @param cc              cc recepient
 * @param bcc             bcc recipient
 * @param from            sender
 * @param replyTo         reply-to address
 * @param mimeAttachments strings containing mime encoded attachments
 * @throws FxApplicationException on errors
 */
public static void sendMail(String SMTPServer, String subject, String textBody, String htmlBody, String to,
        String cc, String bcc, String from, String replyTo, String... mimeAttachments)
        throws FxApplicationException {

    try {
        // Set the mail server
        java.util.Properties properties = System.getProperties();
        if (SMTPServer != null)
            properties.put("mail.smtp.host", SMTPServer);

        // Get a session and create a new message
        javax.mail.Session session = javax.mail.Session.getInstance(properties, null);
        MimeMessage msg = new MimeMessage(session);

        // Set the sender
        if (StringUtils.isBlank(from))
            msg.setFrom(); // Uses local IP Adress and the user under which the server is running
        else {
            msg.setFrom(createAddress(from));
        }

        if (!StringUtils.isBlank(replyTo))
            msg.setReplyTo(encodePersonal(InternetAddress.parse(replyTo, false)));

        // Set the To, Cc and Bcc fields
        if (!StringUtils.isBlank(to))
            msg.setRecipients(MimeMessage.RecipientType.TO, encodePersonal(InternetAddress.parse(to, false)));
        if (!StringUtils.isBlank(cc))
            msg.setRecipients(MimeMessage.RecipientType.CC, encodePersonal(InternetAddress.parse(cc, false)));
        if (!StringUtils.isBlank(bcc))
            msg.setRecipients(MimeMessage.RecipientType.BCC, encodePersonal(InternetAddress.parse(bcc, false)));

        // Set the subject
        msg.setSubject(subject, "UTF-8");

        String sMainType = "Multipart/Alternative;\n\tboundary=\"" + BOUNDARY1 + "\"";

        StringBuilder body = new StringBuilder(5000);

        if (mimeAttachments.length > 0) {
            sMainType = "Multipart/Mixed;\n\tboundary=\"" + BOUNDARY2 + "\"";
            body.append("This is a multi-part message in MIME format.\n\n");
            body.append("--" + BOUNDARY2 + "\n");
            body.append("Content-Type: Multipart/Alternative;\n\tboundary=\"" + BOUNDARY1 + "\"\n\n\n");
        }

        if (textBody.length() > 0) {
            body.append("--" + BOUNDARY1 + "\n");
            body.append("Content-Type: text/plain; charset=\"UTF-8\"\n");
            body.append("Content-Transfer-Encoding: quoted-printable\n\n");
            body.append(encodeQuotedPrintable(textBody)).append("\n");
        }
        if (htmlBody.length() > 0) {
            body.append("--" + BOUNDARY1 + "\n");
            body.append("Content-Type: text/html;\n\tcharset=\"UTF-8\"\n");
            body.append("Content-Transfer-Encoding: quoted-printable\n\n");
            if (htmlBody.toLowerCase().indexOf("<html>") < 0) {
                body.append("<HTML><HEAD>\n<TITLE></TITLE>\n");
                body.append(
                        "<META http-equiv=3DContent-Type content=3D\"text/html; charset=3Dutf-8\"></HEAD>\n<BODY>\n");
                body.append(encodeQuotedPrintable(htmlBody)).append("</BODY></HTML>\n");
            } else
                body.append(encodeQuotedPrintable(htmlBody)).append("\n");
        }

        body.append("\n--" + BOUNDARY1 + "--\n");

        if (mimeAttachments.length > 0) {
            for (String mimeAttachment : mimeAttachments) {
                body.append("\n--" + BOUNDARY2 + "\n");
                body.append(mimeAttachment).append("\n");
            }
            body.append("\n--" + BOUNDARY2 + "--\n");
        }

        msg.setDataHandler(
                new javax.activation.DataHandler(new ByteArrayDataSource(body.toString(), sMainType)));

        // Set the header
        msg.setHeader("X-Mailer", "JavaMailer");

        // Set the sent date
        msg.setSentDate(new java.util.Date());

        // Send the message
        javax.mail.Transport.send(msg);
    } catch (AddressException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.address", e.getRef());
    } catch (javax.mail.MessagingException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage());
    } catch (IOException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage());
    } catch (EncoderException e) {
        throw new FxApplicationException(e, "ex.messaging.mail.send", e.getMessage());
    }
}

From source file:org.apache.camel.component.mail.MailBinding.java

protected String populateContentOnMimeMessage(MimeMessage part, MailConfiguration configuration,
        Exchange exchange) throws MessagingException, IOException {

    String contentType = determineContentType(configuration, exchange);

    if (LOG.isTraceEnabled()) {
        LOG.trace("Using Content-Type " + contentType + " for MimeMessage: " + part);
    }//  ww  w  .j a v  a 2  s  .co  m

    // always store content in a byte array data store to avoid various content type and charset issues
    DataSource ds = new ByteArrayDataSource(exchange.getIn().getBody(String.class), contentType);
    part.setDataHandler(new DataHandler(ds));

    // set the content type header afterwards
    part.setHeader("Content-Type", contentType);

    return contentType;
}