Example usage for javax.mail Message getSubject

List of usage examples for javax.mail Message getSubject

Introduction

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

Prototype

public abstract String getSubject() throws MessagingException;

Source Link

Document

Get the subject of this message.

Usage

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

@Test
public void testPopulateResubscribeMessage() 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",
            "Resubscribe Successful", "resubscribe_email.vm", _session);

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

    InternetAddress[] internetAddresses = new InternetAddress[1];

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

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

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

@Test
public void testPopulateCancellationMessage() 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",
            "Cancellation Successful", "cancellation_email.vm", _session);

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

    InternetAddress[] internetAddresses = new InternetAddress[1];

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

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

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

@Test
public void testPopulateAccountDeletionMessage() 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",
            "Account Deletion Successful", "account_deletion_email.vm", _session);

    Assert.assertEquals("Auction Alert <test@test.com>", message.getFrom()[0].toString());
    Assert.assertEquals("Account Deletion Successful", message.getSubject());
    Assert.assertEquals(_ACCOUNT_DELETION_EMAIL, message.getContent());

    InternetAddress[] internetAddresses = new InternetAddress[1];

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

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

From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java

protected void deleteMailsFromUserMailbox(final Properties props, final String folderName, final int start,
        final int deleteCount, final String user, final String password) throws MessagingException {
    final Store store = Session.getInstance(props).getStore();

    store.connect(user, password);//from w ww.j a v a 2s .  c o m
    checkStoreForTestConnection(store);
    final Folder f = store.getFolder(folderName);
    f.open(Folder.READ_WRITE);

    final int msgCount = f.getMessageCount();

    final Message[] m = deleteCount == -1 ? f.getMessages()
            : f.getMessages(start, Math.min(msgCount, deleteCount + start - 1));
    int d = 0;

    for (final Message message : m) {
        message.setFlag(Flag.DELETED, true);
        logger.info("Delete msgnum: {} with sid {}", message.getMessageNumber(), message.getSubject());
        d++;
    }

    f.close(true);
    logger.info("Deleted " + d + " messages");
    store.close();

}

From source file:org.codice.ddf.platform.email.impl.SmtpClientImpl.java

@Override
public Future<Void> send(Message message) {
    notNull(message, "message must be non-null");
    return executorService.submit(() -> {
        try {//  w  w  w.j  a  v  a 2  s . c o  m
            Transport.send(message);
        } catch (MessagingException e) {
            LOGGER.debug("Could not send message {}", message, e);
            return null;
        }

        SecurityLogger.audit("Sent an email: recipient={} subject={}",
                Arrays.toString(message.getAllRecipients()), message.getSubject());
        return null;
    });
}

From source file:com.naryx.tagfusion.cfm.mail.cfMailMessageData.java

private boolean extractMessage(Message Mess, long messageID, String attachURI, String attachDIR) {
    cfArrayData ADD = cfArrayData.createArray(1);

    try {/*ww w .  j  a v a2  s .  c o m*/

        setData("subject", new cfStringData(Mess.getSubject()));
        setData("id", new cfNumberData(messageID));

        //--- Pull out all the headers
        cfStructData headers = new cfStructData();
        Enumeration<Header> eH = Mess.getAllHeaders();
        String headerKey;
        while (eH.hasMoreElements()) {
            Header hdr = eH.nextElement();

            headerKey = hdr.getName().replace('-', '_').toLowerCase();
            if (headers.containsKey(headerKey)) {
                headers.setData(headerKey,
                        new cfStringData(headers.getData(headerKey).toString() + ";" + hdr.getValue()));
            } else
                headers.setData(headerKey, new cfStringData(hdr.getValue()));
        }

        setData("headers", headers);

        // Get the Date
        Date DD = Mess.getReceivedDate();
        if (DD == null)
            setData("rxddate", new cfDateData(System.currentTimeMillis()));
        else
            setData("rxddate", new cfDateData(DD.getTime()));

        DD = Mess.getSentDate();
        if (DD == null)
            setData("sentdate", new cfDateData(System.currentTimeMillis()));
        else
            setData("sentdate", new cfDateData(DD.getTime()));

        // Get the FROM field
        Address[] from = Mess.getFrom();
        if (from != null && from.length > 0) {
            cfStructData sdFrom = new cfStructData();
            String name = ((InternetAddress) from[0]).getPersonal();
            if (name != null)
                sdFrom.setData("name", new cfStringData(name));

            sdFrom.setData("email", new cfStringData(((InternetAddress) from[0]).getAddress()));
            setData("from", sdFrom);
        }

        //--[ Get the TO/CC/BCC field
        cfArrayData AD = extractAddresses(Mess.getRecipients(Message.RecipientType.TO));
        if (AD != null)
            setData("to", AD);

        AD = extractAddresses(Mess.getRecipients(Message.RecipientType.CC));
        if (AD != null)
            setData("cc", AD);

        AD = extractAddresses(Mess.getRecipients(Message.RecipientType.BCC));
        if (AD != null)
            setData("bcc", AD);

        AD = extractAddresses(Mess.getReplyTo());
        if (AD != null)
            setData("replyto", AD);

        //--[ Set the flags
        setData("answered", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.ANSWERED)));
        setData("deleted", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.DELETED)));
        setData("draft", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.DRAFT)));
        setData("flagged", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.FLAGGED)));
        setData("recent", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.RECENT)));
        setData("seen", cfBooleanData.getcfBooleanData(Mess.isSet(Flags.Flag.SEEN)));

        setData("size", new cfNumberData(Mess.getSize()));
        setData("lines", new cfNumberData(Mess.getLineCount()));

        String tmp = Mess.getContentType();
        if (tmp.indexOf(";") != -1)
            tmp = tmp.substring(0, tmp.indexOf(";"));

        setData("mimetype", new cfStringData(tmp));

        // Get the body of the email
        extractBody(Mess, ADD, attachURI, attachDIR);

    } catch (Exception E) {
        return false;
    }

    setData("body", ADD);
    return true;
}

