Example usage for javax.mail Message setReplyTo

List of usage examples for javax.mail Message setReplyTo

Introduction

In this page you can find the example usage for javax.mail Message setReplyTo.

Prototype

public void setReplyTo(Address[] addresses) throws MessagingException 

Source Link

Document

Set the addresses to which replies should be directed.

Usage

From source file:com.threewks.thundr.mail.JavaMailMailer.java

@Override
protected void sendInternal(Map.Entry<String, String> from, Map.Entry<String, String> replyTo,
        Map<String, String> to, Map<String, String> cc, Map<String, String> bcc, String subject, Object body,
        List<Attachment> attachments) {
    try {/* w ww  . j a  v  a  2 s . c  o  m*/
        Session emailSession = getSession();

        Message message = new MimeMessage(emailSession);
        message.setFrom(emailAddress(from));
        if (replyTo != null) {
            message.setReplyTo(new Address[] { emailAddress(replyTo) });
        }

        message.setSubject(subject);

        BasicViewRenderer viewRenderer = render(body);
        String content = viewRenderer.getOutputAsString();
        String contentType = ContentType.cleanContentType(viewRenderer.getContentType());
        contentType = StringUtils.isBlank(contentType) ? ContentType.TextHtml.value() : contentType;

        if (Expressive.isEmpty(attachments)) {
            message.setContent(content, contentType);
        } else {
            Multipart multipart = new MimeMultipart("mixed"); // subtype must be "mixed" or inline & regular attachments won't play well together
            addBody(multipart, content, contentType);
            addAttachments(multipart, attachments);
            message.setContent(multipart);
        }

        addRecipients(to, message, RecipientType.TO);
        addRecipients(cc, message, RecipientType.CC);
        addRecipients(bcc, message, RecipientType.BCC);

        sendMessage(message);
    } catch (MessagingException e) {
        throw new MailException(e, "Failed to send an email: %s", e.getMessage());
    }
}

From source file:contestWebsite.ContactUs.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Query query = new Query("user")
            .setFilter(new FilterPredicate("name", FilterOperator.EQUAL, req.getParameter("name")));
    List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(3));
    Entity feedback = new Entity("feedback");
    if (users.size() != 0) {
        feedback.setProperty("user-id", users.get(0).getProperty("user-id"));
    }// ww w .jav  a2s  . com

    String name = escapeHtml4(req.getParameter("name"));
    String school = escapeHtml4(req.getParameter("school"));
    String comment = escapeHtml4(req.getParameter("text"));
    String email = escapeHtml4(req.getParameter("email"));

    HttpSession sess = req.getSession(true);
    sess.setAttribute("name", name);
    sess.setAttribute("school", school);
    sess.setAttribute("email", email);
    sess.setAttribute("comment", comment);

    Entity contestInfo = Retrieve.contestInfo();
    if (!(Boolean) sess.getAttribute("nocaptcha")) {
        URL reCaptchaURL = new URL("https://www.google.com/recaptcha/api/siteverify");
        String charset = java.nio.charset.StandardCharsets.UTF_8.name();
        String reCaptchaQuery = String.format("secret=%s&response=%s&remoteip=%s",
                URLEncoder.encode((String) contestInfo.getProperty("privateKey"), charset),
                URLEncoder.encode(req.getParameter("g-recaptcha-response"), charset),
                URLEncoder.encode(req.getRemoteAddr(), charset));

        final URLConnection connection = new URL(reCaptchaURL + "?" + reCaptchaQuery).openConnection();
        connection.setRequestProperty("Accept-Charset", charset);
        String response = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() {
            @Override
            public InputStream getInput() throws IOException {
                return connection.getInputStream();
            }
        }, Charsets.UTF_8));

        try {
            JSONObject JSONResponse = new JSONObject(response);
            if (!JSONResponse.getBoolean("success")) {
                resp.sendRedirect("/contactUs?captchaError=1");
                return;
            }
        } catch (JSONException e) {
            e.printStackTrace();
            resp.sendRedirect("/contactUs?captchaError=1");
            return;
        }
    }

    feedback.setProperty("name", name);
    feedback.setProperty("school", school);
    feedback.setProperty("email", email);
    feedback.setProperty("comment", new Text(comment));
    feedback.setProperty("resolved", false);

    Transaction txn = datastore.beginTransaction();
    try {
        datastore.put(feedback);
        txn.commit();

        Session session = Session.getDefaultInstance(new Properties(), null);
        String appEngineEmail = (String) contestInfo.getProperty("account");

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(appEngineEmail, "Tournament Website Admin"));
            msg.addRecipient(Message.RecipientType.TO,
                    new InternetAddress((String) contestInfo.getProperty("email"), "Contest Administrator"));
            msg.setSubject("Question about tournament from " + name);
            msg.setReplyTo(new InternetAddress[] { new InternetAddress(req.getParameter("email"), name),
                    new InternetAddress(appEngineEmail, "Tournament Website Admin") });

            VelocityEngine ve = new VelocityEngine();
            ve.init();

            VelocityContext context = new VelocityContext();
            context.put("name", name);
            context.put("email", email);
            context.put("school", school);
            context.put("message", comment);

            StringWriter sw = new StringWriter();
            Velocity.evaluate(context, sw, "questionEmail",
                    ((Text) contestInfo.getProperty("questionEmail")).getValue());
            msg.setContent(sw.toString(), "text/html");
            Transport.send(msg);
        } catch (MessagingException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
            return;
        }

        resp.sendRedirect("/contactUs?updated=1");
        sess.invalidate();
    } catch (Exception e) {
        e.printStackTrace();
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
    } finally {
        if (txn.isActive()) {
            txn.rollback();
        }
    }
}

From source file:org.nuxeo.labs.operations.notification.AdvancedSendEmail.java

