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.bizintelapps.cars.service.impl.EmailServiceImpl.java

/**
 * /*w  w  w.  j  a v  a  2  s .  c  o m*/
 * @param recipients
 * @param subject
 * @param message
 * @param from
 * @throws MessagingException
 */
private void sendSSMessage(String recipients[], String subject, Car car, String comment) {

    try {
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            if (recipients[i] != null && recipients[i].length() > 0) {

                addressTo[i] = new InternetAddress(recipients[i]);

            }
        }

        if (addressTo == null || addressTo.length == 0) {
            return;
        }

        boolean debug = true;

        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "true");
        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, new javax.mail.Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(SEND_FROM_USERNAME, SEND_FROM_PASSWORD);
            }
        });

        session.setDebug(debug);

        Message msg = new MimeMessage(session);
        InternetAddress addressFrom = new InternetAddress(EMAIL_FROM_ADDRESS);
        msg.setFrom(addressFrom);
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        // Setting the Subject and Content Type
        msg.setSubject(subject);
        String message = buildMessage(car, comment);
        msg.setContent(message, EMAIL_CONTENT_TYPE);

        Transport.send(msg);
    } catch (Exception ex) {
        logger.warn(ex.getMessage(), ex);
        throw new RuntimeException("Error sending email, please check to and from emails are correct!");
    }
}

From source file:org.data2semantics.yasgui.selenium.FailNotification.java

private void sendMail(String subject, String content, String fileName) {
    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.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(baseTest.props.getMailUserName(),
                    baseTest.props.getMailPassWord());
        }/* w w w . j  a  v  a2 s . c  o  m*/
    });

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(baseTest.props.getMailUserName()));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(baseTest.props.getMailSendTo()));
        message.setSubject(subject);
        message.setContent(content, "text/html; charset=utf-8");

        MimeBodyPart messageBodyPart = new MimeBodyPart();
        // message body
        messageBodyPart.setContent(content, "text/html; charset=utf-8");
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        // attachment
        messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(fileName);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("screenshot.png");
        multipart.addBodyPart(messageBodyPart);
        message.setContent(multipart);

        Transport.send(message);

        System.out.println("Email send");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:Utilities.SendEmailUsingGMailSMTP.java

public void enviarCorreo(String correo, String clave) {
    String to = correo;/*  w  w w . ja va 2s . c o  m*/

    final String username = "angelicabarrientosvera@gmail.com";//change accordingly
    final String password = "90445359D10s";//change accordingly

    // Assuming you are sending email through relay.jangosmtp.net
    String host = "smtp.gmail.com";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.ssl.trust", "smtp.gmail.com");

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    try {
        // Create a default MimeMessage object.
        Message message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(to));

        // Set To: header field of the header.
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set Subject: header field
        message.setSubject("Testing Subject");

        // Now set the actual message
        message.setText("\n" + "Use esta clave para poder restablecer la contrasea" + "\n"
                + "Tu cdigo para restaurar su cuenta es:" + clave);

        // Send message
        Transport.send(message);

        System.out.println("Sent message successfully....");
        //return true;

    } catch (MessagingException e) {
        throw new RuntimeException(e);

    }

}

From source file:transport.java

public void go(Session session, InternetAddress[] toAddr, InternetAddress from) {
    Transport trans = null;/*ww  w . j  av a 2s  .  c  om*/

    try {
        // create a message
        Message msg = new MimeMessage(session);
        msg.setFrom(from);
        msg.setRecipients(Message.RecipientType.TO, toAddr);
        msg.setSubject("JavaMail APIs transport.java Test");
        msg.setSentDate(new Date()); // Date: header
        msg.setContent(msgText + msgText2, "text/plain");
        msg.saveChanges();

        // get the smtp transport for the address
        trans = session.getTransport(toAddr[0]);

        // register ourselves as listener for ConnectionEvents 
        // and TransportEvents
        trans.addConnectionListener(this);
        trans.addTransportListener(this);

        // connect the transport
        trans.connect();

        // send the message
        trans.sendMessage(msg, toAddr);

        // give the EventQueue enough time to fire its events
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }

    } catch (MessagingException mex) {
        // give the EventQueue enough time to fire its events
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }

        System.out.println("Sending failed with exception:");
        mex.printStackTrace();
        System.out.println();
        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    System.out.println("    ** Invalid Addresses");
                    for (int i = 0; i < invalid.length; i++)
                        System.out.println("         " + invalid[i]);
                }
                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    System.out.println("    ** ValidUnsent Addresses");
                    for (int i = 0; i < validUnsent.length; i++)
                        System.out.println("         " + validUnsent[i]);
                }
                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    System.out.println("    ** ValidSent Addresses");
                    for (int i = 0; i < validSent.length; i++)
                        System.out.println("         " + validSent[i]);
                }
            }
            System.out.println();
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    } finally {
        try {
            // close the transport
            if (trans != null)
                trans.close();
        } catch (MessagingException mex) {
            /* ignore */ }
    }
}

