Example usage for javax.mail.internet MimeMessage getAllRecipients

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

Introduction

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

Prototype

@Override
public Address[] getAllRecipients() throws MessagingException 

Source Link

Document

Get all the recipient addresses for the message.

Usage

From source file:tsuboneSystem.original.manager.MailManager.java

/**
 * ?/*from ww  w.ja v  a2 s.  c  om*/
 * @return
 */
public boolean sendMail() {

    //???TRUE
    if (!check()) {
        return false;
    }
    Properties objPrp = new Properties();
    objPrp.setProperty("mail.smtp.host", "smtp.gmail.com");
    objPrp.setProperty("mail.smtp.port", "465");
    objPrp.setProperty("mail.smtp.auth", "true");

    //
    objPrp.setProperty("mail.smtp.connectiontimeout", "5000");
    objPrp.setProperty("mail.smtp.timeout", "5000");

    //???????????JavaMail?Message-ID?????
    objPrp.setProperty("mail.user", "kagucho.net@gmail.com");
    objPrp.setProperty("mail.host", "smtp.gmail.com");

    //????????
    objPrp.setProperty("mail.debug", "true");

    // SSL
    objPrp.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    objPrp.setProperty("mail.smtp.socketFactory.fallback", "false");
    objPrp.setProperty("mail.smtp.socketFactory.port", "465");

    String address = ConfigUtil.getConfig("mail.address");
    String pw = ConfigUtil.getConfig("mail.pw");

    // 
    Session session = Session.getInstance(objPrp, new PlainAuthenticator(address, pw));
    // ??
    MimeMessage objMsg = new MimeMessage(session);

    try {
        // ?
        objMsg.setFrom(new InternetAddress(address, displayName));

        // ??
        objMsg.setSubject(title, encoding);

        // ?TO????CCBCC?
        objMsg.setRecipients(Message.RecipientType.BCC, getToAddress());

        // 
        objMsg.setText(getContent(), encoding);

        // ?
        SMTPTransport t = (SMTPTransport) session.getTransport("smtp");
        try {
            t.connect("smtp.gmail.com", address, pw);
            t.sendMessage(objMsg, objMsg.getAllRecipients());
        } finally {
            t.close();
        }
        return false;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return true;
    } catch (MessagingException e) {
        e.printStackTrace();
        return true;
    }
}

From source file:org.apache.james.James.java

/**
 * Place a mail on the spool for processing
 *
 * @param message the message to send//  ww w . j  a v  a 2  s . com
 *
 * @throws MessagingException if an exception is caught while placing the mail
 *                            on the spool
 */
public void sendMail(MimeMessage message) throws MessagingException {
    MailAddress sender = new MailAddress((InternetAddress) message.getFrom()[0]);
    Collection recipients = new HashSet();
    Address addresses[] = message.getAllRecipients();
    if (addresses != null) {
        for (int i = 0; i < addresses.length; i++) {
            // Javamail treats the "newsgroups:" header field as a
            // recipient, so we want to filter those out.
            if (addresses[i] instanceof InternetAddress) {
                recipients.add(new MailAddress((InternetAddress) addresses[i]));
            }
        }
    }
    sendMail(sender, recipients, message);
}

From source file:fsi_admin.JSmtpConn.java

private boolean sendMsg(String HOST, String USERNAME, String PASSWORD, StringBuffer msj, Session session,
        MimeMessage mmsg, MimeMultipart multipart) {
    try {//w  w w. j ava  2 s.c o  m
        mmsg.setContent(multipart);
        // Create a transport.        
        Transport transport = session.getTransport();
        // Send the message.
        System.out.println(HOST + " " + USERNAME + " " + PASSWORD);
        transport.connect(HOST, USERNAME, PASSWORD);
        // Send the email.
        transport.sendMessage(mmsg, mmsg.getAllRecipients());
        transport.close();

        return true;
    } catch (MessagingException e) {
        e.printStackTrace();
        msj.append("Error de Mensajeria al enviar SMTP: " + e.getMessage());
        return false;
    } catch (Exception ex) {
        ex.printStackTrace();
        msj.append("Error general de mensaje al enviar SMTP: " + ex.getMessage());
        return false;
    }

}