protected void addReplyToEmails(Message msg) throws ClientException, MessagingException {

    if (replyto == null) {
        return;// www. j a v  a  2 s. com
    }

    if ("".equals(replyto)) {
        return;
    }

    List<String> emails = getEmails(replyto, "ReplyTo");
    Address[] replyToValue = new InternetAddress[emails.size()];
    for (int i = 0; i < emails.size(); i++) {
        replyToValue[i] = new InternetAddress(emails.get(i));
    }
    msg.setReplyTo(replyToValue);
}

From source file:org.apache.hupa.server.handler.AbstractFetchMessagesHandler.java

protected ArrayList<org.apache.hupa.shared.data.Message> convert(int offset,
        com.sun.mail.imap.IMAPFolder folder, Message[] messages) throws MessagingException {
    ArrayList<org.apache.hupa.shared.data.Message> mList = new ArrayList<org.apache.hupa.shared.data.Message>();
    // Setup fetchprofile to limit the stuff which is fetched 
    FetchProfile fp = new FetchProfile();
    fp.add(FetchProfile.Item.ENVELOPE);/* www  .j a va 2  s.co m*/
    fp.add(FetchProfile.Item.FLAGS);
    fp.add(FetchProfile.Item.CONTENT_INFO);
    fp.add(UIDFolder.FetchProfileItem.UID);
    folder.fetch(messages, fp);

    // loop over the fetched messages
    for (int i = 0; i < messages.length && i < offset; i++) {
        org.apache.hupa.shared.data.Message msg = new org.apache.hupa.shared.data.Message();
        Message m = messages[i];
        String from = null;
        if (m.getFrom() != null && m.getFrom().length > 0) {
            from = MessageUtils.decodeText(m.getFrom()[0].toString());
        }
        msg.setFrom(from);

        String replyto = null;
        if (m.getReplyTo() != null && m.getReplyTo().length > 0) {
            replyto = MessageUtils.decodeText(m.getReplyTo()[0].toString());
        }
        msg.setReplyto(replyto);

        ArrayList<String> to = new ArrayList<String>();
        // Add to addresses
        Address[] toArray = m.getRecipients(RecipientType.TO);
        if (toArray != null) {
            for (Address addr : toArray) {
                String mailTo = MessageUtils.decodeText(addr.toString());
                to.add(mailTo);
            }
        }
        msg.setTo(to);

        // Check if a subject exist and if so decode it
        String subject = m.getSubject();
        if (subject != null) {
            subject = MessageUtils.decodeText(subject);
        }
        msg.setSubject(subject);

        // Add cc addresses
        Address[] ccArray = m.getRecipients(RecipientType.CC);
        ArrayList<String> cc = new ArrayList<String>();
        if (ccArray != null) {
            for (Address addr : ccArray) {
                String mailCc = MessageUtils.decodeText(addr.toString());
                cc.add(mailCc);
            }
        }
        msg.setCc(cc);

        userPreferences.addContact(from);
        userPreferences.addContact(to);
        userPreferences.addContact(replyto);
        userPreferences.addContact(cc);

        // Using sentDate since received date is not useful in the view when using fetchmail
        msg.setReceivedDate(m.getSentDate());

        // Add flags
        ArrayList<IMAPFlag> iFlags = JavamailUtil.convert(m.getFlags());

        ArrayList<Tag> tags = new ArrayList<Tag>();
        for (String flag : m.getFlags().getUserFlags()) {
            if (flag.startsWith(Tag.PREFIX)) {
                tags.add(new Tag(flag.substring(Tag.PREFIX.length())));
            }
        }

        msg.setUid(folder.getUID(m));
        msg.setFlags(iFlags);
        msg.setTags(tags);
        try {
            msg.setHasAttachments(hasAttachment(m));
        } catch (MessagingException e) {
            logger.debug("Unable to identify attachments in message UID:" + msg.getUid() + " subject:"
                    + msg.getSubject() + " cause:" + e.getMessage());
            logger.info("");
        }
        mList.add(0, msg);

    }
    return mList;
}

From source file:uk.ac.cam.cl.dtg.util.Mailer.java

/**
 * @param recipient//from  w  ww.j  a va2  s .  co m
 *            - 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
 *            - the e-mail address that should be used as the reply-to address
 * @param subject
 *            - The message subject
 * @return a newly created message with all of the headers populated.
 * @throws MessagingException - if there is an error in setting up the message
 */
private Message setupMessage(final String[] recipient, final String from, @Nullable final String replyTo,
        @Nullable final String replyToName, final String subject)
        throws MessagingException, UnsupportedEncodingException {
    Validate.notEmpty(recipient);
    Validate.notBlank(recipient[0]);
    Validate.notBlank(from);

    Properties p = new Properties();
    p.put("mail.smtp.host", smtpAddress);

    if (null != smtpPort) {
        p.put("mail.smtp.port", smtpPort);
    }

    p.put("mail.smtp.starttls.enable", "true");

    Session s = Session.getDefaultInstance(p);
    Message msg = new MimeMessage(s);

    InternetAddress sentBy = null;
    InternetAddress[] sender = new InternetAddress[1];
    InternetAddress[] recievers = new InternetAddress[recipient.length];

    sentBy = new InternetAddress(mailAddress, mailName);
    sender[0] = new InternetAddress(from);
    for (int i = 0; i < recipient.length; i++) {
        recievers[i] = new InternetAddress(recipient[i]);
    }

    if (sentBy != null && sender != null && recievers != null) {
        msg.setFrom(sentBy);
        msg.setRecipients(RecipientType.TO, recievers);
        msg.setSubject(subject);

        if (null != replyTo && null != replyToName) {
            msg.setReplyTo(new InternetAddress[] { new InternetAddress(replyTo, replyToName) });
        }
    }
    return msg;
}

