Example usage for javax.mail Message setRecipients

List of usage examples for javax.mail Message setRecipients

Introduction

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

Prototype

public abstract void setRecipients(RecipientType type, Address[] addresses) throws MessagingException;

Source Link

Document

Set the recipient addresses.

Usage

From source file:com.photon.phresco.util.Utility.java

public static void sendTemplateEmail(String[] toAddr, String fromAddr, String user, String subject, String body,
        String username, String password, String host, String screen, String build) throws PhrescoException {

    List<String> lists = Arrays.asList(toAddr);
    if (fromAddr == null) {
        fromAddr = "phresco.do.not.reply@gmail.com";
        username = "phresco.do.not.reply@gmail.com";
        password = "phresco123";
    }/* w ww .j a v  a  2s  . co  m*/
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");
    Session session = Session.getDefaultInstance(props, new LoginAuthenticator(username, password));
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromAddr));
        List<Address> emailsList = getEmailsList(lists);
        Address[] dsf = new Address[emailsList.size()];
        message.setRecipients(Message.RecipientType.BCC, emailsList.toArray(dsf));
        message.setSubject(subject);
        DataSource source = new FileDataSource(body);
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("Error.txt");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        MimeBodyPart messageBodyPart2 = new MimeBodyPart();
        DataSource source2 = new FileDataSource(screen);
        messageBodyPart2.setDataHandler(new DataHandler(source2));
        messageBodyPart2.setFileName("Error.jpg");
        multipart.addBodyPart(messageBodyPart2);
        MimeBodyPart mainPart = new MimeBodyPart();
        String content = "<b>Phresco framework error report<br><br>User Name:&nbsp;&nbsp;" + user
                + "<br> Email Address:&nbsp;&nbsp;" + fromAddr + "<br>Build No:&nbsp;&nbsp;" + build;
        mainPart.setContent(content, "text/html");
        multipart.addBodyPart(mainPart);
        message.setContent(multipart);
        Transport.send(message);
    } catch (MessagingException e) {
        throw new PhrescoException(e);
    }
}

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

/**
 * @param recipient//from   w w  w  .  j  a va  2  s .  c o  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:Interface.FoodDistributionWorkArea.FoodDistributionWorkArea.java

public void sendEmail(String emailID, Food food) {

    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    // Get a Properties object
    Properties props = System.getProperties();
    props.setProperty("mail.smtp.host", "smtp.gmail.com");
    props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.port", "465");
    props.setProperty("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.auth", "true");
    props.put("mail.debug", "true");
    props.put("mail.store.protocol", "pop3");
    props.put("mail.transport.protocol", "smtp");
    final String username = "kunal.deora@gmail.com";//
    final String password = "adrika46";
    String text = "Hi Sir/Mam, " + '\n'
            + "You have received rewards points for the food you have donated. Details are listed below: "
            + '\n' + "Food Name:  " + food.getFoodName() + '\n' + "Food ID :" + food.getFoodBarCode() + '\n'
            + "Food Reward Points " + food.getRewardPoints() + '\n'
            + "If you have any queries you can contact us on +133333333333" + '\n'
            + "Thank you for helping for the betterment of society. Every little bite counts :) " + '\n';
    try {/*from ww w  .ja  v a 2 s.  c  o m*/
        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                return new javax.mail.PasswordAuthentication(username, password);
            }
        });

        // -- Create a new message --
        javax.mail.Message msg = new MimeMessage(session);

        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress("kunal.deora@gmail.com"));
        msg.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(emailID, false));
        msg.setSubject("Congratulations! You have received reward points !!!");
        msg.setText(text);
        msg.setSentDate(new Date());
        javax.mail.Transport.send(msg);
        System.out.println("Message sent.");
    } catch (javax.mail.MessagingException e) {
        System.out.println("Erreur d'envoi, cause: " + e);
    }

}

From source file:org.collectionspace.chain.csp.persistence.file.TestGeneral.java

/**
 * Sets up and sends email message providing you have set up the email address to send to
 *///from ww w.j  ava2  s . co  m