From source file:com.fstx.stdlib.common.messages.MailSenderImpl.java

/**
 * @see com.ess.messages.MailSender#send()
 *//*w w  w. j ava  2s.c o m*/
public boolean send() {

    try {
        // 2005-11-27 RSC always requires authentication.
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");

        props.put("mail.smtp.host", host.getAddress());
        /*
         * 2005-11-27 RSC
         * Since webmail.us is starting to make other ports available
         * as Comcast blocks port 25.
         */
        props.put("mail.smtp.port", host.getPort());

        Session s = Session.getInstance(props, null);

        MimeMessage messageOut = new MimeMessage(s);

        InternetAddress fromOut = new InternetAddress(from.getAddress());

        //reid 2004-12-20
        fromOut.setPersonal(from.getName());

        messageOut.setFrom(fromOut);

        InternetAddress toOut = new InternetAddress(this.to.getAddress());

        //reid 2004-12-20
        toOut.setPersonal(to.getName());

        messageOut.addRecipient(javax.mail.Message.RecipientType.TO, toOut);

        messageOut.setSubject(message.getSubject());

        messageOut.setText(message.getMessage());

        if (host.useAuthentication()) {

            Transport transport = s.getTransport("smtp");
            transport.connect(host.getAddress(), host.getUsername(), host.getPassword());
            transport.sendMessage(messageOut, messageOut.getAllRecipients());
            transport.close();
        } else {

            Transport.send(messageOut);
        }

    } catch (Exception e) {
        log.info("\n\nMailSenderIMPL3: " + host.getAddress());
        e.printStackTrace();
        throw new RuntimeException(e);
    }

    return true;
}

From source file:org.jumpmind.metl.core.runtime.flow.FlowRuntime.java

protected void sendNotifications(Notification.EventType eventType) {
    if (notifications != null && notifications.size() > 0) {
        Transport transport = null;/*from  w  ww .  j  a  v a2s.c o  m*/
        Date date = new Date();
        flowParameters.put("_date", DateFormatUtils.format(date, DATE_FORMAT));
        flowParameters.put("_time", DateFormatUtils.format(date, TIME_FORMAT));

        try {
            for (Notification notification : notifications) {
                if (notification.getEventType().equals(eventType.toString())) {
                    log.info("Sending notification '" + notification.getName() + "' of level '"
                            + notification.getLevel() + "' and type '" + notification.getNotifyType() + "'");
                    transport = mailSession.getTransport();
                    MimeMessage message = new MimeMessage(mailSession.getSession());
                    message.setSentDate(new Date());
                    message.setRecipients(RecipientType.BCC, notification.getRecipients());
                    message.setSubject(
                            FormatUtils.replaceTokens(notification.getSubject(), flowParameters, true));
                    message.setText(FormatUtils.replaceTokens(notification.getMessage(), flowParameters, true));
                    try {
                        transport.sendMessage(message, message.getAllRecipients());
                    } catch (MessagingException e) {
                        log.error("Failure while sending notification", e);
                    }
                }
            }
        } catch (MessagingException e) {
            log.error("Failure while preparing notification", e);
        } finally {
            mailSession.closeTransport(transport);
        }
    }
}

From source file:mx.uatx.tesis.managebeans.RecuperarCuentaMB.java

public void enviarCorreo(String nombre, String apellido, String corre, String password2) throws Exception {

    String passwordDesencriptada = Desencriptar(password2);

    try {//from   www . j  a  va 2 s  .  c o m
        // Propiedades de la conexin
        Properties props = new Properties();
        props.setProperty("mail.smtp.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.starttls.enable", "true");
        props.setProperty("mail.smtp.port", "587");
        props.setProperty("mail.smtp.user", "alfons018pbg@gmail.com");
        props.setProperty("mail.smtp.auth", "true");

        // Preparamos la sesion
        Session session = Session.getDefaultInstance(props);

        // Construimos el mensaje
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("alfons018pbg@gmail.com"));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress("" + corre + ""));
        message.setSubject("Asistencia tcnica");
        message.setText("\n \n \n Estimado:  " + nombre + "  " + apellido
                + "\n El Servicio Tecnico de SEA ha recibido tu solicitud. "
                + "\n Los siguientes son tus datos para acceder:" + "\n Correo:    " + corre + "\n Password: "
                + passwordDesencriptada + "");

        // Lo enviamos.
        Transport t = session.getTransport("smtp");
        t.connect("alfons018pbg@gmail.com", "al12fo05zo1990");
        t.sendMessage(message, message.getAllRecipients());

        // Cierre.
        t.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.fsrin.menumine.common.message.MailSenderImpl.java

