Example usage for javax.mail.internet InternetAddress getAddress

List of usage examples for javax.mail.internet InternetAddress getAddress

Introduction

In this page you can find the example usage for javax.mail.internet InternetAddress getAddress.

Prototype

public String getAddress() 

Source Link

Document

Get the email address.

Usage

From source file:org.jasig.ssp.service.impl.MessageServiceImpl.java

private InternetAddress[] getEmailAddresses(Person person, String type, UUID messageId) {
    List<InternetAddress> validAddresses = new ArrayList<InternetAddress>();

    if (person.hasEmailAddresses()) {
        InternetAddress[] addresses = getEmailAddresses(person.getEmailAddresses(), "to:", messageId);
        for (InternetAddress address : addresses) {
            try {
                validAddresses.add(new InternetAddress(address.getAddress(), person.getFullName()));
            } catch (UnsupportedEncodingException e) {
                LOGGER.warn("Invalid email address found: " + address.toString() + " for " + type
                        + "of message " + messageId, e);
            }/*  w w w  .  j a  v a2 s . co m*/
        }
    }

    return validAddresses.toArray(new InternetAddress[validAddresses.size()]);
}

From source file:mitm.application.djigzo.james.mailets.Notify.java

private void handleUserProperty(Mail mail, String userProperty, Collection<MailAddress> result)
        throws MessagingException, AddressException {
    InternetAddress originator = getMessageOriginatorIdentifier().getOriginator(mail);

    if (originator != null) {
        try {//  ww  w  .  ja  v  a  2  s. c  o  m
            User user = getUserWorkflow().getUser(originator.getAddress(),
                    UserWorkflow.GetUserMode.CREATE_IF_NOT_EXIST);

            String userValue = user.getUserPreferences().getProperties().getProperty(userProperty, false);

            addEmails(userValue, result);
        } catch (HierarchicalPropertiesException e) {
            getLogger().error("Error getting user property " + userProperty, e);
        }
    }
}

From source file:com.silverpeas.importExport.control.RepositoriesTypeManager.java

private void processMailContent(PublicationDetail pubDetail, File file, ImportReportManager reportManager,
        UnitReport unitReport, GEDImportExport gedIE, boolean isVersioningUsed) throws ImportExportException {

    String componentId = gedIE.getCurrentComponentId();
    UserDetail userDetail = gedIE.getCurentUserDetail();
    MailExtractor extractor = null;//from w ww.  j a v a 2 s.c o m
    Mail mail = null;
    try {
        extractor = Extractor.getExtractor(file);
        mail = extractor.getMail();
    } catch (Exception e) {
        SilverTrace.error("importExport", "RepositoriesTypeManager.processMailContent",
                "importExport.EX_CANT_EXTRACT_MAIL_DATA", e);
    }
    if (mail != null) {
        // save mail data into dedicated form
        String content = mail.getBody();
        PublicationContentType pubContent = new PublicationContentType();
        XMLModelContentType modelContent = new XMLModelContentType("mail");
        pubContent.setXMLModelContentType(modelContent);
        List<XMLField> fields = new ArrayList<XMLField>();
        modelContent.setFields(fields);

        XMLField subject = new XMLField("subject", mail.getSubject());
        fields.add(subject);

        XMLField body = new XMLField("body", ESCAPE_ISO8859_1.translate(content));
        fields.add(body);

        XMLField date = new XMLField("date", DateUtil.getOutputDateAndHour(mail.getDate(), "fr"));
        fields.add(date);

        InternetAddress address = mail.getFrom();
        String from = "";
        if (StringUtil.isDefined(address.getPersonal())) {
            from += address.getPersonal() + " - ";
        }
        from += "<a href=\"mailto:" + address.getAddress() + "\">" + address.getAddress() + "</a>";
        XMLField fieldFROM = new XMLField("from", from);
        fields.add(fieldFROM);

        Address[] recipients = mail.getAllRecipients();
        String to = "";
        for (Address recipient : recipients) {
            InternetAddress ia = (InternetAddress) recipient;
            if (StringUtil.isDefined(ia.getPersonal())) {
                to += ia.getPersonal() + " - ";
            }
            to += "<a href=\"mailto:" + ia.getAddress() + "\">" + ia.getAddress() + "</a></br>";
        }
        XMLField fieldTO = new XMLField("to", to);
        fields.add(fieldTO);

        // save form
        gedIE.createPublicationContent(reportManager, unitReport, Integer.parseInt(pubDetail.getPK().getId()),
                pubContent, userDetail.getId(), null);

        // extract each file from mail...
        try {
            List<AttachmentDetail> documents = new ArrayList<AttachmentDetail>();

            List<MailAttachment> attachments = extractor.getAttachments();
            for (MailAttachment attachment : attachments) {
                if (attachment != null) {
                    AttachmentDetail attDetail = new AttachmentDetail();
                    AttachmentPK pk = new AttachmentPK("unknown", "useless", componentId);
                    attDetail.setLogicalName(attachment.getName());
                    attDetail.setPhysicalName(attachment.getPath());
                    attDetail.setAuthor(userDetail.getId());
                    attDetail.setSize(attachment.getSize());
                    attDetail.setPK(pk);

                    documents.add(attDetail);
                }
            }

            // ... and save it
            if (isVersioningUsed) {
                // versioning mode
                VersioningImportExport versioningIE = new VersioningImportExport(userDetail);
                versioningIE.importDocuments(pubDetail.getPK().getId(), componentId, documents,
                        Integer.parseInt(userDetail.getId()), pubDetail.isIndexable());
            } else {
                // classic mode
                AttachmentImportExport attachmentIE = new AttachmentImportExport(gedIE.getCurentUserDetail());
                attachmentIE.importAttachments(pubDetail.getPK().getId(), componentId, documents,
                        userDetail.getId(), pubDetail.isIndexable());
            }
        } catch (Exception e) {
            SilverTrace.error("importExport", "RepositoriesTypeManager.processMailContent",
                    "root.EX_NO_MESSAGE", e);
        }
    }
}