@Test
public void testEmail() {
    Boolean doIreallyWantToSpam = false; // set to true when you have configured the email addresses
    /* please personalises these emails before sending - I don't want your spam. */
    String from = "admin@collectionspace.org";
    String[] recipients = { "" };

    String SMTP_HOST_NAME = "localhost";
    String SMTP_PORT = "25";
    String message = "Hi, Test Message Contents";
    String subject = "A test from collectionspace test suite";
    String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); //REM - Replace.  This is pre-JDK 1.4 code, from the days when JSSE was a separate download.  Fix the imports so they refer to the classes in javax.net.ssl If you really want to get hold of a specific instance, you can use Security.getProvider(name). You'll find the appropriate names in the providers documentation. 
    boolean debug = true;

    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    //props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.auth", "false");
    props.put("mail.debug", "true");
    props.put("mail.smtp.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.put("mail.smtp.socketFactory.fallback", "false");

    Session session = Session.getDefaultInstance(props);

    session.setDebug(debug);
    if (doIreallyWantToSpam) {

        Message msg = new MimeMessage(session);
        InternetAddress addressFrom;
        try {
            addressFrom = new InternetAddress(from);
            msg.setFrom(addressFrom);

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

            // Setting the Subject and Content Type
            msg.setSubject(subject);
            msg.setContent(message, "text/plain");
            if (doIreallyWantToSpam) {
                Transport.send(msg);
                assertTrue(doIreallyWantToSpam);
            }
        } catch (AddressException e) {
            log.debug(e.getMessage());
            assertTrue(false);
        } catch (MessagingException e) {
            log.debug(e.getMessage());
            assertTrue(false);
        }
    }
    //assertTrue(doIreallyWantToSpam);
}

From source file:org.infoglue.cms.util.mail.MailService.java

/**
 *
 *///  w ww . j av a  2 s  .c o  m
private Message createMessage(String from, String to, String bcc, String subject, String content,
        String contentType, String encoding) throws SystemException {
    try {
        final Message message = new MimeMessage(this.session);
        String contentTypeWithEncoding = contentType + ";charset=" + encoding;

        //message.setContent(content, contentType);
        message.setFrom(createInternetAddress(from));
        message.setRecipient(Message.RecipientType.TO, createInternetAddress(to));
        if (bcc != null)
            message.setRecipients(Message.RecipientType.BCC, createInternetAddresses(bcc));
        //message.setSubject(subject);

        ((MimeMessage) message).setSubject(subject, encoding);
        //message.setText(content);
        message.setDataHandler(
                new DataHandler(new StringDataSource(content, contentTypeWithEncoding, encoding)));
        //message.setText(content);
        //message.setDataHandler(new DataHandler(new StringDataSource(content, "text/html"))); 

        return message;
    } catch (MessagingException e) {
        throw new Bug("Unable to create the message.", e);
    }
}

From source file:it.eng.spagobi.tools.scheduler.dispatcher.DistributionListDocumentDispatchChannel.java