From source file:Security.EmailSender.java

/**
 * Metda sendUerAuthEmail sli na generovanie a zaslanie potvrdzovacieho emailu, ktor sli na overenie zadanho emailu pouvatea, novo registrovanmu pouvateovi.
 * @param email - emailov adresa pouvatea, ktormu bude zalan email
 * @param userToken - jedine?n 32 znakov identifiktor registrcie pouvatea
 * @param firstName - krstn meno pouvatea
 * @param lastName - priezvisko pouvatea
 *//*from w  w  w.  j  a  v a  2 s .  c o m*/
public void sendUserAuthEmail(String email, String userToken, String firstName, String lastName) {
    String name = "NONE";
    String surname = "NONE";
    if (firstName != null) {
        name = firstName;
    }
    if (lastName != null) {
        surname = lastName;
    }

    Properties props = new Properties();
    props.put("mail.smtp.host", server);
    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(userName, password);
        }
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("skuska.api.3@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject("Confirmation email from GPSWebApp server!!!");
        //message.setText(userToken);
        message.setSubject("Confirmation email from GPSWebApp server!!!");
        if (system.startsWith("Windows")) {
            message.setContent("<html><head><meta charset=\"Windows-1250\"></head><body><h1>Hello " + name + " "
                    + surname
                    + ", please confirm your email by clicking on link ...</h1><a href=http://localhost:8084/GPSWebApp/TryToAcceptUser.jsp?token="
                    + userToken + "&email=" + email + ">LINK</a></body></html>", "text/html");
        } else {
            message.setContent("<html><head><meta charset=\"Windows-1250\"></head><body><h1>Hello " + name + " "
                    + surname
                    + ", please confirm your email by clicking on link ...</h1><a href=http://gps.kpi.fei.tuke.sk/TryToAcceptUser.jsp?token="
                    + userToken + "&email=" + email + ">LINK</a></body></html>", "text/html");
        }

        Transport.send(message);

        FileLogger.getInstance().createNewLog("Successfuly sent email to user " + email + ".");

    } catch (MessagingException e) {
        FileLogger.getInstance().createNewLog("ERROR: cannot sent email to user " + email + ".");
    }

}

From source file:gov.nih.nci.cacis.cdw.CDWPendingLoader.java