From source file:com.clustercontrol.jobmanagement.util.SendApprovalMail.java

/**
 * ????/*from   w w  w  .  j  av  a  2  s.  c o m*/
 * @param toAddressStr
 *            ?To
 * @param ccAddressStr
 *            ?Cc
 * @param subject
 *            ??
 * @param content
 *            
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 */

public void sendMail(String[] toAddressStr, String[] ccAddressStr, String subject, String content)
        throws MessagingException, UnsupportedEncodingException {

    if (toAddressStr == null || toAddressStr.length <= 0) {
        // ??
        return;
    }
    /*
     *  https://javamail.java.net/nonav/docs/api/com/sun/mail/smtp/package-summary.html
     */
    Properties _properties = new Properties();
    _properties.setProperty("mail.debug",
            Boolean.toString(HinemosPropertyUtil.getHinemosPropertyBool("mail.debug", false)));
    _properties.setProperty("mail.store.protocol",
            HinemosPropertyUtil.getHinemosPropertyStr("mail.store.protocol", "pop3"));
    String protocol = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.protocol", "smtp");
    _properties.setProperty("mail.transport.protocol", protocol);
    _properties.put("mail.smtp.socketFactory", javax.net.SocketFactory.getDefault());
    _properties.put("mail.smtp.ssl.socketFactory", javax.net.ssl.SSLSocketFactory.getDefault());

    setProperties(_properties, "mail." + protocol + ".user", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".host", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".port", HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".connectiontimeout",
            HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".timeout", HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".writetimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".from", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".localhost", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".localaddress", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".localport", HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".ehlo", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth.mechanisms",
            HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".auth.login.disable",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth.plain.disable",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth.digest-md5.disable",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth.ntlm.disable",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth.ntlm.domain",
            HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".auth.ntlm.flags",
            HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".submitter", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".dsn.notify", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".dsn.ret", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".allow8bitmime", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".sendpartial", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".sasl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".sasl.mechanisms",
            HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".sasl.authorizationid",
            HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".sasl.realm", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".sasl.usecanonicalhostname",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".quitwait", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".reportsuccess", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".socketFactory.class",
            HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".socketFactory.fallback",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".socketFactory.port",
            HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".starttls.enable", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".starttls.required",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".socks.host", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".socks.port", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".mailextension", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".userset", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".noop.strict", HinemosPropertyTypeConstant.TYPE_TRUTH);

    setProperties(_properties, "mail.smtp.ssl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail.smtp.ssl.checkserveridentity", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail.smtp.ssl.trust", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail.smtp.ssl.socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail.smtp.ssl.socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail.smtp.ssl.protocols", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail.smtp.ssl.ciphersuites", HinemosPropertyTypeConstant.TYPE_STRING);

    /**
     * ?DB??
     */
    String _loginUser = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.user", "nobody");
    String _loginPassword = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.password", "password");
    String _fromAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.address", "admin@hinemos.com");
    String _fromPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.personal.name",
            "Hinemos Admin");
    _fromPersonalName = convertNativeToAscii(_fromPersonalName);

    String _replyToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.to.address",
            "admin@hinemos.com");
    String _replyToPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.personal.name",
            "Hinemos Admin");
    _replyToPersonalName = convertNativeToAscii(_replyToPersonalName);

    String _errorsToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.errors.to.address",
            "admin@hinemos.com");

    int _transportTries = HinemosPropertyUtil.getHinemosPropertyNum("mail.transport.tries", Long.valueOf(1))
            .intValue();
    int _transportTriesInterval = HinemosPropertyUtil
            .getHinemosPropertyNum("mail.transport.tries.interval", Long.valueOf(10000)).intValue();

    String _charsetAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.address",
            _charsetAddressDefault);
    String _charsetSubject = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.subject",
            _charsetSubjectDefault);
    String _charsetContent = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.content",
            _charsetContentDefault);

    m_log.debug("initialized mail sender : from_address = " + _fromAddress + ", From = " + _fromPersonalName
            + " <" + _replyToAddress + ">" + ", Reply-To = " + _replyToPersonalName + " <" + _replyToAddress
            + ">" + ", Errors-To = " + _errorsToAddress + ", tries = " + _transportTries + ", tries-interval = "
            + _transportTriesInterval + ", Charset [address:subject:content] = [" + _charsetAddress + ":"
            + _charsetSubject + ":" + _charsetContent + "]");

    // JavaMail Session
    Session session = Session.getInstance(_properties);

    Message mineMsg = new MimeMessage(session);

    // ?????
    if (_fromAddress != null && _fromPersonalName != null) {
        mineMsg.setFrom(new InternetAddress(_fromAddress, _fromPersonalName, _charsetAddress));
    } else if (_fromAddress != null && _fromPersonalName == null) {
        mineMsg.setFrom(new InternetAddress(_fromAddress));
    }

    // REPLY-TO
    if (_replyToAddress != null && _replyToPersonalName != null) {
        InternetAddress reply[] = {
                new InternetAddress(_replyToAddress, _replyToPersonalName, _charsetAddress) };
        mineMsg.setReplyTo(reply);
        mineMsg.reply(true);
    } else if (_replyToAddress != null && _replyToPersonalName == null) {
        InternetAddress reply[] = { new InternetAddress(_replyToAddress) };
        mineMsg.setReplyTo(reply);
        mineMsg.reply(true);
    }

    // ERRORS-TO
    if (_errorsToAddress != null) {
        mineMsg.setHeader("Errors-To", _errorsToAddress);
    }

    // ?
    // TO
    InternetAddress[] toAddress = this.getAddress(toAddressStr);
    if (toAddress != null && toAddress.length > 0) {
        mineMsg.setRecipients(javax.mail.Message.RecipientType.TO, toAddress);
    } else {
        return; // TO?
    }

    // CC
    if (ccAddressStr != null) {
        InternetAddress[] ccAddress = this.getAddress(ccAddressStr);
        if (ccAddress != null && ccAddress.length > 0) {
            mineMsg.setRecipients(javax.mail.Message.RecipientType.CC, ccAddress);
        }
    }
    String message = "TO=" + Arrays.asList(toAddressStr);

    if (ccAddressStr != null) {
        message += ", CC=" + Arrays.asList(ccAddressStr);
    }
    m_log.debug(message);

    // ???
    mineMsg.setSubject(MimeUtility.encodeText(subject, _charsetSubject, "B"));

    // ?
    mineMsg.setContent(content, "text/plain; charset=" + _charsetContent);

    // ?
    mineMsg.setSentDate(HinemosTime.getDateInstance());

    // ???true??????
    for (int i = 0; i < _transportTries; i++) {
        Transport transport = null;
        try {
            // ?
            transport = session.getTransport();
            boolean flag = HinemosPropertyUtil.getHinemosPropertyBool("mail." + protocol + ".auth", false);
            if (flag) {
                transport.connect(_loginUser, _loginPassword);
            } else {
                transport.connect();
            }
            transport.sendMessage(mineMsg, mineMsg.getAllRecipients());
            break;
        } catch (AuthenticationFailedException e) {
            throw e;
        } catch (SMTPAddressFailedException e) {
            throw e;
        } catch (MessagingException me) {
            //_transportTries?sleep??? 
            if (i < (_transportTries - 1)) {
                m_log.info("sendMail() : retry sendmail. " + me.getMessage());
                try {
                    Thread.sleep(_transportTriesInterval);
                } catch (InterruptedException e) {
                }
                //_transportTries??INTERNAL????Exceptionthrow 
            } else {
                throw me;
            }
        } finally {
            if (transport != null) {
                transport.close();
            }
        }
    }
}

