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:org.apache.hupa.server.handler.AbstractFetchMessagesHandler.java

protected ArrayList<org.apache.hupa.shared.data.Message> convert(int offset,
        com.sun.mail.imap.IMAPFolder folder, Message[] messages) throws MessagingException {
    ArrayList<org.apache.hupa.shared.data.Message> mList = new ArrayList<org.apache.hupa.shared.data.Message>();
    // Setup fetchprofile to limit the stuff which is fetched 
    FetchProfile fp = new FetchProfile();
    fp.add(FetchProfile.Item.ENVELOPE);// w  ww. j  av  a 2s.c o m
    fp.add(FetchProfile.Item.FLAGS);
    fp.add(FetchProfile.Item.CONTENT_INFO);
    fp.add(UIDFolder.FetchProfileItem.UID);
    folder.fetch(messages, fp);

    // loop over the fetched messages
    for (int i = 0; i < messages.length && i < offset; i++) {
        org.apache.hupa.shared.data.Message msg = new org.apache.hupa.shared.data.Message();
        Message m = messages[i];
        String from = null;
        if (m.getFrom() != null && m.getFrom().length > 0) {
            from = MessageUtils.decodeText(m.getFrom()[0].toString());
        }
        msg.setFrom(from);

        String replyto = null;
        if (m.getReplyTo() != null && m.getReplyTo().length > 0) {
            replyto = MessageUtils.decodeText(m.getReplyTo()[0].toString());
        }
        msg.setReplyto(replyto);

        ArrayList<String> to = new ArrayList<String>();
        // Add to addresses
        Address[] toArray = m.getRecipients(RecipientType.TO);
        if (toArray != null) {
            for (Address addr : toArray) {
                String mailTo = MessageUtils.decodeText(addr.toString());
                to.add(mailTo);
            }
        }
        msg.setTo(to);

        // Check if a subject exist and if so decode it
        String subject = m.getSubject();
        if (subject != null) {
            subject = MessageUtils.decodeText(subject);
        }
        msg.setSubject(subject);

        // Add cc addresses
        Address[] ccArray = m.getRecipients(RecipientType.CC);
        ArrayList<String> cc = new ArrayList<String>();
        if (ccArray != null) {
            for (Address addr : ccArray) {
                String mailCc = MessageUtils.decodeText(addr.toString());
                cc.add(mailCc);
            }
        }
        msg.setCc(cc);

        userPreferences.addContact(from);
        userPreferences.addContact(to);
        userPreferences.addContact(replyto);
        userPreferences.addContact(cc);

        // Using sentDate since received date is not useful in the view when using fetchmail
        msg.setReceivedDate(m.getSentDate());

        // Add flags
        ArrayList<IMAPFlag> iFlags = JavamailUtil.convert(m.getFlags());

        ArrayList<Tag> tags = new ArrayList<Tag>();
        for (String flag : m.getFlags().getUserFlags()) {
            if (flag.startsWith(Tag.PREFIX)) {
                tags.add(new Tag(flag.substring(Tag.PREFIX.length())));
            }
        }

        msg.setUid(folder.getUID(m));
        msg.setFlags(iFlags);
        msg.setTags(tags);
        try {
            msg.setHasAttachments(hasAttachment(m));
        } catch (MessagingException e) {
            logger.debug("Unable to identify attachments in message UID:" + msg.getUid() + " subject:"
                    + msg.getSubject() + " cause:" + e.getMessage());
            logger.info("");
        }
        mList.add(0, msg);

    }
    return mList;
}

From source file:org.webguitoolkit.messagebox.mail.MailChannel.java

/**
 * //from ww  w .ja  va  2s  .c o  m
 */
