Example usage for javax.mail.internet MimeMessage setReplyTo

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

Introduction

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

Prototype

@Override
public void setReplyTo(Address[] addresses) throws MessagingException 

Source Link

Document

Set the RFC 822 "Reply-To" header field.

Usage

From source file:org.intermine.util.MailUtils.java

/**
 * Send an email to an address, supplying the recipient, subject and body.
 *
 * @param to the address to send to//from w w  w .  j  a va 2s  .  co  m
 * @param subject The Subject of the email
 * @param body The content of the email
 * @param from the address to send from
 * @param webProperties Common properties for all emails (such as from, authentication)
 * @throws MessagingException if there is a problem creating the email
 */
public static void email(String to, String subject, String body, String from, final Properties webProperties)
        throws MessagingException {
    final String user = webProperties.getProperty("mail.smtp.user");
    String smtpPort = webProperties.getProperty("mail.smtp.port");
    String authFlag = webProperties.getProperty("mail.smtp.auth");
    String starttlsFlag = webProperties.getProperty("mail.smtp.starttls.enable");

    Properties properties = System.getProperties();

    properties.put("mail.smtp.host", webProperties.get("mail.host"));
    properties.put("mail.smtp.user", user);
    // Fix to "javax.mail.MessagingException: 501 Syntactically
    // invalid HELO argument(s)" problem
    // See http://forum.java.sun.com/thread.jspa?threadID=487000&messageID=2280968
    properties.put("mail.smtp.localhost", "localhost");
    if (smtpPort != null) {
        properties.put("mail.smtp.port", smtpPort);
    }
    if (starttlsFlag != null) {
        properties.put("mail.smtp.starttls.enable", starttlsFlag);
    }
    if (authFlag != null) {
        properties.put("mail.smtp.auth", authFlag);
    }

    Session session;
    if (authFlag != null && ("true".equals(authFlag) || "t".equals(authFlag))) {
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                String password = (String) webProperties.get("mail.server.password");
                return new PasswordAuthentication(user, password);
            }
        };
        session = Session.getInstance(properties, authenticator);
    } else {
        session = Session.getInstance(properties);
    }
    MimeMessage message = new MimeMessage(session);
    if (StringUtils.isEmpty(user)) {
        message.setFrom(new InternetAddress(from));
    } else {
        message.setReplyTo(InternetAddress.parse(from, true));
        message.setFrom(new InternetAddress(user));
    }
    message.addRecipient(Message.RecipientType.TO, InternetAddress.parse(to, true)[0]);
    message.setSubject(subject);
    message.setContent(body, "text/plain");
    Transport.send(message);
}

From source file:org.j2free.email.EmailService.java

private void send(InternetAddress from, InternetAddress[] recipients, String subject, String body,
        ContentType contentType, Priority priority, boolean ccSender)
        throws AddressException, MessagingException, RejectedExecutionException {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(from);//from www .  ja  v  a 2  s.c  o m
    message.setRecipients(Message.RecipientType.TO, recipients);

    for (Map.Entry<String, String> header : headers.entrySet())
        message.setHeader(header.getKey(), header.getValue());

    // CC the sender if they want
    if (ccSender)
        message.addRecipient(Message.RecipientType.CC, from);

    message.setReplyTo(new InternetAddress[] { from });

    message.setSubject(subject);
    message.setSentDate(new Date());

    if (contentType == ContentType.PLAIN) {
        // Just set the body as plain text
        message.setText(body, "UTF-8");
    } else {
        MimeMultipart multipart = new MimeMultipart("alternative");

        // Create the text part
        MimeBodyPart text = new MimeBodyPart();
        text.setText(new HtmlFilter().filterForEmail(body), "UTF-8");

        // Add the text part
        multipart.addBodyPart(text);

        // Create the HTML portion
        MimeBodyPart html = new MimeBodyPart();
        html.setContent(body, ContentType.HTML.toString());

        // Add the HTML portion
        multipart.addBodyPart(html);

        // set the message content
        message.setContent(multipart);
    }
    enqueue(message, priority);
}

From source file:org.jenkinsci.plugins.send_mail_builder.SendMailBuilder.java

