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:org.apache.camel.component.mail.MailBinding.java

public void populateMailMessage(MailEndpoint endpoint, MimeMessage mimeMessage, Exchange exchange)
        throws MessagingException, IOException {

    // camel message headers takes precedence over endpoint configuration
    if (hasRecipientHeaders(exchange)) {
        setRecipientFromCamelMessage(mimeMessage, exchange);
    } else {/*from w w w  .  ja va 2 s.c om*/
        // fallback to endpoint configuration
        setRecipientFromEndpointConfiguration(mimeMessage, endpoint);
    }

    // must have at least one recipients otherwise we do not know where to send the mail
    if (mimeMessage.getAllRecipients() == null) {
        throw new IllegalArgumentException("The mail message does not have any recipients set.");
    }

    // set the subject if it was passed in as an option in the uri. Note: if it is in both the URI
    // and headers the headers win.
    String subject = endpoint.getConfiguration().getSubject();
    if (subject != null) {
        mimeMessage.setSubject(subject, IOConverter.getCharsetName(exchange, false));
    }

    // append the rest of the headers (no recipients) that could be subject, reply-to etc.
    appendHeadersFromCamelMessage(mimeMessage, endpoint.getConfiguration(), exchange);

    if (empty(mimeMessage.getFrom())) {
        // lets default the address to the endpoint destination
        String from = endpoint.getConfiguration().getFrom();
        mimeMessage.setFrom(new InternetAddress(from));
    }

    // if there is an alternative body provided, set up a mime multipart alternative message
    if (hasAlternativeBody(endpoint.getConfiguration(), exchange)) {
        createMultipartAlternativeMessage(mimeMessage, endpoint.getConfiguration(), exchange);
    } else {
        if (exchange.getIn().hasAttachments()) {
            appendAttachmentsFromCamel(mimeMessage, endpoint.getConfiguration(), exchange);
        } else {
            populateContentOnMimeMessage(mimeMessage, endpoint.getConfiguration(), exchange);
        }
    }
}

From source file:com.duroty.service.Mailet.java

/**
 * DOCUMENT ME!//  ww w  .j a v a2s.c o  m
 *
 * @param hfactory DOCUMENT ME!
 * @param username DOCUMENT ME!
 * @param mime DOCUMENT ME!
 */