From source file:com.clustercontrol.notify.util.SendMail.java

public void sendMail(String[] toAddressStr, String[] ccAddressStr, String[] bccAddressStr, String subject,
        String content) throws MessagingException, UnsupportedEncodingException {

    if (toAddressStr == null || toAddressStr.length <= 0) {
        // ??/*  w w w .  java  2s.  c o m*/
        return;
    }

    /*
     *  https://javamail.java.net/nonav/docs/api/com/sun/mail/smtp/package-summary.html
     */
    Properties _properties = new Properties();
    _properties.setProperty("mail.debug",
            Boolean.toString(HinemosPropertyUtil.getHinemosPropertyBool("mail.debug", false)));
    _properties.setProperty("mail.store.protocol",
            HinemosPropertyUtil.getHinemosPropertyStr("mail.store.protocol", "pop3"));
    String protocol = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.protocol", "smtp");
    _properties.setProperty("mail.transport.protocol", protocol);
    _properties.put("mail.smtp.socketFactory", javax.net.SocketFactory.getDefault());
    _properties.put("mail.smtp.ssl.socketFactory", javax.net.ssl.SSLSocketFactory.getDefault());

    setProperties(_properties, "mail." + protocol + ".user", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".host", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".port", HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".connectiontimeout",
            HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".timeout", HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".writetimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".from", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".localhost", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".localaddress", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".localport", HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".ehlo", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth.mechanisms",
            HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".auth.login.disable",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth.plain.disable",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth.digest-md5.disable",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth.ntlm.disable",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".auth.ntlm.domain",
            HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".auth.ntlm.flags",
            HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".submitter", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".dsn.notify", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".dsn.ret", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".allow8bitmime", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".sendpartial", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".sasl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".sasl.mechanisms",
            HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".sasl.authorizationid",
            HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".sasl.realm", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".sasl.usecanonicalhostname",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".quitwait", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".reportsuccess", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".socketFactory.class",
            HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".socketFactory.fallback",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".socketFactory.port",
            HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail." + protocol + ".starttls.enable", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".starttls.required",
            HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".socks.host", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".socks.port", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".mailextension", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail." + protocol + ".userset", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail." + protocol + ".noop.strict", HinemosPropertyTypeConstant.TYPE_TRUTH);

    setProperties(_properties, "mail.smtp.ssl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail.smtp.ssl.checkserveridentity", HinemosPropertyTypeConstant.TYPE_TRUTH);
    setProperties(_properties, "mail.smtp.ssl.trust", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail.smtp.ssl.socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail.smtp.ssl.socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC);
    setProperties(_properties, "mail.smtp.ssl.protocols", HinemosPropertyTypeConstant.TYPE_STRING);
    setProperties(_properties, "mail.smtp.ssl.ciphersuites", HinemosPropertyTypeConstant.TYPE_STRING);

    /**
     * ?DB??
     */
    String _loginUser = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.user", "nobody");
    String _loginPassword = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.password", "password");
    String _fromAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.address", "admin@hinemos.com");
    String _fromPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.personal.name",
            "Hinemos Admin");
    _fromPersonalName = convertNativeToAscii(_fromPersonalName);

    String _replyToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.to.address",
            "admin@hinemos.com");
    String _replyToPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.personal.name",
            "Hinemos Admin");
    _replyToPersonalName = convertNativeToAscii(_replyToPersonalName);

    String _errorsToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.errors.to.address",
            "admin@hinemos.com");

    int _transportTries = HinemosPropertyUtil.getHinemosPropertyNum("mail.transport.tries", Long.valueOf(1))
            .intValue();
    int _transportTriesInterval = HinemosPropertyUtil
            .getHinemosPropertyNum("mail.transport.tries.interval", Long.valueOf(10000)).intValue();

    String _charsetAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.address",
            _charsetAddressDefault);
    String _charsetSubject = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.subject",
            _charsetSubjectDefault);
    String _charsetContent = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.content",
            _charsetContentDefault);

    m_log.debug("initialized mail sender : from_address = " + _fromAddress + ", From = " + _fromPersonalName
            + " <" + _replyToAddress + ">" + ", Reply-To = " + _replyToPersonalName + " <" + _replyToAddress
            + ">" + ", Errors-To = " + _errorsToAddress + ", tries = " + _transportTries + ", tries-interval = "
            + _transportTriesInterval + ", Charset [address:subject:content] = [" + _charsetAddress + ":"
            + _charsetSubject + ":" + _charsetContent + "]");

    // JavaMail Session
    Session session = Session.getInstance(_properties);

    Message mineMsg = new MimeMessage(session);

    // ?????
    if (_fromAddress != null && _fromPersonalName != null) {
        mineMsg.setFrom(new InternetAddress(_fromAddress, _fromPersonalName, _charsetAddress));
    } else if (_fromAddress != null && _fromPersonalName == null) {
        mineMsg.setFrom(new InternetAddress(_fromAddress));
    }
    // REPLY-TO
    if (_replyToAddress != null && _replyToPersonalName != null) {
        InternetAddress reply[] = {
                new InternetAddress(_replyToAddress, _replyToPersonalName, _charsetAddress) };
        mineMsg.setReplyTo(reply);
        mineMsg.reply(true);
    } else if (_replyToAddress != null && _replyToPersonalName == null) {
        InternetAddress reply[] = { new InternetAddress(_replyToAddress) };
        mineMsg.setReplyTo(reply);
        mineMsg.reply(true);
    }

    // ERRORS-TO
    if (_errorsToAddress != null) {
        mineMsg.setHeader("Errors-To", _errorsToAddress);
    }

    // ?
    // TO
    InternetAddress[] toAddress = this.getAddress(toAddressStr);
    if (toAddress != null && toAddress.length > 0) {
        mineMsg.setRecipients(javax.mail.Message.RecipientType.TO, toAddress);
    } else {
        return; // TO?
    }
    // CC
    if (ccAddressStr != null) {
        InternetAddress[] ccAddress = this.getAddress(ccAddressStr);
        if (ccAddress != null && ccAddress.length > 0) {
            mineMsg.setRecipients(javax.mail.Message.RecipientType.CC, ccAddress);
        }
    }
    // BCC
    if (bccAddressStr != null) {
        InternetAddress[] bccAddress = this.getAddress(bccAddressStr);
        if (bccAddress != null && bccAddress.length > 0) {
            mineMsg.setRecipients(javax.mail.Message.RecipientType.BCC, bccAddress);
        }
    }
    String message = "TO=" + Arrays.asList(toAddressStr);

    if (ccAddressStr != null) {
        message += ", CC=" + Arrays.asList(ccAddressStr);
    }
    if (bccAddressStr != null) {
        message += ", BCC=" + Arrays.asList(bccAddressStr);
    }
    m_log.debug(message);

    // ???
    mineMsg.setSubject(MimeUtility.encodeText(subject, _charsetSubject, "B"));

    // ?
    mineMsg.setContent(content, "text/plain; charset=" + _charsetContent);

    // ?
    mineMsg.setSentDate(HinemosTime.getDateInstance());

    // ???true??????
    for (int i = 0; i < _transportTries; i++) {
        Transport transport = null;
        try {
            // ?
            transport = session.getTransport();
            boolean flag = HinemosPropertyUtil.getHinemosPropertyBool("mail." + protocol + ".auth", false);
            if (flag) {
                transport.connect(_loginUser, _loginPassword);
            } else {
                transport.connect();
            }
            transport.sendMessage(mineMsg, mineMsg.getAllRecipients());
            break;
        } catch (AuthenticationFailedException e) {
            throw e;
        } catch (SMTPAddressFailedException e) {
            throw e;
        } catch (MessagingException me) {
            //_transportTries?sleep??? 
            if (i < (_transportTries - 1)) {
                m_log.info("sendMail() : retry sendmail. " + me.getMessage());
                try {
                    Thread.sleep(_transportTriesInterval);
                } catch (InterruptedException e) {
                }
                //_transportTries??INTERNAL????Exceptionthrow 
            } else {
                throw me;
            }
        } finally {
            if (transport != null) {
                transport.close();
            }
        }
    }
}