/**
 * @see com.ess.messages.MailSender#send()
 *///w w  w.j  a v a2s.  c  om
public boolean send() {

    try {

        Properties props = new Properties();

        props.put("mail.smtp.host", host.getAddress());

        if (host.useAuthentication()) {

            props.put("mail.smtp.auth", "true");
        }

        Session s = Session.getInstance(props, null);

        s.setDebug(true);

        //            PasswordAuthentication pa = new PasswordAuthentication(host
        //                    .getUsername(), host.getPassword());
        //
        //            URLName url = new URLName(host.getAddress());
        //
        //            s.setPasswordAuthentication(url, pa);

        MimeMessage messageOut = new MimeMessage(s);

        InternetAddress fromOut = new InternetAddress(from.getAddress());

        //reid 2004-12-20
        fromOut.setPersonal(from.getName());

        messageOut.setFrom(fromOut);

        InternetAddress toOut = new InternetAddress(this.to.getAddress());

        //reid 2004-12-20
        toOut.setPersonal(to.getName());

        messageOut.addRecipient(javax.mail.Message.RecipientType.TO, toOut);

        messageOut.setSubject(message.getSubject());

        messageOut.setText(message.getMessage());

        if (host.useAuthentication()) {

            Transport transport = s.getTransport("smtp");
            transport.connect(host.getAddress(), host.getUsername(), host.getPassword());
            transport.sendMessage(messageOut, messageOut.getAllRecipients());
            transport.close();
        } else {

            Transport.send(messageOut);
        }

    } catch (Exception e) {
        log.info("\n\nMailSenderIMPL3: " + host.getAddress());

        e.printStackTrace();
        throw new RuntimeException(e);

    }

    return true;
}

From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java

/**
 * Send a Collection of Mails (multiple emails)
 * /*from w  w w.j av  a 2  s  . co m*/
 * @param emails Mail Collection
 * @return True in any case (TODO ?)
 */
public boolean sendMails(Collection<Mail> emails, MailConfiguration mailConfiguration, XWikiContext context)
        throws MessagingException, UnsupportedEncodingException {
    Session session = null;
    Transport transport = null;
    int emailCount = emails.size();
    int count = 0;
    int sendFailedCount = 0;
    try {
        for (Iterator<Mail> emailIt = emails.iterator(); emailIt.hasNext();) {
            count++;

            Mail mail = emailIt.next();
            LOGGER.info("Sending email: " + mail.toString());

            if ((transport == null) || (session == null)) {
                // initialize JavaMail Session and Transport
                Properties props = initProperties(mailConfiguration);
                session = Session.getInstance(props, null);
                transport = session.getTransport("smtp");
                if (!mailConfiguration.usesAuthentication()) {
                    // no auth info - typical 127.0.0.1 open relay scenario
                    transport.connect();
                } else {
                    // auth info present - typical with external smtp server
                    transport.connect(mailConfiguration.getSmtpUsername(), mailConfiguration.getSmtpPassword());
                }
            }

            try {
                MimeMessage message = createMimeMessage(mail, session, context);
                if (message == null) {
                    continue;
                }

                transport.sendMessage(message, message.getAllRecipients());

                // close the connection every other 100 emails
                if ((count % 100) == 0) {
                    try {
                        if (transport != null) {
                            transport.close();
                        }
                    } catch (MessagingException ex) {
                        LOGGER.error("MessagingException has occured.", ex);
                    }
                    transport = null;
                    session = null;
                }
            } catch (SendFailedException ex) {
                sendFailedCount++;
                LOGGER.error("SendFailedException has occured.", ex);
                LOGGER.error("Detailed email information" + mail.toString());
                if (emailCount == 1) {
                    throw ex;
                }
                if ((emailCount != 1) && (sendFailedCount > 10)) {
                    throw ex;
                }
            } catch (MessagingException mex) {
                LOGGER.error("MessagingException has occured.", mex);
                LOGGER.error("Detailed email information" + mail.toString());
                if (emailCount == 1) {
                    throw mex;
                }
            } catch (XWikiException e) {
                LOGGER.error("XWikiException has occured.", e);
            } catch (IOException e) {
                LOGGER.error("IOException has occured.", e);
            }
        }
    } finally {
        try {
            if (transport != null) {
                transport.close();
            }
        } catch (MessagingException ex) {
            LOGGER.error("MessagingException has occured.", ex);
        }

        LOGGER.info("sendEmails: Email count = " + emailCount + " sent count = " + count);
    }
    return true;
}