@Override
public boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener)
        throws IOException, InterruptedException {
    final EnvVars env = build.getEnvironment(listener);
    final String charset = Mailer.descriptor().getCharset();
    final MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession());
    try {// ww w . j  a v a 2s  .c om
        msg.setFrom(Mailer.StringToAddress(JenkinsLocationConfiguration.get().getAdminAddress(), charset));
        msg.setContent("", "text/plain");
        msg.setSentDate(new Date());
        String actualReplyTo = env.expand(replyTo);
        if (StringUtils.isBlank(actualReplyTo)) {
            actualReplyTo = Mailer.descriptor().getReplyToAddress();
        }
        if (StringUtils.isNotBlank(actualReplyTo)) {
            msg.setReplyTo(new Address[] { Mailer.StringToAddress(actualReplyTo, charset) });
        }
        msg.setRecipients(RecipientType.TO, toInternetAddresses(listener, env.expand(tos), charset));
        msg.setRecipients(RecipientType.CC, toInternetAddresses(listener, env.expand(ccs), charset));
        msg.setRecipients(RecipientType.BCC, toInternetAddresses(listener, env.expand(bccs), charset));
        msg.setSubject(env.expand(subject), charset);
        msg.setText(env.expand(text), charset);
        Transport.send(msg);
    } catch (final MessagingException e) {
        listener.getLogger().println(Messages.SendMail_FailedToSend());
        e.printStackTrace(listener.error(e.getMessage()));
        return false;
    }
    listener.getLogger().println(Messages.SendMail_SentSuccessfully());
    return true;
}

From source file:org.linagora.linshare.core.service.impl.MailNotifierServiceImpl.java

@Override
public void sendNotification(String smtpSender, String replyTo, String recipient, String subject,
        String htmlContent, String inReplyTo, String references) throws SendFailedException {

    if (smtpServer.equals("")) {
        logger.warn("Mail notifications are disabled.");
        return;/*from w  w  w.  j ava 2s  .c om*/
    }
    // get the mail session
    Session session = getMailSession();

    // Define message
    MimeMessage messageMim = new MimeMessage(session);

    try {
        messageMim.setFrom(new InternetAddress(smtpSender));

        if (replyTo != null) {
            InternetAddress reply[] = new InternetAddress[1];
            reply[0] = new InternetAddress(replyTo);
            messageMim.setReplyTo(reply);
        }

        messageMim.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient));

        if (inReplyTo != null && inReplyTo != "") {
            // This field should contain only ASCCI character (RFC 822)
            if (isPureAscii(inReplyTo)) {
                messageMim.setHeader("In-Reply-To", inReplyTo);
            }
        }

        if (references != null && references != "") {
            // This field should contain only ASCCI character (RFC 822)  
            if (isPureAscii(references)) {
                messageMim.setHeader("References", references);
            }
        }

        messageMim.setSubject(subject, charset);

        // Create a "related" Multipart message
        // content type is multipart/alternative
        // it will contain two part BodyPart 1 and 2
        Multipart mp = new MimeMultipart("alternative");

        // BodyPart 2
        // content type is multipart/related
        // A multipart/related is used to indicate that message parts should
        // not be considered individually but rather
        // as parts of an aggregate whole. The message consists of a root
        // part (by default, the first) which reference other parts inline,
        // which may in turn reference other parts.
        Multipart html_mp = new MimeMultipart("related");

        // Include an HTML message with images.
        // BodyParts: the HTML file and an image

        // Get the HTML file
        BodyPart rel_bph = new MimeBodyPart();
        rel_bph.setDataHandler(
                new DataHandler(new ByteArrayDataSource(htmlContent, "text/html; charset=" + charset)));
        html_mp.addBodyPart(rel_bph);

        // Create the second BodyPart of the multipart/alternative,
        // set its content to the html multipart, and add the
        // second bodypart to the main multipart.
        BodyPart alt_bp2 = new MimeBodyPart();
        alt_bp2.setContent(html_mp);
        mp.addBodyPart(alt_bp2);

        messageMim.setContent(mp);

        // RFC 822 "Date" header field
        // Indicates that the message is complete and ready for delivery
        messageMim.setSentDate(new GregorianCalendar().getTime());

        // Since we used html tags, the content must be marker as text/html
        // messageMim.setContent(content,"text/html; charset="+charset);

        Transport tr = session.getTransport("smtp");

        // Connect to smtp server, if needed
        if (needsAuth) {
            tr.connect(smtpServer, smtpPort, smtpUser, smtpPassword);
            messageMim.saveChanges();
            tr.sendMessage(messageMim, messageMim.getAllRecipients());
            tr.close();
        } else {
            // Send message
            Transport.send(messageMim);
        }
    } catch (SendFailedException e) {
        logger.error("Error sending notification on " + smtpServer + " port " + smtpPort + " to " + recipient,
                e);
        throw e;
    } catch (MessagingException e) {
        logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e);
        throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e);
    } catch (Exception e) {
        logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e);
        throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e);
    }
}

