Example usage for javax.mail Message getFrom

List of usage examples for javax.mail Message getFrom

Introduction

In this page you can find the example usage for javax.mail Message getFrom.

Prototype

public abstract Address[] getFrom() throws MessagingException;

Source Link

Document

Returns the "From" attribute.

Usage

From source file:MainClass.java

public static void dumpEnvelope(Message m) throws Exception {
    pr("This is the message envelope");
    pr("---------------------------");
    Address[] a;/*from   w ww .ja v  a 2  s . com*/
    // FROM
    if ((a = m.getFrom()) != null) {
        for (int j = 0; j < a.length; j++)
            pr("FROM: " + a[j].toString());
    }

    // TO
    if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
        for (int j = 0; j < a.length; j++) {
            pr("TO: " + a[j].toString());
            InternetAddress ia = (InternetAddress) a[j];
            if (ia.isGroup()) {
                InternetAddress[] aa = ia.getGroup(false);
                for (int k = 0; k < aa.length; k++)
                    pr("  GROUP: " + aa[k].toString());
            }
        }
    }

    // SUBJECT
    pr("SUBJECT: " + m.getSubject());

    // DATE
    Date d = m.getSentDate();
    pr("SendDate: " + (d != null ? d.toString() : "UNKNOWN"));

    // FLAGS
    Flags flags = m.getFlags();
    StringBuffer sb = new StringBuffer();
    Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags

    boolean first = true;
    for (int i = 0; i < sf.length; i++) {
        String s;
        Flags.Flag f = sf[i];
        if (f == Flags.Flag.ANSWERED)
            s = "\\Answered";
        else if (f == Flags.Flag.DELETED)
            s = "\\Deleted";
        else if (f == Flags.Flag.DRAFT)
            s = "\\Draft";
        else if (f == Flags.Flag.FLAGGED)
            s = "\\Flagged";
        else if (f == Flags.Flag.RECENT)
            s = "\\Recent";
        else if (f == Flags.Flag.SEEN)
            s = "\\Seen";
        else
            continue; // skip it
        if (first)
            first = false;
        else
            sb.append(' ');
        sb.append(s);
    }

    String[] uf = flags.getUserFlags(); // get the user flag strings
    for (int i = 0; i < uf.length; i++) {
        if (first)
            first = false;
        else
            sb.append(' ');
        sb.append(uf[i]);
    }
    pr("FLAGS: " + sb.toString());

    // X-MAILER
    String[] hdrs = m.getHeader("X-Mailer");
    if (hdrs != null)
        pr("X-Mailer: " + hdrs[0]);
    else
        pr("X-Mailer NOT available");
}

From source file:com.email.ReceiveEmail.java

/**
 * Saved the list of all of the TO, FROM, CC, BCC, and dates
 *
 * @param m Message/*from  w w w  .  j  a va 2s  .  c o  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:com.aurel.track.util.emailHandling.MailReader.java

/**
 * Retrieves the senders e-mail address from this message.
 *
 * @param message//from w w w .  j  av a  2 s. com
 *            the message to be processed
 * @return the senders e-mail address
 */
public static String getSenderEmailAddress(Message message) {
    String from = null;
    try {
        if (message.getFrom() != null && message.getFrom().length > 0) {
            InternetAddress fromAddress = (InternetAddress) message.getFrom()[0];
            if (null != fromAddress) {
                from = fromAddress.getAddress();
            }
        } else {
            LOGGER.warn("No from sender address in message!");
        }
    } catch (Exception e) {
        // can't do much here
        LOGGER.warn("Can't get sender email address", e);
    }
    return from;
}

From source file:com.aurel.track.util.emailHandling.MailReader.java

/**
 * Retrieves the senders name from this message if possible.
 *
 * @param message/*  w ww .  java  2  s .  c om*/
 *            the message to be processed
 * @return the senders e-mail address
 */
public static String getSenderName(Message message) {
    String from = null;
    try {
        InternetAddress fromAddress = (InternetAddress) message.getFrom()[0];
        if (null != fromAddress) {
            if (null != fromAddress.getPersonal()) {
                // if there is a name, return it
                from = fromAddress.getPersonal();
            }
        }
    } catch (Exception e) {
        LOGGER.error(ExceptionUtils.getStackTrace(e));
        // can't do much here
    }
    return from;
}

From source file:com.aurel.track.util.emailHandling.MailReader.java

/**
 * Retrieves the sender as a TPersonBean with first and last name
 *
 * @param message// w  ww  .j a v  a 2 s  .  c  om
 *            the message to be processed
 * @return the sender
 */