public boolean dispatch(BIObject document, byte[] executionOutput) {

    String contentType;//from  w  w  w .  ja  v a  2 s. c o m
    String fileExtension;
    String nameSuffix;
    JobExecutionContext jobExecutionContext;

    logger.debug("IN");

    try {

        contentType = dispatchContext.getContentType();
        fileExtension = dispatchContext.getFileExtension();
        nameSuffix = dispatchContext.getNameSuffix();
        jobExecutionContext = dispatchContext.getJobExecutionContext();

        //Custom Trusted Store Certificate Options
        String trustedStorePath = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.file");
        String trustedStorePassword = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.password");

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
        String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL");
        logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl);

        if ((smtphost == null) || smtphost.trim().equals(""))
            throw new Exception("Smtp host not configured");
        String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
        if ((from == null) || from.trim().equals(""))
            from = "spagobi.scheduler@eng.it";

        int smptPort = 25;

        if ((smtpport == null) || smtpport.trim().equals("")) {
            throw new Exception("Smtp host not configured");
        } else {
            smptPort = Integer.parseInt(smtpport);
        }

        String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");

        /*
        if( (user==null) || user.trim().equals(""))
           throw new Exception("Smtp user not configured");
                
        if( (pass==null) || pass.trim().equals(""))
           throw new Exception("Smtp password not configured");
        */

        String mailTos = "";
        List dlIds = dispatchContext.getDlIds();
        Iterator it = dlIds.iterator();
        while (it.hasNext()) {

            Integer dlId = (Integer) it.next();
            DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);

            List emails = new ArrayList();
            emails = dl.getEmails();
            Iterator j = emails.iterator();
            while (j.hasNext()) {
                Email e = (Email) j.next();
                String email = e.getEmail();
                String userTemp = e.getUserId();
                IEngUserProfile userProfile = GeneralUtilities.createNewUserProfile(userTemp);
                if (ObjectsAccessVerifier.canSee(document, userProfile)) {
                    if (j.hasNext()) {
                        mailTos = mailTos + email + ",";
                    } else {
                        mailTos = mailTos + email;
                    }
                }

            }
        }

        if ((mailTos == null) || mailTos.trim().equals("")) {
            throw new Exception("No recipient address found");
        }

        String[] recipients = mailTos.split(",");
        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.port", Integer.toString(smptPort));

        Session session = null;

        if (StringUtilities.isEmpty(user) || StringUtilities.isEmpty(pass)) {
            props.put("mail.smtp.auth", "false");
            session = Session.getInstance(props);
            logger.debug("Connecting to mail server without authentication");
        } else {
            props.put("mail.smtp.auth", "true");
            Authenticator auth = new SMTPAuthenticator(user, pass);
            //SSL Connection
            if (smtpssl.equals("true")) {
                Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
                //props.put("mail.smtp.debug", "true");          
                props.put("mail.smtps.auth", "true");
                props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort));
                if ((!StringUtilities.isEmpty(trustedStorePath))) {
                    /* Dynamic configuration of trustedstore for CA
                     * Using Custom SSLSocketFactory to inject certificates directly from specified files
                     */
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY);

                } else {
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY);
                }
                props.put("mail.smtp.socketFactory.fallback", "false");
            }
            session = Session.getInstance(props, auth);
            logger.debug("Connecting to mail server with authentication");
        }

        // create a message
        Message msg = new MimeMessage(session);
        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        // Setting the Subject and Content Type
        IMessageBuilder msgBuilder = MessageBuilderFactory.getMessageBuilder();
        String subject = document.getName() + nameSuffix;
        msg.setSubject(subject);
        // create and fill the first message part
        //MimeBodyPart mbp1 = new MimeBodyPart();
        //mbp1.setText(mailTxt);
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message
        SchedulerDataSource sds = new SchedulerDataSource(executionOutput, contentType,
                document.getName() + nameSuffix + fileExtension);
        mbp2.setDataHandler(new DataHandler(sds));
        mbp2.setFileName(sds.getName());
        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        //mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        // add the Multipart to the message
        msg.setContent(mp);
        // send message
        if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) {
            //USE SSL Transport comunication with SMTPS
            Transport transport = session.getTransport("smtps");
            transport.connect(smtphost, smptPort, user, pass);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } else {
            //Use normal SMTP
            Transport.send(msg);
        }

        if (jobExecutionContext.getNextFireTime() == null) {
            String triggername = jobExecutionContext.getTrigger().getName();
            dlIds = dispatchContext.getDlIds();
            it = dlIds.iterator();
            while (it.hasNext()) {
                Integer dlId = (Integer) it.next();
                DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);
                DAOFactory.getDistributionListDAO().eraseDistributionListObjects(dl,
                        (document.getId()).intValue(), triggername);
            }
        }
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
        return false;
    } finally {
        logger.debug("OUT");
    }

    return true;
}

From source file:org.collectionspace.chain.csp.webui.userdetails.UserDetailsReset.java