From source file:org.liveSense.service.email.EmailServiceImpl.java

private MimeMessage prepareMimeMessage(MimeMessage mimeMessage, Node node, String template, String subject,
        Object replyTo, Object from, Date date, Object[] to, Object[] cc, Object[] bcc,
        HashMap<String, Object> variables) throws AddressException, MessagingException, ValueFormatException,
        PathNotFoundException, RepositoryException, UnsupportedEncodingException {

    if (replyTo != null) {
        mimeMessage.setReplyTo(convertToInternetAddress(replyTo));
    } else {//from  w w  w .  j  ava  2s  .co  m
        if (node != null && node.hasProperty("replyTo")) {
            mimeMessage.setReplyTo(convertToInternetAddress(node.getProperty("replyTo").getString()));
        } else if (variables != null && variables.containsKey("replyTo")) {
            mimeMessage.setReplyTo(convertToInternetAddress(variables.get("replyTo")));
        }
    }
    if (date == null) {
        if (node != null && node.hasProperty("mailDate")) {
            mimeMessage.setSentDate(node.getProperty("mailDate").getDate().getTime());
        } else if (variables != null && variables.containsKey("mailDate")) {
            mimeMessage.setSentDate((Date) variables.get("mailDate"));
        } else {
            mimeMessage.setSentDate(new Date());
        }
    } else {
        mimeMessage.setSentDate(date);
    }

    if (subject != null) {
        mimeMessage.setSubject(MimeUtility.encodeText(subject, configurator.getEncoding(), "Q"));
    } else {
        if (node != null && node.hasProperty("subject")) {
            mimeMessage.setSubject(MimeUtility.encodeText(node.getProperty("subject").getString(),
                    configurator.getEncoding(), "Q"));
        } else if (variables != null && variables.containsKey("subject")) {
            mimeMessage.setSubject(
                    MimeUtility.encodeText((String) variables.get("subject"), configurator.getEncoding(), "Q"));
        }
    }

    if (from != null) {
        mimeMessage.setFrom(convertToInternetAddress(from)[0]);
    } else {
        if (node != null && node.hasProperty("from")) {
            mimeMessage.setFrom(convertToInternetAddress(node.getProperty("from").getString())[0]);
        } else if (variables != null && variables.containsKey("from")) {
            mimeMessage.setFrom(convertToInternetAddress(variables.get("from"))[0]);
        }
    }

    if (to != null) {
        mimeMessage.addRecipients(Message.RecipientType.TO, convertToInternetAddress(to));
    } else {
        if (node != null && node.hasProperty("to")) {
            if (node.getProperty("to").isMultiple()) {
                Value[] values = node.getProperty("to").getValues();
                for (int i = 0; i < values.length; i++) {
                    mimeMessage.addRecipients(Message.RecipientType.TO,
                            convertToInternetAddress(values[i].getString()));
                }
            } else {
                mimeMessage.addRecipients(Message.RecipientType.TO,
                        convertToInternetAddress(node.getProperty("to").getString()));
            }
        } else if (variables != null && variables.containsKey("to")) {
            mimeMessage.addRecipients(Message.RecipientType.TO, convertToInternetAddress(variables.get("to")));
        }

    }

    if (cc != null) {
        mimeMessage.addRecipients(Message.RecipientType.CC, convertToInternetAddress(cc));
    } else {
        if (node != null && node.hasProperty("cc")) {
            if (node.getProperty("cc").isMultiple()) {
                Value[] values = node.getProperty("cc").getValues();
                for (int i = 0; i < values.length; i++) {
                    mimeMessage.addRecipients(Message.RecipientType.CC,
                            convertToInternetAddress(values[i].getString()));
                }
            } else {
                mimeMessage.addRecipients(Message.RecipientType.CC,
                        convertToInternetAddress(node.getProperty("cc").getString()));
            }
        } else if (variables != null && variables.containsKey("cc")) {
            mimeMessage.addRecipients(Message.RecipientType.CC, convertToInternetAddress(variables.get("cc")));
        }
    }

    if (bcc != null) {
        mimeMessage.addRecipients(Message.RecipientType.BCC, convertToInternetAddress(bcc));
    } else {
        if (node != null && node.hasProperty("bcc")) {
            if (node.getProperty("bcc").isMultiple()) {
                Value[] values = node.getProperty("bcc").getValues();
                for (int i = 0; i < values.length; i++) {
                    mimeMessage.addRecipients(Message.RecipientType.BCC,
                            convertToInternetAddress(values[i].getString()));
                }
            } else {
                mimeMessage.addRecipients(Message.RecipientType.BCC,
                        convertToInternetAddress(node.getProperty("bcc").getString()));
            }
        } else if (variables != null && variables.containsKey("bcc")) {
            mimeMessage.addRecipients(Message.RecipientType.BCC,
                    convertToInternetAddress(variables.get("bcc")));
        }
    }
    return mimeMessage;
}