From source file:com.panet.imeta.trans.steps.mail.Mail.java

public void sendMail(Object[] r, String server, String port, String senderAddress, String senderName,
        String destination, String destinationCc, String destinationBCc, String contactPerson,
        String contactPhone, String authenticationUser, String authenticationPassword, String mailsubject,
        String comment, String replyToAddresses) throws Exception {

    // Send an e-mail...
    // create some properties and get the default Session

    String protocol = "smtp";
    if (meta.isUsingAuthentication()) {
        if (meta.getSecureConnectionType().equals("TLS")) {
            // Allow TLS authentication
            data.props.put("mail.smtp.starttls.enable", "true");
        } else {//from   w  w  w  .  j  a  v  a  2  s . c o  m
            protocol = "smtps";
            // required to get rid of a SSL exception :
            //  nested exception is:
            //  javax.net.ssl.SSLException: Unsupported record version Unknown
            data.props.put("mail.smtps.quitwait", "false");
        }
    }
    data.props.put("mail." + protocol + ".host", server);
    if (!Const.isEmpty(port))
        data.props.put("mail." + protocol + ".port", port);
    boolean debug = log.getLogLevel() >= LogWriter.LOG_LEVEL_DEBUG;

    if (debug)
        data.props.put("mail.debug", "true");

    if (meta.isUsingAuthentication())
        data.props.put("mail." + protocol + ".auth", "true");

    Session session = Session.getInstance(data.props);
    session.setDebug(debug);

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

    // set message priority
    if (meta.isUsePriority()) {
        String priority_int = "1";
        if (meta.getPriority().equals("low"))
            priority_int = "3";
        if (meta.getPriority().equals("normal"))
            priority_int = "2";

        msg.setHeader("X-Priority", priority_int); //(String)int between 1= high and 3 = low.
        msg.setHeader("Importance", meta.getImportance());
        //seems to be needed for MS Outlook.
        //where it returns a string of high /normal /low.
    }

    // set Email sender
    String email_address = senderAddress;
    if (!Const.isEmpty(email_address)) {
        // get sender name
        if (!Const.isEmpty(senderName))
            email_address = senderName + '<' + email_address + '>';
        msg.setFrom(new InternetAddress(email_address));
    } else {
        throw new MessagingException(Messages.getString("Mail.Error.ReplyEmailNotFilled"));
    }

    // Set reply to 
    if (!Const.isEmpty(replyToAddresses)) {
        // get replay to
        // Split the mail-address: space separated
        String[] reply_Address_List = replyToAddresses.split(" ");
        InternetAddress[] address = new InternetAddress[reply_Address_List.length];

        for (int i = 0; i < reply_Address_List.length; i++)
            address[i] = new InternetAddress(reply_Address_List[i]);

        // To add the real reply-to 
        msg.setReplyTo(address);
    }

    // Split the mail-address: space separated
    String destinations[] = destination.split(" ");
    InternetAddress[] address = new InternetAddress[destinations.length];
    for (int i = 0; i < destinations.length; i++)
        address[i] = new InternetAddress(destinations[i]);

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

    String realdestinationCc = destinationCc;
    if (!Const.isEmpty(realdestinationCc)) {
        // Split the mail-address Cc: space separated
        String destinationsCc[] = realdestinationCc.split(" ");
        InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
        for (int i = 0; i < destinationsCc.length; i++)
            addressCc[i] = new InternetAddress(destinationsCc[i]);

        msg.setRecipients(Message.RecipientType.CC, addressCc);
    }

    String realdestinationBCc = destinationBCc;
    if (!Const.isEmpty(realdestinationBCc)) {
        // Split the mail-address BCc: space separated
        String destinationsBCc[] = realdestinationBCc.split(" ");
        InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
        for (int i = 0; i < destinationsBCc.length; i++)
            addressBCc[i] = new InternetAddress(destinationsBCc[i]);

        msg.setRecipients(Message.RecipientType.BCC, addressBCc);
    }

    if (mailsubject != null)
        msg.setSubject(mailsubject);

    msg.setSentDate(new Date());
    StringBuffer messageText = new StringBuffer();

    if (comment != null)
        messageText.append(comment).append(Const.CR).append(Const.CR);

    if (meta.getIncludeDate())
        messageText.append(Messages.getString("Mail.Log.Comment.MsgDate") + ": ")
                .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR);

    if (!meta.isOnlySendComment() && (!Const.isEmpty(contactPerson) || !Const.isEmpty(contactPhone))) {
        messageText.append(Messages.getString("Mail.Log.Comment.ContactInfo") + " :").append(Const.CR);
        messageText.append("---------------------").append(Const.CR);
        messageText.append(Messages.getString("Mail.Log.Comment.PersonToContact") + " : ").append(contactPerson)
                .append(Const.CR);
        messageText.append(Messages.getString("Mail.Log.Comment.Tel") + "  : ").append(contactPhone)
                .append(Const.CR);
        messageText.append(Const.CR);
    }
    data.parts = new MimeMultipart();

    MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
    // 1st part

    if (meta.isUseHTML()) {
        if (!Const.isEmpty(meta.getEncoding()))
            part1.setContent(messageText.toString(), "text/html; " + "charset=" + meta.getEncoding());
        else
            part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1");
    } else
        part1.setText(messageText.toString());

    data.parts.addBodyPart(part1);

    // attached files
    if (meta.isDynamicFilename())
        setAttachedFilesList(r, log);
    else
        setAttachedFilesList(null, log);

    msg.setContent(data.parts);

    Transport transport = null;
    try {
        transport = session.getTransport(protocol);
        if (meta.isUsingAuthentication()) {
            if (!Const.isEmpty(port)) {
                transport.connect(Const.NVL(server, ""), Integer.parseInt(Const.NVL(port, "")),
                        Const.NVL(authenticationUser, ""), Const.NVL(authenticationPassword, ""));
            } else {
                transport.connect(Const.NVL(server, ""), Const.NVL(authenticationUser, ""),
                        Const.NVL(authenticationPassword, ""));
            }
        } else {
            transport.connect();
        }
        transport.sendMessage(msg, msg.getAllRecipients());
    } finally {
        if (transport != null)
            transport.close();
    }

}