public void loadPendingCDWDocuments(CDWLoader loader) {
    LOG.debug("Pending folder: " + cdwLoadPendingDirectory);
    LOG.info("SSSSSSS STARTED CDW LOAD SSSSSSSS");
    File pendingFolder = new File(cdwLoadPendingDirectory);
    FilenameFilter loadFileFilter = new FilenameFilter() {

        public boolean accept(File dir, String name) {
            return true;
        }/*  ww w.  j  a v  a 2 s .c om*/
    };
    String[] loadFileNames = pendingFolder.list(loadFileFilter);
    LOG.info("Total Files to Load: " + loadFileNames.length);
    int filesLoaded = 0;
    int fileNumber = 0;
    for (String fileName : loadFileNames) {
        fileNumber++;
        LOG.info("Processing File [" + fileNumber + "] " + fileName);
        File loadFile = new File(cdwLoadPendingDirectory + "/" + fileName);
        try {
            final String[] params = StringUtils.split(fileName, "@@");
            String siteId = params[0];
            String studyId = params[1];
            String patientId = params[2];
            LOG.debug("SiteId: " + siteId);

            // the below code is not working, so parsing the file name for attributes.
            // DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            // DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            // Document document = documentBuilder.parse(loadFile);
            // XPathFactory factory = XPathFactory.newInstance();
            // XPath xPath = factory.newXPath();
            // String siteID = xPath.evaluate("/caCISRequest/clinicalMetaData/@siteIdRoot", document);

            loader.load(FileUtils.getStringFromFile(loadFile), loader.generateContext(), studyId, siteId,
                    patientId);
            LOG.info(String.format("Successfully processed file [%s] [%s] and moving into [%s]", fileNumber,
                    loadFile.getAbsolutePath(), cdwLoadProcessedDirectory));
            org.apache.commons.io.FileUtils.moveFileToDirectory(loadFile, new File(cdwLoadProcessedDirectory),
                    true);
            filesLoaded++;
        } catch (Exception e) {
            LOG.error(e.getMessage());
            e.printStackTrace();
            try {
                Properties props = new Properties();
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.host", cdwLoadSenderHost);
                props.put("mail.smtp.port", cdwLoadSenderPort);

                Session session = Session.getInstance(props, new javax.mail.Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(cdwLoadSenderUser, cdwLoadSenderPassword);
                    }
                });
                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(cdwLoadSenderAddress));
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(cdwLoadRecipientAddress));
                message.setSubject(cdwLoadNotificationSubject);
                message.setText(cdwLoadNotificationMessage + " [" + e.getMessage() + "]");

                Transport.send(message);
                org.apache.commons.io.FileUtils.moveFileToDirectory(loadFile, new File(cdwLoadErrorDirectory),
                        true);
                // TODO add logic to send email
            } catch (Exception e1) {
                LOG.error(e1.getMessage());
                e1.printStackTrace();
            }
        }
    }
    LOG.info("Files Successfully Loaded: " + filesLoaded);
    LOG.info("EEEEEEE ENDED CDW LOAD EEEEEEE");
}

From source file:sk.mlp.security.EmailSender.java

/**
 * Metda sendUerAuthEmail sli na generovanie a zaslanie potvrdzovacieho emailu, ktor sli na overenie zadanho emailu pouvatea, novo registrovanmu pouvateovi.
 * @param email - emailov adresa pouvatea, ktormu bude zalan email
 * @param userToken - jedine?n 32 znakov identifiktor registrcie pouvatea
 * @param firstName - krstn meno pouvatea
 * @param lastName - priezvisko pouvatea
 *//*from   w w  w  .  ja  v a2  s  . c  o m*/
public void sendUserAuthEmail(String email, String userToken, String firstName, String lastName) {
    String name = "NONE";
    String surname = "NONE";
    if (firstName != null) {
        name = firstName;
    }
    if (lastName != null) {
        surname = lastName;
    }

    Properties props = new Properties();
    props.put("mail.smtp.host", server);
    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(userName, password);
        }
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("skuska.api.3@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject("Confirmation email from gTraxxx app!!!");
        //message.setText(userToken);
        message.setSubject("Confirmation email from gTraxxx app!!!");
        if (system.startsWith("Windows")) {
            message.setContent("<html><head><meta charset=\"Windows-1250\"></head><body><h1>Hello " + name + " "
                    + surname
                    + ", please confirm your email by clicking on link ...</h1><a href=http://localhost:8080/gTraxxx/TryToAcceptUser.jsp?token="
                    + userToken + "&email=" + email + ">LINK</a></body></html>", "text/html");
        } else {
            message.setContent("<html><head><meta charset=\"Windows-1250\"></head><body><h1>Hello " + name + " "
                    + surname
                    + ", please confirm your email by clicking on link ...</h1><a href=http://gps.kpi.fei.tuke.sk/TryToAcceptUser.jsp?token="
                    + userToken + "&email=" + email + ">LINK</a></body></html>", "text/html");
        }

        Transport.send(message);

        FileLogger.getInstance().createNewLog("Successfuly sent email to user " + email + ".");

    } catch (MessagingException e) {
        FileLogger.getInstance().createNewLog("ERROR: cannot sent email to user " + email + ".");
    }

}

From source file:transport.java