From source file:org.accesointeligente.server.robots.ResponseChecker.java

public void connectAndCheck() {
    if (ApplicationProperties.getProperty("email.server") == null
            || ApplicationProperties.getProperty("email.user") == null
            || ApplicationProperties.getProperty("email.password") == null
            || ApplicationProperties.getProperty("email.folder") == null
            || ApplicationProperties.getProperty("email.failfolder") == null
            || ApplicationProperties.getProperty("attachment.directory") == null
            || ApplicationProperties.getProperty("attachment.baseurl") == null) {
        logger.error("Properties are not defined!");
        return;/*from w ww. j  a  v  a  2 s .  c om*/
    }

    org.hibernate.Session hibernate = null;

    try {
        session = Session.getInstance(props, null);
        store = session.getStore("imaps");
        store.connect(ApplicationProperties.getProperty("email.server"),
                ApplicationProperties.getProperty("email.user"),
                ApplicationProperties.getProperty("email.password"));

        Folder failbox = store.getFolder(ApplicationProperties.getProperty("email.failfolder"));
        Folder inbox = store.getFolder(ApplicationProperties.getProperty("email.folder"));
        inbox.open(Folder.READ_WRITE);

        for (Message message : inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false))) {
            try {
                logger.info("Sender: " + message.getFrom()[0] + "\tSubject: " + message.getSubject());
                remoteIdentifiers = null;
                messageBody = null;
                remoteIdentifiers = new HashSet<String>();

                if (message.getSubject() != null) {
                    Matcher matcher = pattern.matcher(message.getSubject());

                    if (matcher.matches()) {
                        remoteIdentifiers.add(formatIdentifier(matcher.group(1), matcher.group(2),
                                Integer.parseInt(matcher.group(3))));
                        logger.info("remote identifier: " + formatIdentifier(matcher.group(1), matcher.group(2),
                                Integer.parseInt(matcher.group(3))));
                    }
                }

                Object content = message.getContent();

                if (content instanceof Multipart) {
                    Multipart mp = (Multipart) message.getContent();
                    logger.info("Email content type is Multipart, each part of " + mp.getCount()
                            + " will be processed");

                    for (int i = 0, n = mp.getCount(); i < n; i++) {
                        Part part = mp.getBodyPart(i);
                        logger.info("Part: " + (i + 1) + " of " + mp.getCount());
                        processPart(part);
                    }
                } else if (content instanceof String) {
                    logger.info("Email content type is String");
                    messageBody = (String) content;
                    Matcher matcher;
                    StringTokenizer tokenizer = new StringTokenizer(messageBody);

                    while (tokenizer.hasMoreTokens()) {
                        String token = tokenizer.nextToken();
                        matcher = pattern.matcher(token);

                        if (matcher.matches()) {
                            remoteIdentifiers.add(formatIdentifier(matcher.group(1), matcher.group(2),
                                    Integer.parseInt(matcher.group(3))));
                            logger.info("remote identifier: " + formatIdentifier(matcher.group(1),
                                    matcher.group(2), Integer.parseInt(matcher.group(3))));
                        }
                    }
                } else {
                    logger.info("Email content type isn't String or Multipart");
                    message.setFlag(Flag.SEEN, false);
                    inbox.copyMessages(new Message[] { message }, failbox);
                    message.setFlag(Flag.DELETED, true);
                    inbox.expunge();
                    continue;
                }

                Boolean requestFound = false;
                Matcher matcher = htmlPattern.matcher(messageBody);

                if (matcher.find()) {
                    messageBody = htmlToString(messageBody);
                }

                logger.info("Searching for Request Remote Identifier");
                for (String remoteIdentifier : remoteIdentifiers) {
                    hibernate = HibernateUtil.getSession();
                    hibernate.beginTransaction();

                    Criteria criteria = hibernate.createCriteria(Request.class);
                    criteria.add(Restrictions.eq("remoteIdentifier", remoteIdentifier));
                    Request request = (Request) criteria.uniqueResult();
                    hibernate.getTransaction().commit();

                    if (request != null) {
                        logger.info("Request found for Remote Identifier: " + remoteIdentifier);
                        Response response;

                        // If the attachments haven't been used, use them. Otherwise, copy them.
                        if (!requestFound) {
                            response = createResponse(message.getFrom()[0].toString(), message.getSentDate(),
                                    message.getSubject(), messageBody);
                        } else {
                            response = createResponse(message.getFrom()[0].toString(), message.getSentDate(),
                                    message.getSubject(), messageBody);
                        }

                        hibernate = HibernateUtil.getSession();
                        hibernate.beginTransaction();

                        response.setRequest(request);
                        request.setStatus(RequestStatus.RESPONDED);
                        request.setExpired(RequestExpireType.WITHRESPONSE);
                        request.setResponseDate(new Date());
                        hibernate.update(request);
                        hibernate.update(response);
                        hibernate.getTransaction().commit();
                        requestFound = true;
                    }
                }

                if (!requestFound) {
                    logger.info("Request not found");
                    createResponse(message.getFrom()[0].toString(), message.getSentDate(), message.getSubject(),
                            messageBody);
                    message.setFlag(Flag.SEEN, false);
                    inbox.copyMessages(new Message[] { message }, failbox);
                    message.setFlag(Flag.DELETED, true);
                    inbox.expunge();
                }
            } catch (Exception e) {
                if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) {
                    hibernate.getTransaction().rollback();
                }

                logger.error(e.getMessage(), e);
            }
        }
    } catch (Exception e) {
        if (hibernate != null && hibernate.isOpen() && hibernate.getTransaction().isActive()) {
            hibernate.getTransaction().rollback();
        }

        logger.error(e.getMessage(), e);
    }
}

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