private Boolean doEmail(String csid, String emailparam, Request in, JSONObject userdetails)
        throws UIException, JSONException {

    String token = createToken(csid);
    EmailData ed = spec.getEmailData();//w w  w. jav  a  2 s . c  o  m
    String[] recipients = new String[1];

    /* ABSTRACT EMAIL STUFF : WHERE do we get the content of emails from? cspace-config.xml */
    String messagebase = ed.getPasswordResetMessage();
    String link = ed.getBaseURL() + ed.getLoginUrl() + "?token=" + token + "&email=" + emailparam;
    String message = messagebase.replaceAll("\\{\\{link\\}\\}", link);
    String greeting = userdetails.getJSONObject("fields").getString("screenName");
    message = message.replaceAll("\\{\\{greeting\\}\\}", greeting);
    message = message.replaceAll("\\\\n", "\\\n");
    message = message.replaceAll("\\\\r", "\\\r");

    String SMTP_HOST_NAME = ed.getSMTPHost();
    String SMTP_PORT = ed.getSMTPPort();
    String subject = ed.getPasswordResetSubject();
    String from = ed.getFromAddress();
    if (ed.getToAddress().isEmpty()) {
        recipients[0] = emailparam;
    } else {
        recipients[0] = ed.getToAddress();
    }
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    boolean debug = false;

    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", ed.doSMTPAuth());
    props.put("mail.debug", ed.doSMTPDebug());
    props.put("mail.smtp.port", SMTP_PORT);

    Session session = Session.getDefaultInstance(props);
    // XXX fix to allow authpassword /username

    session.setDebug(debug);

    Message msg = new MimeMessage(session);
    InternetAddress addressFrom;
    try {
        addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

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

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setText(message);

        Transport.send(msg);
    } catch (AddressException e) {
        throw new UIException("AddressException: " + e.getMessage());
    } catch (MessagingException e) {
        throw new UIException("MessagingException: " + e.getMessage());
    }

    return true;
}

From source file:UserInfo_Frame.java

private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port ", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("anhduc.nguyen77000@gmail.com", "Matmachung020587");
        }//from   w  ww  .  j ava 2  s .c  o m
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("anhduc.nguyen77000@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("oracle.submit@gmail.com"));
        message.setSubject("hi this is me");
        message.setText("hi how are you, i am fine");
        Transport.send(message);
        JOptionPane.showMessageDialog(null, "message sent");
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
}

From source file:org.springfield.lou.application.types.EuscreenxlitemApplication.java

public void sendContentProviderMail(Screen s, String data) {
    //System.out.println("Send mail to CP: " + data);

    JSONObject form = (JSONObject) JSONValue.parse(data);

    String mailfrom = "euscreen-portal@noterik.nl";
    String mailsubject = "Somebody showed interest in your item on EUScreen";
    String email = (String) form.get("email");
    String id = (String) form.get("identifier");
    String provider = (String) form.get("provider");
    String subject = (String) form.get("subject");
    String title = (String) form.get("title");
    String message = (String) form.get("message");
    message = message.replaceAll("(\r\n|\n)", "<br />");

    //Form validation
    JSONObject mailResponse = new JSONObject();
    Set<String> keys = form.keySet();
    boolean errors = false;
    for (String key : keys) {
        String value = (String) form.get(key);
        if (value == null || value.isEmpty()) {
            errors = true;/*from   w  ww. ja  v a 2  s .  c  om*/
            break;
        }
    }

    if (errors) {
        mailResponse.put("status", "false");
        mailResponse.put("message", "Please fill in all the fields.");
        s.putMsg("copyright", "", "showMailResponse(" + mailResponse + ")");
        return;
    }

    String toemail = null;
    //Find the provider email
    FsNode providerNode = Fs.getNode("/domain/euscreenxl/user/" + provider + "/account/default");
    toemail = providerNode.getProperty("email");

    String body = "Identifier: " + id + "<br/>";
    body += "Title: " + title + "<br/>";
    body += "Link to item on EUScreen:<br/>";
    body += "<a href=\"http://euscreen.eu/item.html?id=" + id + "\">http://euscreen.eu/item.html?id=" + id
            + "</a><br/>";
    body += "-------------------------------------------<br/><br/>";
    body += "Subject: " + subject + "<br/>";
    body += "Message:<br/>";
    body += message + "<br/><br/>";
    body += "-------------------------------------------<br/>";
    body += "You can contact the sender of this message on: <a href=\"mailto:" + email + "\">" + email
            + "</a><br/>";

    if (this.inDevelMode()) { //In devel mode always send the email to the one filled in the form
        toemail = email;
    }

    //!!! Hack to send the email to the one filled in the form (for testing purposes). When on production it should be removed
    //toemail = email;

    boolean success = true;
    if (toemail != null) {
        try {
            Context initCtx = new InitialContext();
            Context envCtx = (Context) initCtx.lookup("java:comp/env");
            Session session = (Session) envCtx.lookup("mail/Session");

            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(mailfrom));
            InternetAddress to[] = new InternetAddress[1];
            to[0] = new InternetAddress(toemail);
            msg.setRecipients(Message.RecipientType.TO, to);

            InternetAddress bcc[] = new InternetAddress[1];
            bcc[0] = new InternetAddress("r.rozendal@noterik.nl");
            msg.setRecipients(Message.RecipientType.BCC, bcc);

            msg.setSubject(mailsubject);
            msg.setContent(body, "text/html");
            Transport.send(msg);
        } catch (Exception e) {
            System.out.println("Failed sending email: " + e);
            success = false;
        }
    } else {
        success = false;
    }

    String response = "Your message has been successfuly sent.";
    if (!success)
        response = "There was a problem sending your mail.<br/>Please try again later.";

    mailResponse.put("status", Boolean.toString(success));
    mailResponse.put("message", response);

    s.putMsg("copyright", "", "showMailResponse(" + mailResponse + ")");

}

