Example usage for javax.mail Address toString

List of usage examples for javax.mail Address toString

Introduction

In this page you can find the example usage for javax.mail Address toString.

Prototype

@Override
public abstract String toString();

Source Link

Document

Return a String representation of this address object.

Usage

From source file:info.debatty.java.datasets.enron.Email.java

private static List<String> addressToString(List<Address> addresses) {
    ArrayList<String> strings = new ArrayList<String>();
    for (Address address : addresses) {
        strings.add(address.toString());
    }/*  ww w.  j  av a 2s.com*/
    return strings;
}

From source file:com.canoo.webtest.plugins.emailtest.AbstractSelectStep.java

static boolean doMatchMultiple(final String expected, final Address[] actuals) {
    // semantics are: if no expectation then match
    if (StringUtils.isEmpty(expected)) {
        return true;
    } else if (actuals == null) {
        return false;
    }//from   ww  w .  j a v a  2  s  . com

    final StringTokenizer expectedTokens = new StringTokenizer(expected, ",");
    while (expectedTokens.hasMoreTokens()) {
        final String expectedToken = expectedTokens.nextToken().trim();
        boolean hasMatched = false;
        for (int i = 0; i < actuals.length; i++) {
            final Address actual = actuals[i];
            hasMatched = doMatch(expectedToken, actual.toString());
            if (hasMatched) {
                break;
            }
        }
        if (!hasMatched) {
            return false;
        }
    }
    return true;
}

From source file:com.mgmtp.jfunk.core.mail.MessagePredicates.java

/**
 * Creates a {@link Predicate} for matching a mail recipient. This Predicate returns true if at least
 * one recipient matches the given value.
 * // www. j av  a2 s .  c  om
 * @param recipient
 *            the recipient to match
 * @return the predicate
 */
public static Predicate<Message> forRecipient(final String recipient) {
    return new Predicate<Message>() {
        @Override
        public boolean apply(final Message input) {
            Address[] addresses;
            try {
                addresses = input.getAllRecipients();
                if (addresses == null) {
                    return false;
                }
                for (Address address : addresses) {
                    if (StringUtils.equalsIgnoreCase(address.toString(), recipient)) {
                        return true;
                    }
                }
            } catch (MessagingException e) {
                throw new MailException("Error while reading recipients", e);
            }
            return false;
        }

        @Override
        public String toString() {
            return String.format("recipient to include %s", recipient);
        }
    };
}

From source file:org.nuxeo.ecm.core.convert.plugins.text.extractors.RFC822ToTextConverter.java

protected static void writeInfo(OutputStream stream, Address address) {
    if (address != null) {
        try {// ww w .  j  a  va  2  s. c  om
            stream.write(address.toString().getBytes());
            stream.write(" ".getBytes());
        } catch (Exception e) {
            log.error(e);
        }
    }
}

From source file:com.liferay.petra.mail.InternetAddressUtil.java

public static void validateAddress(Address address) throws AddressException {

    if (address == null) {
        throw new AddressException("Email address is null");
    }/*from www.ja v  a2s  . c o  m*/

    String addressString = address.toString();

    for (char c : addressString.toCharArray()) {
        if ((c == CharPool.NEW_LINE) || (c == CharPool.RETURN)) {
            StringBundler sb = new StringBundler(3);

            sb.append("Email address ");
            sb.append(addressString);
            sb.append(" is invalid because it contains line breaks");

            throw new AddressException(sb.toString());
        }
    }
}

From source file:com.email.ReceiveEmail.java

/**
 * Saved the list of all of the TO, FROM, CC, BCC, and dates
 *
 * @param m Message//from  www. j a v  a  2s . co  m
 * @param p Part
 * @param eml EmailMessageModel
 * @return EmailMessageModel
 */