@Override
public boolean execute(ExecutionContext context) {
    bodyContent = "";

    boolean copyMessage = Boolean.parseBoolean(Framework.getProperty(COPY_MESSAGE, "false"));

    try {/*  w w w  .jav a2 s. com*/
        Message originalMessage = context.getMessage();
        if (log.isDebugEnabled()) {
            log.debug("Transforming message, original subject: " + originalMessage.getSubject());
        }

        // fully load the message before trying to parse to
        // override most of server bugs, see
        // http://java.sun.com/products/javamail/FAQ.html#imapserverbug
        Message message;
        if (originalMessage instanceof MimeMessage && copyMessage) {
            message = new MimeMessage((MimeMessage) originalMessage);
            if (log.isDebugEnabled()) {
                log.debug("Transforming message after full load: " + message.getSubject());
            }
        } else {
            // stuck with the original one
            message = originalMessage;
        }

        // Subject
        String subject = message.getSubject();
        if (subject != null) {
            subject = subject.trim();
        }
        if (subject == null || "".equals(subject)) {
            subject = "<Unknown>";
        }
        context.put(SUBJECT_KEY, subject);

        // Sender
        try {
            Address[] from = message.getFrom();
            String sender = null;
            String senderEmail = null;
            if (from != null) {
                Address addr = from[0];
                if (addr instanceof InternetAddress) {
                    InternetAddress iAddr = (InternetAddress) addr;
                    senderEmail = iAddr.getAddress();
                    sender = iAddr.getPersonal() + " <" + senderEmail + ">";
                } else {
                    sender += addr.toString();
                    senderEmail = sender;
                }
            }
            context.put(SENDER_KEY, sender);
            context.put(SENDER_EMAIL_KEY, senderEmail);
        } catch (AddressException ae) {
            // try to parse sender from header instead
            String[] values = message.getHeader("From");
            if (values != null) {
                context.put(SENDER_KEY, values[0]);
            }
        }
        // Sending date
        context.put(SENDING_DATE_KEY, message.getSentDate());

        // Recipients
        try {
            Address[] to = message.getRecipients(Message.RecipientType.TO);
            Collection<String> recipients = new ArrayList<String>();
            if (to != null) {
                for (Address addr : to) {
                    if (addr instanceof InternetAddress) {
                        InternetAddress iAddr = (InternetAddress) addr;
                        if (iAddr.getPersonal() != null) {
                            recipients.add(iAddr.getPersonal() + " <" + iAddr.getAddress() + ">");
                        } else {
                            recipients.add(iAddr.getAddress());
                        }
                    } else {
                        recipients.add(addr.toString());
                    }
                }
            }
            context.put(RECIPIENTS_KEY, recipients);
        } catch (AddressException ae) {
            // try to parse recipient from header instead
            Collection<String> recipients = getHeaderValues(message, Message.RecipientType.TO.toString());
            context.put(RECIPIENTS_KEY, recipients);
        }

        // CC recipients

        try {
            Address[] toCC = message.getRecipients(Message.RecipientType.CC);
            Collection<String> ccRecipients = new ArrayList<String>();
            if (toCC != null) {
                for (Address addr : toCC) {
                    if (addr instanceof InternetAddress) {
                        InternetAddress iAddr = (InternetAddress) addr;
                        ccRecipients.add(iAddr.getPersonal() + " " + iAddr.getAddress());
                    } else {
                        ccRecipients.add(addr.toString());
                    }
                }
            }
            context.put(CC_RECIPIENTS_KEY, ccRecipients);

        } catch (AddressException ae) {
            // try to parse ccRecipient from header instead
            Collection<String> ccRecipients = getHeaderValues(message, Message.RecipientType.CC.toString());
            context.put(CC_RECIPIENTS_KEY, ccRecipients);
        }
        String[] messageIdHeader = message.getHeader("Message-ID");
        if (messageIdHeader != null) {
            context.put(MailCoreConstants.MESSAGE_ID_KEY, messageIdHeader[0]);
        }

        MimetypeRegistry mimeService = (MimetypeRegistry) context.getInitialContext().get(MIMETYPE_SERVICE_KEY);

        List<Blob> blobs = new ArrayList<Blob>();
        context.put(ATTACHMENTS_KEY, blobs);

        // String[] cte = message.getHeader("Content-Transfer-Encoding");

        // process content
        getAttachmentParts(message, subject, mimeService, context);

        context.put(TEXT_KEY, bodyContent);

        return true;
    } catch (MessagingException | IOException e) {
        log.error(e, e);
    }
    return false;
}