From source file:org.mule.transport.email.transformers.StringToEmailMessage.java

@Override
public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {
    String endpointAddress = endpoint.getEndpointURI().getAddress();
    SmtpConnector connector = (SmtpConnector) endpoint.getConnector();
    String to = lookupProperty(message, MailProperties.TO_ADDRESSES_PROPERTY, endpointAddress);
    String cc = lookupProperty(message, MailProperties.CC_ADDRESSES_PROPERTY, connector.getCcAddresses());
    String bcc = lookupProperty(message, MailProperties.BCC_ADDRESSES_PROPERTY, connector.getBccAddresses());
    String from = lookupProperty(message, MailProperties.FROM_ADDRESS_PROPERTY, connector.getFromAddress());
    String replyTo = lookupProperty(message, MailProperties.REPLY_TO_ADDRESSES_PROPERTY,
            connector.getReplyToAddresses());
    String subject = lookupProperty(message, MailProperties.SUBJECT_PROPERTY, connector.getSubject());
    String contentType = lookupProperty(message, MailProperties.CONTENT_TYPE_PROPERTY,
            connector.getContentType());

    Properties headers = new Properties();
    Properties customHeaders = connector.getCustomHeaders();

    if (customHeaders != null && !customHeaders.isEmpty()) {
        headers.putAll(customHeaders);/*from w  w  w  . j  a va  2s.  c  o  m*/
    }

    Properties otherHeaders = message.getOutboundProperty(MailProperties.CUSTOM_HEADERS_MAP_PROPERTY);
    if (otherHeaders != null && !otherHeaders.isEmpty()) {
        //TODO Whats going on here?
        //                final MuleContext mc = context.getMuleContext();
        //                for (Iterator iterator = message.getPropertyNames().iterator(); iterator.hasNext();)
        //                {
        //                    String propertyKey = (String) iterator.next();
        //                    mc.getRegistry().registerObject(propertyKey, message.getProperty(propertyKey), mc);
        //                }
        headers.putAll(templateParser.parse(new TemplateParser.TemplateCallback() {
            public Object match(String token) {
                return muleContext.getRegistry().lookupObject(token);
            }
        }, otherHeaders));

    }

    if (logger.isDebugEnabled()) {
        StringBuffer buf = new StringBuffer();
        buf.append("Constructing email using:\n");
        buf.append("To: ").append(to);
        buf.append(", From: ").append(from);
        buf.append(", CC: ").append(cc);
        buf.append(", BCC: ").append(bcc);
        buf.append(", Subject: ").append(subject);
        buf.append(", ReplyTo: ").append(replyTo);
        buf.append(", Content type: ").append(contentType);
        buf.append(", Payload type: ").append(message.getPayload().getClass().getName());
        buf.append(", Custom Headers: ").append(MapUtils.toString(headers, false));
        logger.debug(buf.toString());
    }

    try {
        MimeMessage email = new MimeMessage(
                ((SmtpConnector) endpoint.getConnector()).getSessionDetails(endpoint).getSession());

        email.setRecipients(Message.RecipientType.TO, MailUtils.stringToInternetAddresses(to));

        // sent date
        email.setSentDate(Calendar.getInstance().getTime());

        if (StringUtils.isNotBlank(from)) {
            email.setFrom(MailUtils.stringToInternetAddresses(from)[0]);
        }

        if (StringUtils.isNotBlank(cc)) {
            email.setRecipients(Message.RecipientType.CC, MailUtils.stringToInternetAddresses(cc));
        }

        if (StringUtils.isNotBlank(bcc)) {
            email.setRecipients(Message.RecipientType.BCC, MailUtils.stringToInternetAddresses(bcc));
        }

        if (StringUtils.isNotBlank(replyTo)) {
            email.setReplyTo(MailUtils.stringToInternetAddresses(replyTo));
        }

        email.setSubject(subject, outputEncoding);

        for (Iterator iterator = headers.entrySet().iterator(); iterator.hasNext();) {
            Map.Entry entry = (Map.Entry) iterator.next();
            email.setHeader(entry.getKey().toString(), entry.getValue().toString());
        }

        setContent(message.getPayload(), email, contentType, message);

        return email;
    } catch (Exception e) {
        throw new TransformerException(this, e);
    }
}