private static EmailMessageModel saveEnvelope(Message m, Part p, EmailMessageModel eml) {
    String to = "";
    String cc = "";
    String bcc = "";

    try {
        Address[] address;

        //From
        if ((address = m.getFrom()) != null) {
            for (Address addy : address) {
                eml.setEmailFrom(addy.toString());
            }
        }

        //to
        if ((address = m.getRecipients(Message.RecipientType.TO)) != null) {
            for (int j = 0; j < address.length; j++) {
                if (j == 0) {
                    to = address[j].toString();
                } else {
                    to += "; " + address[j].toString();
                }
            }
        }
        eml.setEmailTo(removeEmojiAndSymbolFromString(to));

        //CC
        if ((address = m.getRecipients(Message.RecipientType.CC)) != null) {

            for (int j = 0; j < address.length; j++) {
                if (j == 0) {
                    cc = address[j].toString();
                } else {
                    cc += "; " + address[j].toString();
                }
            }
        }
        eml.setEmailCC(removeEmojiAndSymbolFromString(cc));

        //BCC
        if ((address = m.getRecipients(Message.RecipientType.BCC)) != null) {
            for (int j = 0; j < address.length; j++) {
                if (j == 0) {
                    bcc = address[j].toString();
                } else {
                    bcc += "; " + address[j].toString();
                }
            }
        }
        eml.setEmailBCC(removeEmojiAndSymbolFromString(bcc));

        //subject
        if (m.getSubject() == null) {
            eml.setEmailSubject("");
        } else {
            eml.setEmailSubject(removeEmojiAndSymbolFromString(m.getSubject().replace("'", "\"")));
        }

        //date
        eml.setSentDate(new java.sql.Timestamp(m.getSentDate().getTime()));
        eml.setReceivedDate(new java.sql.Timestamp(m.getReceivedDate().getTime()));

        //Get email body
        String emailBody = getEmailBodyText(p);

        // clean email Body
        emailBody = StringUtilities.replaceOfficeTags(emailBody);

        if (StringUtilities.isHtml(emailBody)) {
            Source htmlSource = new Source(emailBody);
            Segment htmlSeg = new Segment(htmlSource, 0, htmlSource.length());
            Renderer htmlRend = new Renderer(htmlSeg);
            emailBody = htmlRend.toString();
        }

        eml.setEmailBody(removeEmojiAndSymbolFromString(emailBody));

    } catch (MessagingException ex) {
        ExceptionHandler.Handle(ex);
    }
    return eml;
}

From source file:mitm.common.mail.EmailAddressUtils.java

/**
 * Returns the Address's as List of strings. If decode is true, the address will be mime decoded. 
 * Returns null if addresses is null. Decode is used to decode the user part (if encoded) of an 
 * email address because this is not decoded by default.
 * /*  w  w  w. j av  a  2s .c om*/
 * WARNING: The returned string includes the user part!
 */
public static ArrayList<String> addressesToStrings(Collection<? extends Address> addresses, boolean decode) {
    if (addresses == null) {
        return null;
    }

    ArrayList<String> result = new ArrayList<String>(addresses.size());

    for (Address address : addresses) {
        if (address != null) {
            result.add(decode ? HeaderUtils.decodeTextQuietly(address.toString()) : address.toString());
        }
    }

    return result;
}

From source file:com.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param dataSource - The email message
 * @param authRequired - <code>true</code> if authentication is required, <code>false</code> otherwise
 * @param authList - If authRequired is true, this must be populated with the auth info
 * @return List - The list of email messages in the mailstore
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs during processing
 *///  www  .j  a  v  a2 s.c om