From source file:com.alvexcore.repo.emails.impl.ExtendedEmailMessage.java

@Override
public void send(List<String> to, List<String> cc, List<String> bcc, String subject, String body,
        List<NodeRef> attachments, boolean html) throws Exception {
    EmailConfig config = getConfig();// w  w  w. ja  v a2s  .  co  m
    EmailProvider provider = getEmailProvider(config.getProviderId());
    Properties props = System.getProperties();
    String prefix = "mail." + provider.getOutgoingProto() + ".";
    props.put(prefix + "host", provider.getOutgoingServer());
    props.put(prefix + "port", provider.getOutgoingPort());
    props.put(prefix + "auth", "true");
    Session session = Session.getInstance(props, null);
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(config.getAddress(), config.getRealName()));
    if (to != null) {
        InternetAddress[] recipients = new InternetAddress[to.size()];
        for (int i = 0; i < to.size(); i++)
            recipients[i] = new InternetAddress(to.get(i));
        msg.setRecipients(Message.RecipientType.TO, recipients);
    }

    if (cc != null) {
        InternetAddress[] recipients = new InternetAddress[cc.size()];
        for (int i = 0; i < cc.size(); i++)
            recipients[i] = new InternetAddress(cc.get(i));
        msg.setRecipients(Message.RecipientType.CC, recipients);
    }

    if (bcc != null) {
        InternetAddress[] recipients = new InternetAddress[bcc.size()];
        for (int i = 0; i < bcc.size(); i++)
            recipients[i] = new InternetAddress(bcc.get(i));
        msg.setRecipients(Message.RecipientType.BCC, recipients);
    }

    msg.setSubject(subject);
    msg.setHeader("X-Mailer", "Alvex Emailer");
    msg.setSentDate(new Date());

    MimeBodyPart messageBodyPart = new MimeBodyPart();
    Multipart multipart = new MimeMultipart();

    if (body != null) {
        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(body, "utf-8", html ? "html" : "plain");
        multipart.addBodyPart(messageBodyPart);
    }

    if (attachments != null)
        for (NodeRef att : attachments) {
            messageBodyPart = new MimeBodyPart();
            String fileName = (String) nodeService.getProperty(att, AlvexContentModel.PROP_EMAIL_REAL_NAME);
            messageBodyPart
                    .setDataHandler(new DataHandler(new RepositoryDataSource(att, fileName, contentService)));
            messageBodyPart.setFileName(fileName);
            multipart.addBodyPart(messageBodyPart);
        }

    msg.setContent(multipart);

    SMTPTransport t = (SMTPTransport) session.getTransport(provider.getOutgoingProto());
    t.connect(config.getUsername(), config.getPassword());
    t.sendMessage(msg, msg.getAllRecipients());
    t.close();
}