From source file:com.alkacon.opencms.newsletter.CmsNewsletterMail.java

/**
 * Sends the newsletter mails to the recipients.<p>
 *///from   w w w.  j av a  2  s. c  o  m
public void sendMail() {

    Iterator<InternetAddress> i = getRecipients().iterator();
    while (i.hasNext()) {
        InternetAddress to = i.next();
        List<InternetAddress> toList = new ArrayList<InternetAddress>(1);
        toList.add(to);
        try {
            Email mail = getMailData().getEmail();
            mail.setTo(toList);
            mail.send();
        } catch (Exception e) {
            // log failed mail send process
            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_ERROR_NEWSLETTER_EMAIL_SEND_FAILED_2,
                        to.getAddress(), getNewsletterName()));
            }
            // store message for error report mail
            getMailErrors()
                    .add(Messages.get().getBundle().key(Messages.MAIL_ERROR_EMAIL_ADDRESS_1, to.getAddress()));
        }
    }
}

From source file:mitm.application.djigzo.james.mailets.MailAttributes.java

private LinkedList<String> parseAttribute(String attribute, Mail mail) throws MessagingException {
    attribute = StringUtils.trimToNull(attribute);

    LinkedList<String> result = new LinkedList<String>();

    if (attribute != null) {
        /*/* w  w  w . j a v a 2  s  .  c o m*/
         * Check if the input is a special address
         */
        SpecialAddress specialAddress = SpecialAddress.fromName(attribute);

        if (specialAddress != null) {
            switch (specialAddress) {
            case ORIGINATOR:
                copyMailAddresses(messageOriginatorIdentifier.getOriginator(mail), result);
                break;
            case REPLY_TO:
                copyMailAddresses(mail.getMessage().getReplyTo(), result);
                break;
            case SENDER:
                copyMailAddresses(MailAddressUtils.toInternetAddress(mail.getSender()), result);
                break;
            case FROM:
                copyMailAddresses(mail.getMessage().getFrom(), result);
                break;

            default:
                throw new MessagingException("Unsupported SpecialAddress.");
            }
        } else {
            /*
             * Check if the input is a user property
             */
            Matcher matcher = USER_VAR_PATTERN.matcher(attribute);

            if (matcher.matches()) {
                InternetAddress originator = messageOriginatorIdentifier.getOriginator(mail);

                if (originator != null) {
                    String userProperty = matcher.group(1);

                    try {
                        User user = userWorkflow.getUser(originator.getAddress(),
                                UserWorkflow.GetUserMode.CREATE_IF_NOT_EXIST);

                        String value = user.getUserPreferences().getProperties().getProperty(userProperty,
                                false);

                        value = StringUtils.trimToNull(value);

                        if (value != null) {
                            result.add(value);
                        }
                    } catch (HierarchicalPropertiesException e) {
                        getLogger().error("Error getting user property " + userProperty, e);
                    }
                }
            } else {
                result.add(attribute);
            }
        }
    }

    return result;
}