private void parseContacts(Session hsession, Users user, MimeMessage mime, String box) {
    try {
        Address[] addresses = null;

        Date sentDate = null;
        Date receivedDate = null;

        if (box.equals("SENT")) {
            addresses = mime.getAllRecipients();
            sentDate = mime.getSentDate();

            if (sentDate == null) {
                sentDate = new Date();
            }
        } else {
            addresses = mime.getFrom();
            receivedDate = mime.getReceivedDate();

            if (receivedDate == null) {
                receivedDate = new Date();
            }
        }

        if ((addresses != null) && (addresses.length > 0)) {
            String name = null;
            String email = null;

            for (int i = 0; i < addresses.length; i++) {
                if (addresses[i] instanceof InternetAddress) {
                    InternetAddress xinet = (InternetAddress) addresses[i];

                    name = xinet.getPersonal();

                    if ((name != null) && (name.length() > 49)) {
                        name = name.substring(0, 49);
                    }

                    email = xinet.getAddress();
                } else {
                    email = addresses[i].toString();
                }

                Criteria crit1 = hsession.createCriteria(Contact.class);
                crit1.add(Restrictions.eq("users", user));
                crit1.add(Restrictions.eq("conEmail", email));

                Contact contact = (Contact) crit1.uniqueResult();

                if (contact != null) {
                    if (receivedDate != null) {
                        contact.setConReceivedDate(receivedDate);
                    }

                    if (sentDate != null) {
                        contact.setConSentDate(sentDate);
                    }

                    int freq = contact.getConCount();

                    contact.setConCount(freq + 1);

                    if (!StringUtils.isBlank(name)) {
                        name = name.replaceAll(",", " ");
                        name = name.replaceAll(";", " ");
                        contact.setConName(name);
                    }

                    hsession.update(contact);
                } else {
                    contact = new Contact();
                    contact.setConEmail(email);
                    contact.setConName(name);
                    contact.setConReceivedDate(receivedDate);
                    contact.setConSentDate(sentDate);
                    contact.setConCount(new Integer(1));
                    contact.setUsers(user);

                    hsession.save(contact);
                }

                hsession.flush();

                try {
                    if ((contact.getConSentDate() != null) && (contact.getConReceivedDate() != null)) {
                        Criteria crit2 = hsession.createCriteria(Identity.class);
                        crit2.add(Restrictions.eq("ideEmail", email));
                        crit2.add(Restrictions.eq("ideActive", new Boolean(true)));

                        List list = crit2.list();

                        if (list != null) {
                            Iterator scroll = list.iterator();

                            while (scroll.hasNext()) {
                                Identity identity = (Identity) scroll.next();
                                Users buddy = identity.getUsers();

                                if ((buddy != null) && (user.getUseIdint() != buddy.getUseIdint())) {
                                    Criteria auxCrit = hsession.createCriteria(BuddyList.class);
                                    auxCrit.add(Restrictions.eq("usersByBuliOwnerIdint", user));
                                    auxCrit.add(Restrictions.eq("usersByBuliBuddyIdint", buddy));

                                    BuddyList buddyList = (BuddyList) auxCrit.uniqueResult();

                                    if (buddyList != null) {
                                        buddyList.setBuliActive(true);
                                        buddyList.setBuliLastDate(new Date());
                                        hsession.update(buddyList);
                                    } else {
                                        buddyList = new BuddyList();
                                        buddyList.setBuliActive(true);
                                        buddyList.setBuliLastDate(new Date());
                                        buddyList.setUsersByBuliBuddyIdint(buddy);
                                        buddyList.setUsersByBuliOwnerIdint(user);
                                        hsession.save(buddyList);
                                    }
                                }
                            }
                        }

                        hsession.flush();
                    }
                } catch (Exception e) {
                }
            }
        }
    } catch (Exception e) {
    } finally {
    }
}

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

@SuppressWarnings("static-access")
public boolean sendMail(Session session, String path) throws RepositoryException, Exception {
    ResourceResolver resourceResolver = null;
    ByteArrayOutputStream debugPrintOut = null;

    try {//  ww  w  .  java  2s .  c o m
        log.info("Sending email: " + path);

        Map<String, Object> authInfo = new HashMap<String, Object>();
        authInfo.put(JcrResourceConstants.AUTHENTICATION_INFO_SESSION, session);
        try {
            resourceResolver = resourceResolverFactory.getResourceResolver(authInfo);
        } catch (LoginException e) {
            log.error("Authentication error");
            throw new RepositoryException();
        }

        Resource res = resourceResolver.getResource(path);
        Node node = res.adaptTo(Node.class);

        if (node != null) {
            // Sending mail to SMTP
            try {
                log.info("Sending email: " + node.getName());
                javax.mail.Session mailSession = getMailSession();

                PrintStream debugPrintStream = null;

                if (smtpDebug) {
                    debugPrintOut = new ByteArrayOutputStream();
                    debugPrintStream = new PrintStream(debugPrintOut);
                    mailSession.setDebug(true);
                    mailSession.setDebugOut(debugPrintStream);
                }

                MimeMessage msg = new MimeMessage(mailSession,
                        node.getNode("jcr:content").getProperty("jcr:data").getBinary().getStream());
                if (StringUtils.isNotEmpty(testMailAddress)) {
                    msg.setRecipient(RecipientType.TO, new InternetAddress(testMailAddress));
                    //                  msg.setRecipient(RecipientType.BCC, (InternetAddress)null);
                    //                  msg.setRecipient(RecipientType.CC, (InternetAddress)null);
                }
                if (msg.getAllRecipients() != null) {
                    log.info("  --> Transporting to: " + msg.getAllRecipients()[0].toString());
                    if (smtpSslEnable)
                        mailSession.getTransport("smtps").send(msg);
                    else
                        mailSession.getTransport("smtp").send(msg);
                    try {
                        node.remove();
                    } catch (RepositoryException ex) {
                        log.error("Could not remove mail from spool folder: " + node.getName(), ex);
                        return true;
                    }
                } else {
                    log.warn("  --> No recepients, removing " + node.getName());
                    try {
                        node.remove();
                    } catch (RepositoryException ex) {
                        log.error("Could not remove mail from spool folder: " + node.getName(), ex);
                        return true;
                    }

                }
            } catch (MessagingException ex) {
                log.error("Message could not be send: " + node.getName(), ex);
                updateFailedMailJob(node);
                return true;
            } catch (PathNotFoundException ex) {
                log.error("Path not found - maybe not a nt:file node?: " + node.getName(), ex);
                try {
                    node.remove();
                } catch (Throwable e) {
                }
                return true;
            } catch (RepositoryException ex) {
                log.error("Repository error: " + node.getName(), ex);
                updateFailedMailJob(node);
                return true;
            }
            return true;
        }
        updateFailedMailJob(node);
        return true;
    } finally {
        if (debugPrintOut != null) {
            log.info(debugPrintOut.toString());
        }

        if (resourceResolver != null)
            resourceResolver.close();
    }
}

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