public static TPersonBean getSender(Message message) {
    String from = null;
    TPersonBean sender = null;
    String firstName = "";
    String lastName = "";
    try {
        if (message.getFrom() != null && message.getFrom().length > 0) {
            InternetAddress fromAddress = (InternetAddress) message.getFrom()[0];
            if (null != fromAddress) {
                from = fromAddress.getAddress();
                String name = fromAddress.getPersonal();
                if (name != null && !"".equals(name)) {
                    String nameparts[] = name.split("\\s+");
                    for (int i = 0; i < nameparts.length - 1; ++i) {
                        firstName = firstName + " " + nameparts[i];
                    }
                    firstName = firstName.trim();
                    lastName = nameparts[nameparts.length - 1];
                }
                sender = new TPersonBean();
                sender.setEmail(from);
                sender.setFirstName(firstName);
                sender.setLastName(lastName);
            }
        } else {
            LOGGER.warn("No from sender address in message!");
        }
    } catch (Exception e) {
        // can't do much here
        LOGGER.warn("Can't get sender email address", e);
    }
    return sender;
}

From source file:com.cubusmail.mail.util.MessageUtils.java

/**
 * @param mailFolder//from  w  w  w .  jav a  2s. c  o  m
 * @param msgs
 * @param extendedSearchFields
 * @param params
 * @return
 */
public static Message[] filterMessages(IMailFolder mailFolder, Message[] msgs, String extendedSearchFields,
        String[][] params) {

    if (!StringUtils.isEmpty(extendedSearchFields)) {
        String[] fields = StringUtils.split(extendedSearchFields, ',');

        List<Message> filteredMsgs = new ArrayList<Message>();
        String fromValue = getParamValue(params, SearchFields.FROM.name());
        String toValue = getParamValue(params, SearchFields.TO.name());
        String ccValue = getParamValue(params, SearchFields.CC.name());
        String subjectValue = getParamValue(params, SearchFields.SUBJECT.name());
        String contentValue = getParamValue(params, SearchFields.CONTENT.name());
        String dateFromValue = getParamValue(params, SearchFields.DATE_FROM.name());
        String dateToValue = getParamValue(params, SearchFields.DATE_TO.name());

        try {
            // Body search
            if (StringUtils.contains(extendedSearchFields, SearchFields.CONTENT.name())) {
                BodyTerm term = new BodyTerm(contentValue);
                msgs = mailFolder.search(term, msgs);
                if (msgs == null) {
                    msgs = new Message[0];
                }
            }

            for (Message message : msgs) {
                boolean contains = true;
                for (String searchField : fields) {
                    if (SearchFields.FROM.name().equals(searchField)) {
                        String from = MessageUtils.getMailAdressString(message.getFrom(),
                                AddressStringType.COMPLETE);
                        contains = StringUtils.containsIgnoreCase(from, fromValue);
                    }
                    if (contains && SearchFields.TO.name().equals(searchField)) {
                        String to = MessageUtils.getMailAdressString(
                                message.getRecipients(Message.RecipientType.TO), AddressStringType.COMPLETE);
                        if (!StringUtils.isEmpty(to)) {
                            contains = StringUtils.containsIgnoreCase(to, toValue);
                        } else {
                            contains = false;
                        }
                    }
                    if (contains && SearchFields.CC.name().equals(searchField)) {
                        String cc = MessageUtils.getMailAdressString(
                                message.getRecipients(Message.RecipientType.CC), AddressStringType.COMPLETE);
                        if (!StringUtils.isEmpty(cc)) {
                            contains = StringUtils.containsIgnoreCase(cc, ccValue);
                        } else {
                            contains = false;
                        }
                    }
                    if (contains && SearchFields.SUBJECT.name().equals(searchField)) {
                        if (!StringUtils.isEmpty(message.getSubject())) {
                            contains = StringUtils.containsIgnoreCase(message.getSubject(), subjectValue);
                        } else {
                            contains = false;
                        }
                    }
                    if (contains && SearchFields.DATE_FROM.name().equals(searchField)) {
                        Date dateFrom = new Date(Long.parseLong(dateFromValue));
                        if (message.getSentDate() != null) {
                            contains = !message.getSentDate().before(dateFrom);
                        } else {
                            contains = false;
                        }
                    }
                    if (contains && SearchFields.DATE_TO.name().equals(searchField)) {
                        Date dateTo = new Date(Long.parseLong(dateToValue));
                        if (message.getSentDate() != null) {
                            contains = !message.getSentDate().after(dateTo);
                        } else {
                            contains = false;
                        }
                    }
                }
                if (contains) {
                    filteredMsgs.add(message);
                }
            }
        } catch (MessagingException ex) {
            log.warn(ex.getMessage());
        }

        return filteredMsgs.toArray(new Message[0]);
    }

    return msgs;
}