public void go(Session session, InternetAddress[] toAddr, InternetAddress from) {
    Transport trans = null;/*from w w w. j  a  v a  2 s . co m*/

    try {
        // create a message
        Message msg = new MimeMessage(session);
        msg.setFrom(from);
        msg.setRecipients(Message.RecipientType.TO, toAddr);
        msg.setSubject("JavaMail APIs transport.java Test");
        msg.setSentDate(new Date()); // Date: header
        msg.setContent(msgText + msgText2, "text/plain");
        msg.saveChanges();

        // get the smtp transport for the address
        trans = session.getTransport(toAddr[0]);

        // register ourselves as listener for ConnectionEvents
        // and TransportEvents
        trans.addConnectionListener(this);
        trans.addTransportListener(this);

        // connect the transport
        trans.connect();

        // send the message
        trans.sendMessage(msg, toAddr);

        // give the EventQueue enough time to fire its events
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }

    } catch (MessagingException mex) {
        // give the EventQueue enough time to fire its events
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }

        mex.printStackTrace();
        System.out.println();
        Exception ex = mex;
        do {
            if (ex instanceof SendFailedException) {
                SendFailedException sfex = (SendFailedException) ex;
                Address[] invalid = sfex.getInvalidAddresses();
                if (invalid != null) {
                    System.out.println("    ** Invalid Addresses");
                    if (invalid != null) {
                        for (int i = 0; i < invalid.length; i++)
                            System.out.println("         " + invalid[i]);
                    }
                }
                Address[] validUnsent = sfex.getValidUnsentAddresses();
                if (validUnsent != null) {
                    System.out.println("    ** ValidUnsent Addresses");
                    if (validUnsent != null) {
                        for (int i = 0; i < validUnsent.length; i++)
                            System.out.println("         " + validUnsent[i]);
                    }
                }
                Address[] validSent = sfex.getValidSentAddresses();
                if (validSent != null) {
                    System.out.println("    ** ValidSent Addresses");
                    if (validSent != null) {
                        for (int i = 0; i < validSent.length; i++)
                            System.out.println("         " + validSent[i]);
                    }
                }
            }
            System.out.println();
            if (ex instanceof MessagingException)
                ex = ((MessagingException) ex).getNextException();
            else
                ex = null;
        } while (ex != null);
    } finally {
        try {
            // close the transport
            trans.close();
        } catch (MessagingException mex) { /* ignore */
        }
    }
}

From source file:net.timbusproject.extractors.pojo.CallBack.java

public void sendEmail(String to, String subject, String body) {
    final String fromUser = fromMail;
    final String passUser = password;
    Properties props = new Properties();
    props.put("mail.smtp.host", smtp);
    props.put("mail.smtp.socketFactory.port", port);
    props.put("mail.smtp.socketFactory.class", socketFactoryClass);
    props.put("mail.smtp.auth", mailAuth);
    props.put("mail.smtp.port", port);
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(fromUser, passUser);
        }//  w w w .  j av  a2  s.c o m
    });
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromUser));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSubject(subject);
        message.setText(body);
        Transport.send(message);
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:Security.EmailSender.java

/**
 * Metda sendUserPasswordRecoveryEmail je ur?en na generovbanie a zaslanie pouvateovi email s obnovenm jeho zabudnutho hesla.
 * @param email - pouvatesk email/*w w w  .  j  av  a2 s .  c  om*/
 */
public void sendUserPasswordRecoveryEmail(String email) {
    try {
        DBLoginFinder finder = new DBLoginFinder();
        ArrayList<String> results = finder.getUserInformation(email);
        String name = "NONE";
        String surname = "NONE";
        if (results.get(0) != null) {
            name = results.get(0);
        }
        if (results.get(1) != null) {
            surname = results.get(1);
        }

        Properties props = new Properties();
        props.put("mail.smtp.host", server);
        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(userName, password);
            }
        });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("skuska.api.3@gmail.com"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
            message.setSubject("Your password to GPSWebApp server!!!");
            //message.setText(userToken);
            message.setSubject("Your password to GPSWebApp server!!!");
            message.setContent("<html><head><meta charset=\"Windows-1250\"></head><body><h1>Hello " + name + " "
                    + surname + ",</h1><br>your paassword to access GPSWebApp server is <b>" + results.get(5)
                    + "</b>. <br>Please take note that you can change it in your settings. Have a pleasant day.</body></html>",
                    "text/html");

            Transport.send(message);

            FileLogger.getInstance()
                    .createNewLog("Successfuly sent password recovery email to user " + email + ".");

        } catch (MessagingException e) {
            FileLogger.getInstance()
                    .createNewLog("ERROR: Cannot sent password recovery email to user " + email + ".");
        }
    } catch (Exception ex) {
        FileLogger.getInstance()
                .createNewLog("ERROR: Cannot sent password recovery email to user " + email + ".");
    }
}