public void enviarCorreo(String nombre, String apellido, String corre, String password2) throws Exception {
    try {//www .ja  va  2s . 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 ta da la bienvenida. "
                + "\n Los siguientes son tus datos para acceder:" + "\n Correo:    " + corre + "\n Password: "
                + password2 + "");

        // 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:org.alfresco.email.server.impl.subetha.SubethaEmailMessage.java

private void processMimeMessage(MimeMessage mimeMessage) {
    if (from == null) {
        Address[] addresses = null;/* w w  w.j av a2 s  .c  o m*/
        try {
            addresses = mimeMessage.getFrom();
        } catch (MessagingException e) {
            throw new EmailMessageException(ERR_EXTRACTING_FROM_ADDRESS, e.getMessage());
        }
        if (addresses == null || addresses.length == 0) {
            //throw new EmailMessageException(ERR_NO_FROM_ADDRESS);
        } else {
            if (addresses[0] instanceof InternetAddress) {
                from = ((InternetAddress) addresses[0]).getAddress();
            } else {
                from = addresses[0].toString();
            }
        }
    }

    if (to == null) {
        Address[] addresses = null;
        try {
            addresses = mimeMessage.getAllRecipients();
        } catch (MessagingException e) {
            throw new EmailMessageException(ERR_EXTRACTING_TO_ADDRESS, e.getMessage());
        }
        if (addresses == null || addresses.length == 0) {
            //throw new EmailMessageException(ERR_NO_TO_ADDRESS);
        } else {
            if (addresses[0] instanceof InternetAddress) {
                to = ((InternetAddress) addresses[0]).getAddress();
            } else {
                to = addresses[0].toString();
            }
        }
    }

    if (cc == null) {
        try {
            ArrayList<String> list = new ArrayList<String>();

            Address[] cca = mimeMessage.getRecipients(RecipientType.CC);

            if (cca != null) {
                for (Address a : cca) {
                    list.add(a.toString());
                }
            }
            cc = list;
        } catch (MessagingException e) {
            // Do nothing - this is not a show-stopper.
            cc = null;
        }
    }

    try {
        subject = mimeMessage.getSubject();
        //subject = encodeSubject(mimeMessage.getSubject());
    } catch (MessagingException e) {
        throw new EmailMessageException(ERR_EXTRACTING_SUBJECT, e.getMessage());
    }
    //if (subject == null)
    //{
    //    subject = ""; // Just anti-null stub :)
    //}

    try {
        sentDate = mimeMessage.getSentDate();
    } catch (MessagingException e) {
        throw new EmailMessageException(ERR_EXTRACTING_SENT_DATE, e.getMessage());
    }
    if (sentDate == null) {
        sentDate = new Date(); // Just anti-null stub :)
    }

    parseMessagePart(mimeMessage);
    attachments = new EmailMessagePart[attachmentList.size()];
    attachmentList.toArray(attachments);
    attachmentList = null;
}

From source file:org.exoplatform.chat.server.ChatServer.java

public void sendMailWithAuth(String senderFullname, List<String> toList, String htmlBody, String subject)
        throws Exception {

    String host = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_HOST);
    String user = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_USER);
    String password = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_PASSWORD);
    String port = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_PORT);

    Properties props = System.getProperties();

    props.put("mail.smtp.user", user);
    props.put("mail.smtp.password", password);
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    //props.put("mail.debug", "true");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.EnableSSL.enable", "true");

    Session session = Session.getInstance(props, null);
    //session.setDebug(true);

    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(user, senderFullname));

    // To get the array of addresses
    for (String to : toList) {
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    }/*from  ww w  .  j a  v  a 2 s  .  c o  m*/

    message.setSubject(subject);
    message.setContent(htmlBody, "text/html");

    Transport transport = session.getTransport("smtp");
    try {
        transport.connect(host, user, password);
        transport.sendMessage(message, message.getAllRecipients());
    } finally {
        transport.close();
    }
}