From source file:edu.stanford.muse.webapp.JSPHelper.java

public static JSONArray formatAddressesAsJSON(Address addrs[]) throws JSONException {
    JSONArray result = new JSONArray();
    if (addrs == null)
        return result;
    int index = 0;
    for (int i = 0; i < addrs.length; i++) {
        Address a = addrs[i];// ww w.j  a  v  a2 s  . c  o m
        if (a instanceof InternetAddress) {
            InternetAddress ia = (InternetAddress) a;
            JSONObject o = new JSONObject();
            o.put("email", Util.maskEmailDomain(ia.getAddress()));
            o.put("name", ia.getPersonal());
            result.put(index++, o);
        }
    }
    return result;
}

From source file:org.jasig.ssp.service.impl.MessageServiceImpl.java

private InternetAddress[] getEmailAddresses(String emailAddress, String type, UUID messageId) {
    if (StringUtils.isBlank(emailAddress)) {
        return new InternetAddress[0];
    }//w  w w  .  ja v a2s .c o  m
    List<InternetAddress> emailAddresses = new ArrayList<InternetAddress>();
    if (emailAddress.indexOf(",") != -1) {
        StringTokenizer tokenizer = new StringTokenizer(emailAddress, ",");
        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken();
            if (StringUtils.isBlank(token))
                continue;
            InternetAddress address = getInternetAddress(token, type, messageId);
            if (address != null) {
                if (validateEmail(address.getAddress()))
                    emailAddresses.add(address);
                else
                    LOGGER.warn("Invalid email address found: " + token + " for " + type + "of message "
                            + messageId);
            }
        }
    } else {
        InternetAddress address = getInternetAddress(emailAddress, type, messageId);
        if (address != null) {
            if (validateEmail(address.getAddress()))
                emailAddresses.add(address);
            else
                LOGGER.warn("Invalid email address found: " + emailAddress + " for " + type + "of message "
                        + messageId);
        }
    }

    return emailAddresses.toArray(new InternetAddress[emailAddresses.size()]);
}

From source file:com.alkacon.opencms.v8.newsletter.CmsNewsletterMail.java

/**
 * Sends the newsletter mails to the recipients.<p>
 *///from  www  . ja  v a 2  s  . c o  m
public void sendMail() {

    Iterator<InternetAddress> i = getRecipients().iterator();
    int errLogCount = 0;
    while (i.hasNext()) {
        InternetAddress to = i.next();
        List<InternetAddress> toList = new ArrayList<InternetAddress>(1);
        toList.add(to);
        try {
            Email mail = getMailData().getEmail();
            mail.setTo(toList);
            mail.send();
        } catch (Exception e) {
            // log failed mail send process
            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_ERROR_NEWSLETTER_EMAIL_SEND_FAILED_2,
                        to.getAddress(), getNewsletterName()));
            }
            if (LOG.isDebugEnabled() && (errLogCount < 10)) {
                LOG.debug(e);
                errLogCount++;
            }
            // store message for error report mail
            String errMsg = Messages.get().getBundle().key(Messages.MAIL_ERROR_EMAIL_ADDRESS_1,
                    to.getAddress());
            if (errLogCount == 10) {
                errMsg += "\nStack:\n" + errMsg + "\n";
            }
            getMailErrors().add(errMsg);
        }
    }
}

From source file:nc.noumea.mairie.appock.services.impl.MailServiceImpl.java