From source file:com.mycompany.apsdtask.MessageToEmailConverter.java

EMail convert(Message message) {
    EMail eMail = new EMail();
    try {//from  w  w w  .  j av a 2s  . com
        eMail.setAuthor(((InternetAddress) message.getFrom()[0]).getAddress());
        eMail.setDate(message.getSentDate());
        eMail.setSubject(message.getSubject());
        Object contnet = message.getContent();
        eMail.setBody((contnet instanceof MimeMultipart)
                ? ((MimeMultipart) contnet).getBodyPart(0).getContent().toString()
                : contnet.toString());
    } catch (IOException | MessagingException e) {
        throw new RuntimeException(e);
    }
    return eMail;
}

From source file:com.mycompany.apsdtask.domain.MessageToEmailConverter.java

@Override
public EMail convert(Message message) {
    EMail eMail = new EMail();
    try {/*from   w w  w.java 2 s  . c o  m*/
        eMail.setAuthor(((InternetAddress) message.getFrom()[0]).getAddress());
        eMail.setDate(message.getSentDate());
        eMail.setSubject(message.getSubject());
        Object contnet = message.getContent();
        eMail.setBody((contnet instanceof MimeMultipart)
                ? ((MimeMultipart) contnet).getBodyPart(0).getContent().toString()
                : contnet.toString());
    } catch (IOException | MessagingException e) {
        throw new RuntimeException(e);
    }
    return eMail;
}

From source file:org.nuxeo.ecm.platform.mail.action.CheckSenderAction.java

public boolean execute(ExecutionContext context) throws MessagingException {
    Message message = context.getMessage();
    Address[] addresses = message.getFrom();
    if (addresses == null || addresses.length == 0 || !(addresses[0] instanceof InternetAddress)) {
        log.debug("No internet messages, stopping the pipe: " + message);
        return false;
    }/*from ww w  . j  av  a  2s.co  m*/
    InternetAddress address = (InternetAddress) addresses[0];
    String principal = getPrincipal(address.getAddress());
    if (principal == null) {
        log.debug("Sender not in user directory. Stop processing");
        return false;
    }
    context.put("sender", principal);
    return true;
}

From source file:com.cubusmail.server.services.ConvertUtil.java

/**
 * @param folder//from  www  . ja  va  2s.  c o m
 * @param msg
 * @param result
 * @throws MessagingException
 */
private static void convertToStringArray(IMAPFolder folder, Message msg, GWTMessageRecord result,
        DateFormat dateFormat, NumberFormat decimalFormat) throws MessagingException {

    result.setId(Long.toString(folder.getUID(msg)));
    try {
        result.setAttachmentImage(MessageUtils.hasAttachments(msg) ? ImageProvider.MSG_ATTACHMENT : null);
    } catch (IOException e) {
        // do nothing
    }
    GWTMessageFlags flags = new GWTMessageFlags();
    flags.setDeleted(msg.isSet(Flags.Flag.DELETED));
    flags.setUnread(!msg.isSet(Flags.Flag.SEEN));
    flags.setAnswered(msg.isSet(Flags.Flag.ANSWERED));
    flags.setDraft(msg.isSet(Flags.Flag.DRAFT));
    result.setFlags(flags);

    result.setProrityImage(getPriorityImage(msg));
    result.setSubject(HtmlUtils.htmlEscape(msg.getSubject()));

    result.setFrom(
            HtmlUtils.htmlEscape(MessageUtils.getMailAdressString(msg.getFrom(), AddressStringType.PERSONAL)));
    result.setTo(HtmlUtils.htmlEscape(
            MessageUtils.getMailAdressString(msg.getRecipients(RecipientType.TO), AddressStringType.PERSONAL)));
    if (msg.getSentDate() != null) {
        result.setSendDateString(HtmlUtils.htmlEscape(dateFormat.format(msg.getSentDate())));
        result.setSendDate(msg.getSentDate());
    }

    int msgSize = MessageUtils.calculateAttachmentSize(msg.getSize());
    result.setSizeString(HtmlUtils.htmlEscape(MessageUtils.formatPartSize(msgSize, decimalFormat)));
    result.setSize(msgSize);
}