From source file:org.xwiki.mail.internal.DefaultMailSenderThread.java

/**
 * Send the mail.//from  www. j a v  a2 s  . co m
 *
 * @param item the queue item containing all the data for sending the mail
 */
protected void sendMail(MailSenderQueueItem item) {
    MimeMessage message = item.getMessage();
    MailResultListener listener = item.getListener();

    try {
        // Step 1: If the current Session in use is different from the one passed then close the current Transport,
        // get a new one and reconnect. Also do that every 100 mails sent.
        // TODO: explain why!
        // TODO: Also explain why we don't use Transport.send()
        if (item.getSession() != this.currentSession || (this.count % 100) == 0) {
            closeTransport();
            this.currentSession = item.getSession();
            this.currentTransport = this.currentSession.getTransport("smtp");
            this.currentTransport.connect();
        } else if (!this.currentTransport.isConnected()) {
            this.currentTransport.connect();
        }

        // Step 2: Send the mail
        this.currentTransport.sendMessage(message, message.getAllRecipients());
        this.count++;

        // Step 3: Notify the user of the success if a listener has been provided
        if (listener != null) {
            listener.onSuccess(message);
        }
    } catch (Exception e) {
        // An error occurred, notify the user if a listener has been provided
        if (listener != null) {
            listener.onError(message, e);
        }
    }
}

From source file:cz.filmtit.userspace.Emailer.java

/**
 * Sends an email with parameters that has been collected before in the fields of the class.
 * @return Sign if the email has been successfully sent
 *//*ww  w.j a  v a 2 s.  com*/
public boolean send() {
    if (hasCollectedData()) {
        // send mail;
        javax.mail.Session session;
        logger.info("Emailer",
                "Create session for mail login " + (String) configuration.getProperty("mail.filmtit.address")
                        + " password" + (String) configuration.getProperty("mail.filmtit.password"));
        session = javax.mail.Session.getDefaultInstance(configuration, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication((String) configuration.getProperty("mail.filmtit.address"),
                        (String) configuration.getProperty("mail.filmtit.password"));
            }
        });
        session.setDebug(true);
        javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(session);
        try {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(this.email));
            message.setFrom(new InternetAddress((String) configuration.getProperty("mail.filmtit.address")));
            message.setSubject(this.subject);
            message.setText(this.message);

            Transport transportSSL = session.getTransport();
            transportSSL.connect((String) configuration.getProperty("mail.smtps.host"),
                    Integer.parseInt(configuration.getProperty("mail.smtps.port")),
                    (String) configuration.getProperty("mail.filmtit.address"),
                    (String) configuration.getProperty("mail.filmtit.password")); // account used
            transportSSL.sendMessage(message, message.getAllRecipients());
            transportSSL.close();
        } catch (MessagingException ex) {
            logger.error("Emailer", "An error while sending an email. " + ex);
        }
        return true;
    }
    logger.warning("Emailer", "Emailer has not collected all data to be able to send an email.");
    return false;
}