From source file:org.olat.core.util.mail.manager.MailManagerImpl.java

@Override
public MimeMessage createMimeMessage(Address from, Address[] tos, Address[] ccs, Address[] bccs, String subject,
        String body, List<File> attachments, MailerResult result) {

    try {/*w ww.j a  v  a 2s .c o  m*/
        //   see FXOLAT-74: send all mails as <fromemail> (in config) to have a valid reverse lookup and therefore pass spam protection.
        // following doesn't work correctly, therefore add bounce-address in message already
        Address convertedFrom = getRawEmailFromAddress(from);
        MimeMessage msg = createMessage(convertedFrom);
        Address viewableFrom = createAddressWithName(WebappHelper.getMailConfig("mailFrom"),
                WebappHelper.getMailConfig("mailFromName"));
        msg.setFrom(viewableFrom);
        msg.setSubject(subject, "utf-8");
        // reply to can only be an address without name (at least for postfix!), see FXOLAT-312
        msg.setReplyTo(new Address[] { convertedFrom });

        if (tos != null && tos.length > 0) {
            msg.addRecipients(RecipientType.TO, tos);
        }

        if (ccs != null && ccs.length > 0) {
            msg.addRecipients(RecipientType.CC, ccs);
        }

        if (bccs != null && bccs.length > 0) {
            msg.addRecipients(RecipientType.BCC, bccs);
        }

        if (attachments != null && !attachments.isEmpty()) {
            // with attachment use multipart message
            Multipart multipart = new MimeMultipart("mixed");
            // 1) add body part
            if (StringHelper.isHtml(body)) {
                Multipart alternativePart = createMultipartAlternative(body);
                MimeBodyPart wrap = new MimeBodyPart();
                wrap.setContent(alternativePart);
                multipart.addBodyPart(wrap);
            } else {
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setText(body);
                multipart.addBodyPart(messageBodyPart);
            }

            // 2) add attachments
            for (File attachmentFile : attachments) {
                // abort if attachment does not exist
                if (attachmentFile == null || !attachmentFile.exists()) {
                    result.setReturnCode(MailerResult.ATTACHMENT_INVALID);
                    logError("Tried to send mail wit attachment that does not exist::"
                            + (attachmentFile == null ? null : attachmentFile.getAbsolutePath()), null);
                    return msg;
                }
                BodyPart filePart = new MimeBodyPart();
                DataSource source = new FileDataSource(attachmentFile);
                filePart.setDataHandler(new DataHandler(source));
                filePart.setFileName(attachmentFile.getName());
                multipart.addBodyPart(filePart);
            }
            // Put parts in message
            msg.setContent(multipart);
        } else {
            // without attachment everything is easy, just set as text
            if (StringHelper.isHtml(body)) {
                msg.setContent(createMultipartAlternative(body));
            } else {
                msg.setText(body, "utf-8");
            }
        }
        msg.setSentDate(new Date());
        msg.saveChanges();
        return msg;
    } catch (AddressException e) {
        result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR);
        logError("", e);
        return null;
    } catch (MessagingException e) {
        result.setReturnCode(MailerResult.SEND_GENERAL_ERROR);
        logError("", e);
        return null;
    } catch (UnsupportedEncodingException e) {
        result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR);
        logError("", e);
        return null;
    }
}

From source file:org.opencastproject.messages.MailService.java

/** Message -> MimeMessage. */
private MimeMessage toMimeMessage(Mail mail) throws Exception {
    final MimeMessage msg = smtpService.createMessage();
    for (EmailAddress reply : mail.getReplyTo())
        msg.setReplyTo(new Address[] { new InternetAddress(reply.getAddress(), reply.getName(), "UTF-8") });

    // recipient/*w w w  .j  av a  2s.  c  o m*/
    for (EmailAddress recipient : mail.getRecipients()) {
        msg.addRecipient(javax.mail.Message.RecipientType.TO,
                new InternetAddress(recipient.getAddress(), recipient.getName(), "UTF-8"));
    }

    // subject
    msg.setSubject(mail.getSubject());

    EmailAddress from = mail.getSender();
    msg.setFrom(new InternetAddress(from.getAddress(), from.getName(), "UTF-8"));
    // body
    msg.setText(mail.getBody(), "UTF-8");
    return msg;
}