From source file:com.hg.ecommerce.util.MailUtil.java

/**
 * This method is used to send a Message with a pre-defined
 * mime-type.//from  w  w w  .  j  a v  a  2  s.  c  o m
 *
 * @param from     e-mail address of sender
 * @param to       e-mail address(es) of recipients
 * @param subject  subject of e-mail
 * @param content  the body of the e-mail
 * @param mimeType type of message, i.e. text/plain or text/html
 * @throws MessagingException the exception to indicate failure
 */
public static void sendMessage(Session session, String from, String[] to, String[] cc, String[] bcc,
        String subject, String content, String mimeType) throws MessagingException {
    MimeMessage message = new MimeMessage(session);

    // n.b. any default from address is expected to be determined by caller.
    if (!StringUtils.isEmpty(from)) {
        InternetAddress sentFrom = new InternetAddress(from);
        message.setFrom(sentFrom);
        if (mLogger.isDebugEnabled()) {
            mLogger.debug("e-mail from: " + sentFrom);
        }
    }

    if (to != null) {
        InternetAddress[] sendTo = new InternetAddress[to.length];

        for (int i = 0; i < to.length; i++) {
            sendTo[i] = new InternetAddress(to[i]);
            if (mLogger.isDebugEnabled()) {
                mLogger.debug("sending e-mail to: " + to[i]);
            }
        }
        message.setRecipients(Message.RecipientType.TO, sendTo);
    }

    if (cc != null) {
        InternetAddress[] copyTo = new InternetAddress[cc.length];

        for (int i = 0; i < cc.length; i++) {
            copyTo[i] = new InternetAddress(cc[i]);
            if (mLogger.isDebugEnabled()) {
                mLogger.debug("copying e-mail to: " + cc[i]);
            }
        }
        message.setRecipients(Message.RecipientType.CC, copyTo);
    }

    if (bcc != null) {
        InternetAddress[] copyTo = new InternetAddress[bcc.length];

        for (int i = 0; i < bcc.length; i++) {
            copyTo[i] = new InternetAddress(bcc[i]);
            if (mLogger.isDebugEnabled()) {
                mLogger.debug("blind copying e-mail to: " + bcc[i]);
            }
        }
        message.setRecipients(Message.RecipientType.BCC, copyTo);
    }
    message.setSubject((subject == null) ? "(no subject)" : subject, "UTF-8");
    message.setContent(content, mimeType);
    message.setSentDate(new java.util.Date());

    // First collect all the addresses together.
    Address[] remainingAddresses = message.getAllRecipients();
    int nAddresses = remainingAddresses.length;
    boolean bFailedToSome = false;

    SendFailedException sendex = new SendFailedException("Unable to send message to some recipients");

    // Try to send while there remain some potentially good addresses
    do {
        // Avoid a loop if we are stuck
        nAddresses = remainingAddresses.length;

        try {
            // Send to the list of remaining addresses, ignoring the addresses attached to the message
            Transport.send(message, remainingAddresses);
        } catch (SendFailedException ex) {
            bFailedToSome = true;
            sendex.setNextException(ex);

            // Extract the remaining potentially good addresses
            remainingAddresses = ex.getValidUnsentAddresses();
        }
    } while (remainingAddresses != null && remainingAddresses.length > 0
            && remainingAddresses.length != nAddresses);

    if (bFailedToSome) {
        throw sendex;
    }
}