@Override
public Message sendMail(AppockMail appockMail) throws MessagingException {

    if (CollectionUtils.isEmpty(appockMail.getListeDestinataire())) {
        log.warn("Mail non envoy, liste des destinataires vide : " + appockMail);
        return null;
    }//from  w w w  . j  a v a2s  .  co  m

    MimeMessage msg = new MimeMessage(mailServer);
    msg.setFrom(appockMail.getFrom() != null ? appockMail.getFrom() : defaultFrom());

    String prefixeSujet = isModeProduction() ? "" : "[TEST APPOCK] ";
    msg.setSubject(prefixeSujet + appockMail.getSujet(), configService.getEncodageSujetEmail());

    StringBuilder infoAdditionnelle = new StringBuilder();

    for (InternetAddress adresse : appockMail.getListeDestinataire()) {
        if (isModeProduction()) {
            // on est en production, envoi rel de mail au destinataire
            msg.addRecipient(Message.RecipientType.TO, adresse);
        } else {
            // en test, on envoie le mail  la personne connecte
            InternetAddress adresseTesteur = getAdresseMailDestinataireTesteur();
            if (adresseTesteur != null) {
                msg.addRecipient(Message.RecipientType.TO, adresseTesteur);
            }
            List<String> listeAdresseMail = new ArrayList<>();
            for (InternetAddress internetAddress : appockMail.getListeDestinataire()) {
                listeAdresseMail.add(internetAddress.getAddress());
            }
            infoAdditionnelle.append("En production cet email serait envoy vers ")
                    .append(StringUtils.join(listeAdresseMail, ", ")).append("<br/><hr/>");
            break;
        }
    }

    String contenuFinal = "";
    if (!StringUtils.isBlank(infoAdditionnelle.toString())) {
        contenuFinal += "<font face=\"arial\" >" + infoAdditionnelle.toString() + "</font>";
    }

    contenuFinal += "<font face=\"arial\" >" + appockMail.getContenu() + "<br/><br/></font>"
            + configService.getPiedDeMail();

    gereBonLivraisonDansMail(appockMail, msg, contenuFinal);

    if (!ArrayUtils.isEmpty(msg.getAllRecipients())) {
        Transport.send(msg);
    }

    return msg;
}

From source file:mitm.application.djigzo.james.mailets.Relay.java

private void handleMessageAction(Session session, Mail sourceMail, MimeMessage relayMessage)
        throws DatabaseException {
    final MutableObject userInfoContainer = new MutableObject();

    RelayUserInfoProvider infoProvider = new RelayUserInfoProvider() {
        @Override//  ww  w.j  a  v  a2s  . c o  m
        public RelayUserInfo getRelayUserInfo(MimeMessage message) throws MessagingException, RelayException {
            RelayUserInfo userInfo = null;

            InternetAddress originator = messageOriginatorIdentifier.getOriginator(message);

            if (originator != null) {
                String userEmail = originator.getAddress();

                logger.debug("Getting relay info for " + userEmail);

                userEmail = EmailAddressUtils.canonicalizeAndValidate(userEmail, false);

                try {
                    User user = userWorkflow.getUser(userEmail, UserWorkflow.GetUserMode.CREATE_IF_NOT_EXIST);

                    userInfo = createRelayUserInfo(user);

                    /*
                     * Save the userInfo because we need it later on
                     */
                    userInfoContainer.setValue(userInfo);
                } catch (HierarchicalPropertiesException e) {
                    throw new RelayException(e);
                }
            }

            return userInfo;
        }
    };

    RelayHandler handler = new RelayHandler(pKISecurityServices, infoProvider);

    if (preventReplay) {
        handler.setAdditionalRelayValidator(relayValidator);
    }

    try {
        MimeMessage messageToRelay = handler.handleRelayMessage(relayMessage);

        if (messageToRelay != null) {
            sendRelayMessage(sourceMail, messageToRelay, handler.getRecipients());

            /*
             * ghost the source mail if not passThrough
             */
            if (!passThrough) {
                sourceMail.setState(Mail.GHOST);
            }
        }
    } catch (RelayException e) {
        handleBlackBerryRelayException(e, (RelayUserInfo) userInfoContainer.getValue(), sourceMail);
    } catch (MessagingException e) {
        throw new DatabaseException(e);
    } catch (IOException e) {
        throw new DatabaseException(e);
    }
}