From source file:org.apache.jmeter.protocol.smtp.sampler.protocol.SendMailCommand.java

/**
 * Prepares message prior to be sent via execute()-method, i.e. sets
 * properties such as protocol, authentication, etc.
 *
 * @return Message-object to be sent to execute()-method
 * @throws MessagingException//w  ww.ja v a2 s  .  c om
 *             when problems constructing or sending the mail occur
 * @throws IOException
 *             when the mail content can not be read or truststore problems
 *             are detected
 */
public Message prepareMessage() throws MessagingException, IOException {

    Properties props = new Properties();

    String protocol = getProtocol();

    // set properties using JAF
    props.setProperty("mail." + protocol + ".host", smtpServer);
    props.setProperty("mail." + protocol + ".port", getPort());
    props.setProperty("mail." + protocol + ".auth", Boolean.toString(useAuthentication));

    // set timeout
    props.setProperty("mail." + protocol + ".timeout", getTimeout());
    props.setProperty("mail." + protocol + ".connectiontimeout", getConnectionTimeout());

    if (useStartTLS || useSSL) {
        try {
            String allProtocols = StringUtils
                    .join(SSLContext.getDefault().getSupportedSSLParameters().getProtocols(), " ");
            logger.info("Use ssl/tls protocols for mail: " + allProtocols);
            props.setProperty("mail." + protocol + ".ssl.protocols", allProtocols);
        } catch (Exception e) {
            logger.error("Problem setting ssl/tls protocols for mail", e);
        }
    }

    if (enableDebug) {
        props.setProperty("mail.debug", "true");
    }

    if (useStartTLS) {
        props.setProperty("mail.smtp.starttls.enable", "true");
        if (enforceStartTLS) {
            // Requires JavaMail 1.4.2+
            props.setProperty("mail.smtp.starttls.require", "true");
        }
    }

    if (trustAllCerts) {
        if (useSSL) {
            props.setProperty("mail.smtps.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY);
            props.setProperty("mail.smtps.ssl.socketFactory.fallback", "false");
        } else if (useStartTLS) {
            props.setProperty("mail.smtp.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY);
            props.setProperty("mail.smtp.ssl.socketFactory.fallback", "false");
        }
    } else if (useLocalTrustStore) {
        File truststore = new File(trustStoreToUse);
        logger.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
        if (!truststore.exists()) {
            logger.info(
                    "load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath());
            truststore = new File(FileServer.getFileServer().getBaseDir(), trustStoreToUse);
            logger.info("load local truststore -Attempting to read truststore from:  "
                    + truststore.getAbsolutePath());
            if (!truststore.exists()) {
                logger.info(
                        "load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath()
                                + ". Local truststore not available, aborting execution.");
                throw new IOException("Local truststore file not found. Also not available under : "
                        + truststore.getAbsolutePath());
            }
        }
        if (useSSL) {
            // Requires JavaMail 1.4.2+
            props.put("mail.smtps.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore));
            props.put("mail.smtps.ssl.socketFactory.fallback", "false");
        } else if (useStartTLS) {
            // Requires JavaMail 1.4.2+
            props.put("mail.smtp.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore));
            props.put("mail.smtp.ssl.socketFactory.fallback", "false");
        }
    }

    session = Session.getInstance(props, null);

    Message message;

    if (sendEmlMessage) {
        message = new MimeMessage(session, new BufferedInputStream(new FileInputStream(emlMessage)));
    } else {
        message = new MimeMessage(session);
        // handle body and attachments
        Multipart multipart = new MimeMultipart();
        final int attachmentCount = attachments.size();
        if (plainBody && (attachmentCount == 0 || (mailBody.length() == 0 && attachmentCount == 1))) {
            if (attachmentCount == 1) { // i.e. mailBody is empty
                File first = attachments.get(0);
                InputStream is = null;
                try {
                    is = new BufferedInputStream(new FileInputStream(first));
                    message.setText(IOUtils.toString(is));
                } finally {
                    IOUtils.closeQuietly(is);
                }
            } else {
                message.setText(mailBody);
            }
        } else {
            BodyPart body = new MimeBodyPart();
            body.setText(mailBody);
            multipart.addBodyPart(body);
            for (File f : attachments) {
                BodyPart attach = new MimeBodyPart();
                attach.setFileName(f.getName());
                attach.setDataHandler(new DataHandler(new FileDataSource(f.getAbsolutePath())));
                multipart.addBodyPart(attach);
            }
            message.setContent(multipart);
        }
    }

    // set from field and subject
    if (null != sender) {
        message.setFrom(new InternetAddress(sender));
    }

    if (null != replyTo) {
        InternetAddress[] to = new InternetAddress[replyTo.size()];
        message.setReplyTo(replyTo.toArray(to));
    }

    if (null != subject) {
        message.setSubject(subject);
    }

    if (receiverTo != null) {
        InternetAddress[] to = new InternetAddress[receiverTo.size()];
        receiverTo.toArray(to);
        message.setRecipients(Message.RecipientType.TO, to);
    }

    if (receiverCC != null) {
        InternetAddress[] cc = new InternetAddress[receiverCC.size()];
        receiverCC.toArray(cc);
        message.setRecipients(Message.RecipientType.CC, cc);
    }

    if (receiverBCC != null) {
        InternetAddress[] bcc = new InternetAddress[receiverBCC.size()];
        receiverBCC.toArray(bcc);
        message.setRecipients(Message.RecipientType.BCC, bcc);
    }

    for (int i = 0; i < headerFields.size(); i++) {
        Argument argument = (Argument) ((TestElementProperty) headerFields.get(i)).getObjectValue();
        message.setHeader(argument.getName(), argument.getValue());
    }

    message.saveChanges();
    return message;
}

From source file:org.pentaho.di.trans.steps.mail.Mail.java

public void sendMail(Object[] r, String server, int port, String senderAddress, String senderName,
        String destination, String destinationCc, String destinationBCc, String contactPerson,
        String contactPhone, String authenticationUser, String authenticationPassword, String mailsubject,
        String comment, String replyToAddresses) throws Exception {

    // Send an e-mail...
    // create some properties and get the default Session

    String protocol = "smtp";
    if (meta.isUsingSecureAuthentication()) { // PDI-2955
        // if (meta.isUsingAuthentication()) {
        if (meta.getSecureConnectionType().equals("TLS")) {
            // Allow TLS authentication
            data.props.put("mail.smtp.starttls.enable", "true");
        } else {/*from  w  ww. j  ava  2 s .c o m*/
            protocol = "smtps";
            // required to get rid of a SSL exception :
            // nested exception is:
            // javax.net.ssl.SSLException: Unsupported record version Unknown
            data.props.put("mail.smtps.quitwait", "false");
        }
    }
    data.props.put("mail." + protocol + ".host", server);
    if (port != -1) {
        data.props.put("mail." + protocol + ".port", "" + port); // needs to be supplied as a string, not as an integer
    }

    if (isDebug()) {
        data.props.put("mail.debug", "true");
    }

    if (meta.isUsingAuthentication()) {
        data.props.put("mail." + protocol + ".auth", "true");
    }

    Session session = Session.getInstance(data.props);
    session.setDebug(isDebug());

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

    // set message priority
    if (meta.isUsePriority()) {
        String priority_int = "1";
        if (meta.getPriority().equals("low")) {
            priority_int = "3";
        }
        if (meta.getPriority().equals("normal")) {
            priority_int = "2";
        }

        msg.setHeader("X-Priority", priority_int); // (String)int between 1= high and 3 = low.
        msg.setHeader("Importance", meta.getImportance());
        // seems to be needed for MS Outlook.
        // where it returns a string of high /normal /low.
        msg.setHeader("Sensitivity", meta.getSensitivity());
        // Possible values are normal, personal, private, company-confidential
    }

    // set Email sender
    String email_address = senderAddress;
    if (!Const.isEmpty(email_address)) {
        // get sender name
        if (!Const.isEmpty(senderName)) {
            email_address = senderName + '<' + email_address + '>';
        }
        msg.setFrom(new InternetAddress(email_address));
    } else {
        throw new MessagingException(BaseMessages.getString(PKG, "Mail.Error.ReplyEmailNotFilled"));
    }

    // Set reply to
    if (!Const.isEmpty(replyToAddresses)) {
        // get replay to
        // Split the mail-address: space separated
        String[] reply_Address_List = replyToAddresses.split(" ");
        InternetAddress[] address = new InternetAddress[reply_Address_List.length];

        for (int i = 0; i < reply_Address_List.length; i++) {
            address[i] = new InternetAddress(reply_Address_List[i]);
        }

        // To add the real reply-to
        msg.setReplyTo(address);
    }

    // Split the mail-address: space separated
    String[] destinations = destination.split(" ");
    InternetAddress[] address = new InternetAddress[destinations.length];
    for (int i = 0; i < destinations.length; i++) {
        address[i] = new InternetAddress(destinations[i]);
    }

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

    String realdestinationCc = destinationCc;
    if (!Const.isEmpty(realdestinationCc)) {
        // Split the mail-address Cc: space separated
        String[] destinationsCc = realdestinationCc.split(" ");
        InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
        for (int i = 0; i < destinationsCc.length; i++) {
            addressCc[i] = new InternetAddress(destinationsCc[i]);
        }

        msg.setRecipients(Message.RecipientType.CC, addressCc);
    }

    String realdestinationBCc = destinationBCc;
    if (!Const.isEmpty(realdestinationBCc)) {
        // Split the mail-address BCc: space separated
        String[] destinationsBCc = realdestinationBCc.split(" ");
        InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
        for (int i = 0; i < destinationsBCc.length; i++) {
            addressBCc[i] = new InternetAddress(destinationsBCc[i]);
        }

        msg.setRecipients(Message.RecipientType.BCC, addressBCc);
    }

    if (mailsubject != null) {
        msg.setSubject(mailsubject);
    }

    msg.setSentDate(new Date());
    StringBuffer messageText = new StringBuffer();

    if (comment != null) {
        messageText.append(comment).append(Const.CR).append(Const.CR);
    }

    if (meta.getIncludeDate()) {
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.MsgDate") + ": ")
                .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR);
    }

    if (!meta.isOnlySendComment() && (!Const.isEmpty(contactPerson) || !Const.isEmpty(contactPhone))) {
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.ContactInfo") + " :").append(Const.CR);
        messageText.append("---------------------").append(Const.CR);
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.PersonToContact") + " : ")
                .append(contactPerson).append(Const.CR);
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.Tel") + "  : ").append(contactPhone)
                .append(Const.CR);
        messageText.append(Const.CR);
    }
    data.parts = new MimeMultipart();

    MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
    // 1st part

    if (meta.isUseHTML()) {
        if (!Const.isEmpty(meta.getEncoding())) {
            part1.setContent(messageText.toString(), "text/html; " + "charset=" + meta.getEncoding());
        } else {
            part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1");
        }
    } else {
        part1.setText(messageText.toString());
    }

    data.parts.addBodyPart(part1);

    if (meta.isAttachContentFromField()) {
        // attache file content
        addAttachedContent(data.previousRowMeta.getString(r, data.IndexOfAttachedFilename),
                data.previousRowMeta.getString(r, data.indexOfAttachedContent));
    } else {
        // attached files
        if (meta.isDynamicFilename()) {
            setAttachedFilesList(r, log);
        } else {
            setAttachedFilesList(null, log);
        }
    }

    // add embedded images
    addImagePart();

    if (data.nrEmbeddedImages > 0 && data.nrattachedFiles == 0) {
        // If we need to embedd images...
        // We need to create a "multipart/related" message.
        // otherwise image will appear as attached file
        data.parts.setSubType("related");
    }

    msg.setContent(data.parts);

    Transport transport = null;
    try {
        transport = session.getTransport(protocol);
        if (meta.isUsingAuthentication()) {
            if (port != -1) {
                transport.connect(Const.NVL(server, ""), port, Const.NVL(authenticationUser, ""),
                        Const.NVL(authenticationPassword, ""));
            } else {
                transport.connect(Const.NVL(server, ""), Const.NVL(authenticationUser, ""),
                        Const.NVL(authenticationPassword, ""));
            }
        } else {
            transport.connect();
        }
        transport.sendMessage(msg, msg.getAllRecipients());
    } finally {
        if (transport != null) {
            transport.close();
        }
    }

}