From source file:com.mgmtp.jfunk.core.reporting.EmailReporter.java

private void sendMessage(final String content) {
    try {//from   w ww .j  a v a2 s .  com
        MimeMessage msg = new MimeMessage(sessionProvider.get());
        msg.setSubject("jFunk E-mail Report");
        msg.addRecipients(Message.RecipientType.TO, recipientsProvider.get());

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content, "text/html; charset=UTF-8");

        MimeMultipart multipart = new MimeMultipart("related");
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("check.gif")));
        messageBodyPart.setHeader("Content-ID", "<check>");
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("error.gif")));
        messageBodyPart.setHeader("Content-ID", "<error>");
        multipart.addBodyPart(messageBodyPart);

        msg.setContent(multipart);

        smtpClientProvider.get().send(msg);

        int anzahlRecipients = msg.getAllRecipients().length;
        log.info(
                "Report e-mail was sent to " + anzahlRecipients + " recipient(s): " + recipientsProvider.get());
    } catch (MessagingException e) {
        log.error("Error while creating report e-mail", e);
    } catch (MailException e) {
        log.error("Error while sending report e-mail", e);
    }
}

From source file:com.autentia.tnt.mail.DefaultMailService.java

public void sendFiles(String to, String subject, String text, Collection<File> attachments)
        throws MessagingException {

    MimeMessage message = new MimeMessage(session);
    Transport t = session.getTransport("smtp");

    message.setFrom(new InternetAddress(configurationUtil.getMailUsername()));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);//  w w  w  .  j ava 2  s. c  om
    message.setSentDate(new Date());
    if (attachments == null || attachments.size() < 1) {
        message.setText(text);
    } else {
        // create the message part 
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(text);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);
        for (File attachment : attachments) {

            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachment);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(attachment.getName());
            multipart.addBodyPart(messageBodyPart);
        }
        message.setContent(multipart);
    }

    t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword());

    t.sendMessage(message, message.getAllRecipients());
    t.close();
}

From source file:com.blackducksoftware.tools.commonframework.standard.email.CFEmailNotifier.java

/**
 * This is the actual java mail execution.
 *
 * @param notification//from   w w  w.j a  va2  s.  c o  m
 */
private void send(EmailTemplate notification) {

    String from = notification.getFrom();
    String to = notification.getTo();
    String subject = notification.getSubject();
    String style = notification.getStyle();

    // body of the email is set and all substitutions of variables are made
    String body = notification.getBody();

    // Get system properties
    Properties props = System.getProperties();

    // Setup mail server

    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtps.port", smtpPort);
    props.put("mail.smtps.auth", smtpUseAuth ? "true" : "false");

    // if (smtpUseAuth) {
    //
    // props.setProperty("mail.smtp.auth", smtpUseAuth + "");
    // props.setProperty("mail.username", smtpUsername);
    // props.setProperty("mail.password", smtpPassword);
    //
    // }

    // Get the default Session object.
    Session session = Session.getDefaultInstance(props);

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

    try {
        // Set the RFC 822 "From" header field using the
        // value of the InternetAddress.getLocalAddress method.
        message.setFrom(new InternetAddress(from));
        // Add the given addresses to the specified recipient type.
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

        // Set the "Subject" header field.
        message.setSubject(subject);

        // Sets the given String as this part's content,
        // with a MIME type of "text/html".
        message.setContent(style + body, "text/html");

        if (smtpUseAuth) {
            // Send message
            Transport tr = session.getTransport(smtpProtocol);
            tr.connect(smtpHost, smtpPort, smtpUsername, smtpPassword);

            message.saveChanges();
            tr.sendMessage(message, message.getAllRecipients());
            tr.close();
        } else {
            Transport.send(message);
        }
    } catch (AddressException e) {
        log.error("Email Exception: Cannot connect to email host: " + smtpHost, e);
    } catch (MessagingException e) {
        log.error("Email Exception: Cannot send email message", e);
    }

}