From source file:org.opens.emailsender.EmailSender.java

/**
 *
 * @param emailFrom/*w ww  . j a  va 2s . co m*/
 * @param emailToSet
 * @param emailBccSet (can be null)
 * @param replyTo (can be null)
 * @param emailSubject
 * @param emailContent
 */
public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo,
        String emailSubject, String emailContent) {
    boolean debug = false;

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");

    // create some properties and get the default Session
    Session session = Session.getInstance(props);
    session.setDebug(debug);
    try {
        Transport t = session.getTransport("smtp");
        t.connect(smtpHost, userName, password);

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

        // set the from and to address
        InternetAddress addressFrom;
        try {
            // Used default from address is passed one is null or empty or
            // blank
            addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom)
                    : new InternetAddress(from);
            msg.setFrom(addressFrom);
            Address[] recipients = new InternetAddress[emailToSet.size()];
            int i = 0;
            for (String emailTo : emailToSet) {
                recipients[i] = new InternetAddress(emailTo);
                i++;
            }

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

            if (CollectionUtils.isNotEmpty(emailBccSet)) {
                Address[] bccRecipients = new InternetAddress[emailBccSet.size()];
                i = 0;
                for (String emailBcc : emailBccSet) {
                    bccRecipients[i] = new InternetAddress(emailBcc);
                    i++;
                }
                msg.setRecipients(Message.RecipientType.BCC, bccRecipients);
            }

            if (StringUtils.isNotBlank(replyTo)) {
                Address[] replyToRecipients = { new InternetAddress(replyTo) };
                msg.setReplyTo(replyToRecipients);
            }

            // Setting the Subject
            msg.setSubject(emailSubject, CHARSET_KEY);

            // Setting content and charset (warning: both declarations of
            // charset are needed)
            msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY);
            LOGGER.error("emailContent  " + emailContent);
            msg.setContent(emailContent, FULL_CHARSET_KEY);
            try {
                LOGGER.debug("emailContent from message object " + msg.getContent().toString());
            } catch (IOException ex) {
                LOGGER.error(ex.getMessage());
            } catch (MessagingException ex) {
                LOGGER.error(ex.getMessage());
            }
            for (Address addr : msg.getAllRecipients()) {
                LOGGER.error("addr " + addr);
            }
            t.sendMessage(msg, msg.getAllRecipients());
        } catch (AddressException ex) {
            LOGGER.warn(ex.getMessage());
        }
    } catch (NoSuchProviderException e) {
        LOGGER.warn(e.getMessage());
    } catch (MessagingException e) {
        LOGGER.warn(e.getMessage());
    }
}

From source file:org.opens.kbaccess.controller.utils.AMailerController.java

/**
 * Send a mail to the specified recipients.
 * //  ww  w  .j  ava2s. c o m
 * @param subject The mail's subject
 * @param message The mail's body
 * @param recipients The adressee
 * @return true if the send succeed,
 *         false otherwise
 */
public boolean sendMail(String subject, String message, String[] recipients) {
    Session session;
    MimeMessage mimeMessage;
    Properties properties;

    // sanity check
    if (recipients.length == 0) {
        return true;
    }
    // set-up session
    properties = new Properties();
    properties.put("mail.smtp.host", mailingServiceProperties.getSmtpHost());
    session = Session.getDefaultInstance(properties);
    //session.setDebug(true);
    try {
        Address from;
        Address[] to = new InternetAddress[recipients.length];

        // set sender
        from = new InternetAddress(mailingServiceProperties.getDefaultReturnAddress());
        // initialize recipients list
        for (int i = 0; i < to.length; ++i) {
            to[i] = new InternetAddress(recipients[i]);
        }
        // create message
        mimeMessage = new MimeMessage(session);
        mimeMessage.setSender(from);
        mimeMessage.setFrom(from);
        mimeMessage.setReplyTo(new Address[] { from });
        mimeMessage.setRecipients(Message.RecipientType.TO, to);
        mimeMessage.setSubject(subject);
        mimeMessage.setText(message, "utf-8");
        // send it
        Transport.send(mimeMessage);
    } catch (MessagingException ex) {
        LogFactory.getLog(GuestController.class).error("Unable to send email", ex);
        return false;
    }
    return true;
}