@Override
public List<IMessage> receive(boolean clear) {
    List<IMessage> result = new ArrayList<IMessage>();

    try {
        String user = properties.getProperty("pop3.login.user");
        String password = properties.getProperty("pop3.login.password");

        String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        Properties pop3Props = new Properties();

        pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
        pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
        pop3Props.setProperty("mail.pop3.port", properties.getProperty("pop3.port"));
        pop3Props.setProperty("mail.pop3.socketFactory.port", properties.getProperty("pop3.port"));

        URLName url = new URLName("pop3", properties.getProperty("pop3.host"),
                Integer.valueOf(properties.getProperty("pop3.port")), "", user, password);

        Session session = Session.getInstance(pop3Props, null);
        Store store = new POP3SSLStore(session, url);
        store.connect();

        // Open the Folder
        Folder folder = store.getDefaultFolder();
        folder = folder.getFolder("INBOX");

        if (folder == null) {
            throw new RuntimeException("Invalid folder INBOX");
        }

        // try to open read/write and if that fails try read-only
        try {
            folder.open(Folder.READ_WRITE);
        } catch (MessagingException ex) {
            folder.open(Folder.READ_ONLY);
        }

        int count = folder.getMessageCount();
        // Message numbers start at 1
        for (int i = 1; i <= count; i++) {
            // Get a message by its sequence number
            Message m = folder.getMessage(i);
            Address[] from = m.getFrom();
            String type = from[0].getType();

            IMessage message = new MailMessage(from[0].toString(), this, m.getSubject(), getContent(m));

            result.add(message);

            // delete message ?
            if (clear)
                m.setFlag(Flags.Flag.DELETED, true);
        }

        // "true" actually deletes flagged messages from folder
        folder.close(clear);
        store.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;
}

From source file:server.MailPop3Expert.java

@Override
public void run() {
    //obtengo la agenda
    List<String> agenda = XmlParcerExpert.getInstance().getAgenda();

    while (store.isConnected()) {
        try {//from  w w  w .jav a  2  s .c  o  m

            // Abre la carpeta INBOX
            Folder folderInbox = store.getFolder("INBOX");
            folderInbox.open(Folder.READ_ONLY);

            // Obtiene los mails
            Message[] arrayMessages = folderInbox.getMessages();

            //procesa los mails
            for (int i = 0; i < arrayMessages.length; i++) {
                Message message = arrayMessages[i];
                Address[] fromAddress = message.getFrom();
                String from = fromAddress[0].toString();
                String subject = message.getSubject();
                String sentDate = message.getSentDate().toString();
                String messageContent = "";
                String contentType = message.getContentType();

                if (contentType.contains("multipart")) {
                    // Si el contenido es mulpart
                    Multipart multiPart = (Multipart) message.getContent();
                    int numberOfParts = multiPart.getCount();
                    for (int partCount = 0; partCount < numberOfParts; partCount++) {
                        MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                        if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                            // si contiene un archivo
                        } else {
                            // el contenido del mensaje
                            messageContent = part.getContent().toString();
                        }
                    }

                } else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                    Object content = message.getContent();
                    if (content != null) {
                        messageContent = content.toString();
                    }
                }

                //parseo del from
                if (from.contains("<")) {
                    from = from.substring(from.indexOf("<") + 1, from.length() - 1);
                }

                //si esta en la agenda
                if (agenda.contains(from)) {
                    //obtiene la trama
                    try {
                        messageContent = messageContent.substring(messageContent.indexOf("&gt"),
                                messageContent.indexOf("&lt;") + 4);
                        if (messageContent.startsWith("&gt") && messageContent.endsWith("&lt;")) {
                            //procesa el mail
                            XmlParcerExpert.getInstance().processAndSaveMail(from, messageContent);
                            frame.loadMails();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    //no lo guarda
                }

            }

            folderInbox.close(false);

            //duerme el hilo por el tiempo de la frecuencia
            Thread.sleep(frecuency * 60 * 1000);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException ex) {
            //Logger.getLogger(MailPop3Expert.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MessagingException ex) {
            //Logger.getLogger(MailPop3Expert.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:org.openiam.idm.srvc.msg.service.MailSender.java

public void send(Message msg) {
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    Session session = Session.getDefaultInstance(properties);
    MimeMessage message = new MimeMessage(session);
    try {//  w ww.java2s.c o  m
        message.setFrom(msg.getFrom());
        message.addRecipient(javax.mail.Message.RecipientType.TO, msg.getTo());
        message.setSubject(msg.getSubject());
        message.setText(msg.getBody());

        Transport.send(message);
        log.info("Message successfully sent.");
    } catch (MessagingException me) {
        log.error(me);
        me.printStackTrace();
    }
}

From source file:nz.net.orcon.kanban.automation.actions.EmailReceiverAction.java

public void generateMailNotification(String mailStoreProtocol, String mailStoreHost, String mailStoreUserName,
        String mailStorePassword, String notificationType, String fromFilter, String subjectFilter)
        throws Exception {
    Session session = getMailStoreSession(mailStoreProtocol, mailStoreHost, mailStoreUserName,
            mailStorePassword);/*w ww  .  jav a  2s.  c  om*/
    try {
        // connects to the message store
        Store store = session.getStore(mailStoreProtocol);
        store.connect(mailStoreHost, mailStoreUserName, mailStorePassword);

        logger.info("connected to message store");

        // opens the inbox folder
        Folder folderInbox = store.getFolder("INBOX");
        folderInbox.open(Folder.READ_WRITE);

        // check if fromFilter is specified
        List<String> fromFilterList = null;

        if (StringUtils.isNotBlank(fromFilter)) {
            String[] fromFilterArray = StringUtils.split(fromFilter, "|");
            fromFilterList = Arrays.asList(fromFilterArray);
        }

        // check if subjectFilter is specified
        List<String> subjectFilterList = null;
        if (StringUtils.isNotBlank(subjectFilter)) {
            String[] subjectFilterArray = StringUtils.split(subjectFilter, "|");
            subjectFilterList = Arrays.asList(subjectFilterArray);
        }
        Map<String, Object> context = new HashMap<String, Object>();
        // fetches new messages from server
        Message[] messages = folderInbox.getMessages();
        for (int i = 0; i < messages.length; i++) {
            Message msg = messages[i];
            Address[] fromAddress = msg.getFrom();
            String address = fromAddress[0].toString();
            String from = extractFromAddress(address);
            if (StringUtils.isBlank(from)) {
                logger.warn("From Address is not proper " + from);
                return;
            }
            boolean isValidFrom = isValidMatch(fromFilterList, from);

            // filter based on fromFilter specified
            if (null == fromFilterList || isValidFrom) {
                String subject = msg.getSubject();

                boolean isValidSubject = isValidMatch(subjectFilterList, subject);
                if (null == subjectFilterList || isValidSubject) {
                    String toList = parseAddresses(msg.getRecipients(RecipientType.TO));
                    String ccList = parseAddresses(msg.getRecipients(RecipientType.CC));
                    String sentDate = msg.getSentDate().toString();

                    String messageContent = "";
                    try {
                        Object content = msg.getContent();
                        if (content != null) {
                            messageContent = content.toString();
                        }
                    } catch (Exception ex) {
                        messageContent = "[Error downloading content]";
                        ex.printStackTrace();
                    }
                    context.put("from", from);
                    context.put("to", toList);
                    context.put("cc", ccList);
                    context.put("subject", subject);
                    context.put("messagebody", messageContent);
                    context.put("sentdate", sentDate);

                    notificationController.createNotification(notificationType, context);
                    msg.setFlag(Flag.DELETED, true);
                } else {
                    logger.warn("subjectFilter doesn't match");
                }
            } else {
                logger.warn("this email originated from " + address
                        + " , which does not match fromAddress specified in the rule, it should be "
                        + fromFilter.toString());
            }
        }
        // disconnect and delete messages marked as DELETED
        folderInbox.close(true);
        store.close();
    } catch (NoSuchProviderException ex) {
        logger.warn("No provider for protocol: " + mailStoreProtocol + " " + ex);
    } catch (MessagingException ex) {
        logger.error("Could not connect to the message store" + ex);
    }
}

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

/**
 * @param folder/*  ww w  .  j av a 2 s . c o  m*/
 * @param msg
 * @param result
 * @throws MessagingException
 */
public static void convertToStringArray(IMailFolder folder, Message msg, String[] result, DateFormat dateFormat,
        NumberFormat decimalFormat) throws MessagingException {

    result[MessageListFields.ID.ordinal()] = Long.toString(folder.getUID(msg));
    try {
        result[MessageListFields.ATTACHMENT_FLAG.ordinal()] = Boolean
                .toString(MessageUtils.hasAttachments(msg));
    } catch (IOException e) {
        // do nothing
    }
    result[MessageListFields.READ_FLAG.ordinal()] = Boolean.toString(msg.isSet(Flags.Flag.SEEN));
    result[MessageListFields.DELETED_FLAG.ordinal()] = Boolean.toString(msg.isSet(Flags.Flag.DELETED));
    result[MessageListFields.ANSWERED_FLAG.ordinal()] = Boolean.toString(msg.isSet(Flags.Flag.ANSWERED));
    result[MessageListFields.DRAFT_FLAG.ordinal()] = Boolean.toString(msg.isSet(Flags.Flag.DRAFT));
    result[MessageListFields.PRIORITY.ordinal()] = Integer.toString(MessageUtils.getMessagePriority(msg));
    if (!StringUtils.isEmpty(msg.getSubject())) {
        result[MessageListFields.SUBJECT.ordinal()] = msg.getSubject();
    }
    result[MessageListFields.FROM.ordinal()] = MessageUtils.getMailAdressString(msg.getFrom(),
            AddressStringType.PERSONAL);
    result[MessageListFields.TO.ordinal()] = MessageUtils
            .getMailAdressString(msg.getRecipients(RecipientType.TO), AddressStringType.PERSONAL);
    if (msg.getSentDate() != null) {
        result[MessageListFields.DATE.ordinal()] = dateFormat.format(msg.getSentDate());
    }
    result[MessageListFields.SIZE.ordinal()] = MessageUtils
            .formatPartSize(MessageUtils.calculateAttachmentSize(msg.getSize()), decimalFormat);
}

From source file:com.app.test.mail.DefaultMailSenderTest.java

@Test
public void testPopulateContactMessage() throws Exception {
    Method populateContactMessage = _clazz.getDeclaredMethod("_populateContactMessage", String.class,
            String.class, Session.class);

    populateContactMessage.setAccessible(true);

    Message message = (Message) populateContactMessage.invoke(_classInstance, "user@test.com",
            "Sample contact message", _session);

    Assert.assertEquals("user@test.com", message.getFrom()[0].toString());
    Assert.assertEquals("You Have A New Message From user@test.com", message.getSubject());
    Assert.assertEquals("Sample contact message", message.getContent());
}

From source file:ch.entwine.weblounge.bridge.mail.MailAggregator.java

/**
 * Returns the author of this message. If the message does not have a
 * <code>from</code> field, an {@link IllegalArgumentException} is thrown.
 * /*  ww  w  . ja  v  a 2  s .c o  m*/
 * @param message
 *          the e-mail message
 * @return the sender
 * @throws MessagingException
 *           if reading the message's author fails
 * @throws IllegalArgumentException
 *           if no author can be found
 */
private String getAuthor(Message message) throws MessagingException, IllegalArgumentException {
    Address[] address = message.getFrom();
    if (address == null || address.length == 0)
        throw new MessagingException("Message has no author");
    return address[0].toString();
}

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

public boolean execute(ExecutionContext context) throws MessagingException {
    Message message = context.getMessage();
    if (log.isDebugEnabled()) {
        log.debug("Transforming message" + message.getSubject());
    }//  w w  w  .  j  a  va2  s  .c  o  m
    if (message.getFrom() != null && message.getFrom().length != 0) {
        List<String> contributors = new ArrayList<String>();
        for (Address ad : message.getFrom()) {
            contributors.add(safelyDecodeText(ad.toString()));
        }
        dcSchema.put("contributors", contributors);
        dcSchema.put("creator", contributors.get(0));
        dcSchema.put("created", message.getReceivedDate());
    }
    if (message.getAllRecipients() != null && message.getAllRecipients().length != 0) {
        List<String> recipients = new ArrayList<String>();
        for (Address address : message.getAllRecipients()) {
            recipients.add(safelyDecodeText(address.toString()));
        }
        mailSchema.put("recipients", recipients);
    }
    if (message instanceof MimeMessage) {
        try {
            processMimeMessage((MimeMessage) message);
        } catch (IOException e) {
            throw new MessagingException(e.getMessage(), e);
        }
    }
    mailSchema.put("text", text.toString());
    dcSchema.put("title", message.getSubject());
    context.put("transformed", schemas);
    return true;
}

From source file:com.app.test.mail.DefaultMailSenderTest.java

@Test
public void testPopulateWelcomeMessage() throws Exception {
    _initializeVelocityTemplate(_clazz, _classInstance);

    Method populateMessage = _clazz.getDeclaredMethod("_populateMessage", String.class, String.class,
            String.class, Session.class);

    populateMessage.setAccessible(true);

    Message message = (Message) populateMessage.invoke(_classInstance, "user@test.com", "Welcome",
            "welcome_email.vm", _session);

    Assert.assertEquals("Auction Alert <test@test.com>", message.getFrom()[0].toString());
    Assert.assertEquals("Welcome", message.getSubject());
    Assert.assertEquals(_WELCOME_EMAIL, message.getContent());

    InternetAddress[] internetAddresses = new InternetAddress[1];

    internetAddresses[0] = new InternetAddress("user@test.com");

    Assert.assertArrayEquals(internetAddresses, message.getRecipients(Message.RecipientType.TO));
}