From source file:org.gcaldaemon.core.GmailEntry.java

public final GmailMessage[] receive(String title) throws Exception {

    // Open 'INBOX' folder
    Folder inbox = mailbox.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);//w  ww. ja v  a2 s. co m
    Message[] messages = inbox.getMessages();
    if (messages == null || messages.length == 0) {
        return new GmailMessage[0];
    }

    // Loop on messages
    LinkedList list = new LinkedList();
    for (int i = 0; i < messages.length; i++) {
        Message msg = messages[i];
        if (!msg.isSet(Flag.SEEN)) {
            String subject = msg.getSubject();
            if (title == null || title.length() == 0 || title.equals(subject)) {
                GmailMessage gm = new GmailMessage();
                Address[] from = msg.getFrom();
                msg.setFlag(Flag.SEEN, true);
                if (from == null || from.length == 0) {
                    continue;
                }
                gm.subject = subject;
                gm.from = from[0].toString();
                gm.memo = String.valueOf(msg.getContent());
                list.addLast(gm);
            }
        }
    }
    inbox.close(true);

    // Return the array of the messages
    GmailMessage[] array = new GmailMessage[list.size()];
    list.toArray(array);
    return array;
}

From source file:com.opinionlab.woa.Awesome.java

public Awesome(Message message) {
    try {// w  ww.  j  a v a2s  .  co m
        this.messageID = ((MimeMessage) message).getMessageID();
        this.id = ID_PTN.matcher(this.messageID).replaceAll("_");

        this.receivedDate = message.getReceivedDate();
        this.monthDay = DATE_FORMATTER
                .format(LocalDateTime.ofInstant(receivedDate.toInstant(), systemDefault()));
        this.to = new Person((InternetAddress) //todo Do this smarter
        message.getRecipients(Message.RecipientType.TO)[0]);
        this.from = new Person((InternetAddress) message.getFrom()[0]);
        this.subject = message.getSubject();

        final MimeMessageParser parser = new MimeMessageParser((MimeMessage) message).parse();
        if (!parser.hasPlainContent()) {
            LOGGER.error(format("Unable to parse message '%s'; has no plain content", this.messageID));
            this.comment = "Unknown content.";
        } else {
            this.comment = parseContent(parser.getPlainContent());
        }
    } catch (Throwable t) {
        throw new IllegalArgumentException(t);
    }
}