public static final synchronized List<EmailMessage> readEmailMessages(final Properties dataSource,
        final boolean authRequired, final List<String> authList) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#readEmailMessages(final Properties dataSource, final boolean authRequired, final List<String> authList) throws MessagingException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("dataSource: {}", dataSource);
        DEBUGGER.debug("authRequired: {}", authRequired);
        DEBUGGER.debug("authList: {}", authList);
    }

    Folder mailFolder = null;
    Session mailSession = null;
    Folder archiveFolder = null;
    List<EmailMessage> emailMessages = null;

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR, -24);

    final Long TIME_PERIOD = cal.getTimeInMillis();
    final URLName URL_NAME = (authRequired)
            ? new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, authList.get(0), authList.get(1))
            : new URLName(dataSource.getProperty("mailtype"), dataSource.getProperty("host"),
                    Integer.parseInt(dataSource.getProperty("port")), null, null, null);

    if (DEBUG) {
        DEBUGGER.debug("timePeriod: {}", TIME_PERIOD);
        DEBUGGER.debug("URL_NAME: {}", URL_NAME);
    }

    try {
        // Set up mail session
        mailSession = (authRequired) ? Session.getDefaultInstance(dataSource, new SMTPAuthenticator())
                : Session.getDefaultInstance(dataSource);

        if (DEBUG) {
            DEBUGGER.debug("mailSession: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        Store mailStore = mailSession.getStore(URL_NAME);
        mailStore.connect();

        if (DEBUG) {
            DEBUGGER.debug("mailStore: {}", mailStore);
        }

        if (!(mailStore.isConnected())) {
            throw new MessagingException("Failed to connect to mail service. Cannot continue.");
        }

        mailFolder = mailStore.getFolder("inbox");
        archiveFolder = mailStore.getFolder("archive");

        if (!(mailFolder.exists())) {
            throw new MessagingException("Requested folder does not exist. Cannot continue.");
        }

        mailFolder.open(Folder.READ_WRITE);

        if ((!(mailFolder.isOpen())) || (!(mailFolder.hasNewMessages()))) {
            throw new MessagingException("Failed to open requested folder. Cannot continue");
        }

        if (!(archiveFolder.exists())) {
            archiveFolder.create(Folder.HOLDS_MESSAGES);
        }

        Message[] mailMessages = mailFolder.getMessages();

        if (mailMessages.length == 0) {
            throw new MessagingException("No messages were found in the provided store.");
        }

        emailMessages = new ArrayList<EmailMessage>();

        for (Message message : mailMessages) {
            if (DEBUG) {
                DEBUGGER.debug("MailMessage: {}", message);
            }

            // validate the message here
            String messageId = message.getHeader("Message-ID")[0];
            Long messageDate = message.getReceivedDate().getTime();

            if (DEBUG) {
                DEBUGGER.debug("messageId: {}", messageId);
                DEBUGGER.debug("messageDate: {}", messageDate);
            }

            // only get emails for the last 24 hours
            // this should prevent us from pulling too
            // many emails
            if (messageDate >= TIME_PERIOD) {
                // process it
                Multipart attachment = (Multipart) message.getContent();
                Map<String, InputStream> attachmentList = new HashMap<String, InputStream>();

                for (int x = 0; x < attachment.getCount(); x++) {
                    BodyPart bodyPart = attachment.getBodyPart(x);

                    if (!(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))) {
                        continue;
                    }

                    attachmentList.put(bodyPart.getFileName(), bodyPart.getInputStream());
                }

                List<String> toList = new ArrayList<String>();
                List<String> ccList = new ArrayList<String>();
                List<String> bccList = new ArrayList<String>();
                List<String> fromList = new ArrayList<String>();

                for (Address from : message.getFrom()) {
                    fromList.add(from.toString());
                }

                if ((message.getRecipients(RecipientType.TO) != null)
                        && (message.getRecipients(RecipientType.TO).length != 0)) {
                    for (Address to : message.getRecipients(RecipientType.TO)) {
                        toList.add(to.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.CC) != null)
                        && (message.getRecipients(RecipientType.CC).length != 0)) {
                    for (Address cc : message.getRecipients(RecipientType.CC)) {
                        ccList.add(cc.toString());
                    }
                }

                if ((message.getRecipients(RecipientType.BCC) != null)
                        && (message.getRecipients(RecipientType.BCC).length != 0)) {
                    for (Address bcc : message.getRecipients(RecipientType.BCC)) {
                        bccList.add(bcc.toString());
                    }
                }

                EmailMessage emailMessage = new EmailMessage();
                emailMessage.setMessageTo(toList);
                emailMessage.setMessageCC(ccList);
                emailMessage.setMessageBCC(bccList);
                emailMessage.setEmailAddr(fromList);
                emailMessage.setMessageAttachments(attachmentList);
                emailMessage.setMessageDate(message.getSentDate());
                emailMessage.setMessageSubject(message.getSubject());
                emailMessage.setMessageBody(message.getContent().toString());
                emailMessage.setMessageSources(message.getHeader("Received"));

                if (DEBUG) {
                    DEBUGGER.debug("emailMessage: {}", emailMessage);
                }

                emailMessages.add(emailMessage);

                if (DEBUG) {
                    DEBUGGER.debug("emailMessages: {}", emailMessages);
                }
            }

            // archive it
            archiveFolder.open(Folder.READ_WRITE);

            if (archiveFolder.isOpen()) {
                mailFolder.copyMessages(new Message[] { message }, archiveFolder);
                message.setFlag(Flags.Flag.DELETED, true);
            }
        }
    } catch (IOException iox) {
        throw new MessagingException(iox.getMessage(), iox);
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } finally {
        try {
            if ((mailFolder != null) && (mailFolder.isOpen())) {
                mailFolder.close(true);
            }

            if ((archiveFolder != null) && (archiveFolder.isOpen())) {
                archiveFolder.close(false);
            }
        } catch (MessagingException mx) {
            ERROR_RECORDER.error(mx.getMessage(), mx);
        }
    }

    return emailMessages;
}

From source file:mitm.common.mail.EmailAddressUtils.java

/**
 * Returns the email part if address is an InternetAddress, if not toString() is called in the Address.
 *//*w ww.ja  v a2  s .com*/
public static String getEmailAddress(Address address) {
    String email;

    if (address == null) {
        return null;
    }

    if (address instanceof InternetAddress) {
        email = ((InternetAddress) address).getAddress();
    } else {
        email = address.toString();
    }

    return email;
}

From source file:fr.gouv.culture.vitam.eml.EmlExtract.java

private static String addAddress(Element root, String entry, Address address, String except) {
    String value = address.toString();
    String ad = StringUtils.selectChevron(value);
    if (ad == null || (except != null && ad.equalsIgnoreCase(except))) {
        return null;
    }/*w  ww.j a v  a  2 s .  c  om*/
    String nams = value.replace('<' + ad + '>', "");
    Element val = XmlDom.factory.createElement(entry);
    Element name = XmlDom.factory.createElement(EMAIL_FIELDS.emailName.name);
    Element addresse = XmlDom.factory.createElement(EMAIL_FIELDS.emailAddress.name);
    name.setText(StringUtils.unescapeHTML(nams, true, false));
    addresse.setText(StringUtils.unescapeHTML(ad, true, false));
    val.add(name);
    val.add(addresse);
    root.add(val);
    return value;
}