List of usage examples for javax.mail Message getHeader
public String[] getHeader(String header_name) throws MessagingException;
From source file:com.email.ReceiveEmail.java
/** * This account fetches emails from a specified account and marks the emails * as seen, only touches the email account does not delete or move any * information./*from ww w . j av a 2 s .com*/ * * @param account SystemEmailModel */ public static void fetchEmail(SystemEmailModel account) { Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account); Properties properties = EmailProperties.setEmailInProperties(account); try { Session session = Session.getInstance(properties, auth); Store store = session.getStore(); store.connect(account.getIncomingURL(), account.getIncomingPort(), account.getUsername(), account.getPassword()); Folder fetchFolder = store.getFolder(account.getIncomingFolder()); if (account.getIncomingFolder().trim().equals("")) { fetchFolder = store.getFolder("INBOX"); } if (fetchFolder.exists()) { fetchFolder.open(Folder.READ_WRITE); Message[] msgs = fetchFolder.getMessages(); // USE THIS FOR UNSEEN MAIL TO SEEN MAIL //Flags seen = new Flags(Flags.Flag.SEEN); //FlagTerm unseenFlagTerm = new FlagTerm(seen, false); //Message[] msgs = fetchFolder.search(unseenFlagTerm); //fetchFolder.setFlags(msgs, seen, true); if (msgs.length > 0) { List<String> messageList = new ArrayList<>(); for (Message msg : msgs) { boolean notDuplicate = true; String headerText = Arrays.toString(msg.getHeader("Message-ID")); for (String header : messageList) { if (header.equals(headerText)) { notDuplicate = false; break; } } if (notDuplicate) { //Add to header to stop duplicates messageList.add(headerText); attachmentCount = 1; attachmentList = new ArrayList<>(); //Setup Email For dbo.Email EmailMessageModel eml = new EmailMessageModel(); String emailTime = String.valueOf(new Date().getTime()); eml.setSection(account.getSection()); eml = saveEnvelope(msg, msg, eml); eml.setId(EMail.InsertEmail(eml)); //After Email has been inserted Gather Attachments saveAttachments(msg, msg, eml); //Create Email Body eml = EmailBodyToPDF.createEmailBodyIn(eml, emailTime, attachmentList); //Insert Email Body As Attachment (so it shows up in attachment table during Docketing) EmailAttachment.insertEmailAttachment(eml.getId(), eml.getEmailBodyFileName()); //Flag email As ready to file so it is available in the docket tab of SERB3.0 eml.setReadyToFile(1); EMail.setEmailReadyToFile(eml); } if (deleteEmailEnabled) { // Will Delete message from server // Un Comment line below to run msg.setFlag(Flags.Flag.DELETED, true); } } } fetchFolder.close(true); store.close(); } } catch (MessagingException ex) { if (ex != null) { System.out.println("Unable to connect to email Server for: " + account.getEmailAddress() + "\nPlease ensure you are connected to the network and" + " try again."); } ExceptionHandler.Handle(ex); } }
From source file:com.cubusmail.mail.util.MessageUtils.java
/** * /*from ww w . ja v a2s . c om*/ * * @param msg * @return */ public static int getMessagePriority(Message msg) { int prio = CubusConstants.PRIORITY_NONE; try { String header[] = msg.getHeader(CubusConstants.FETCH_ITEM_PRIORITY); if (header != null && header.length > 0 && header[0].length() > 0) { String first = header[0].substring(0, 1); if (StringUtils.isNumeric(first)) { return Integer.parseInt(first); } } } catch (MessagingException e) { log.error(e.getMessage(), e); } return prio; }
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 *//* w w w . j ava 2 s . co m*/ 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:com.adaptris.mail.CustomHeaderFilter.java
@Override List<String> getHeaders(Message m) throws MessagingException { return Arrays.asList(ArrayUtils.nullToEmpty(m.getHeader(customHeader))); }
From source file:com.canoo.webtest.plugins.emailtest.EmailStoreHeader.java
/** * Calculate the result./* w w w. j a v a 2 s.c om*/ * * @param message * @return The result */ protected String performOperation(final Message message) throws MessagingException { if (StringUtils.isEmpty(getPartIndex())) { return arrayToString(message.getHeader(getHeaderName())); } final Object content; try { content = message.getContent(); } catch (IOException e) { LOG.error("Error processing email message: ", e); throw new MessagingException("Error processing email message: " + e.getMessage()); } if (content instanceof Multipart) { final Multipart mp = (Multipart) content; final int part = ConversionUtil.convertToInt(getPartIndex(), 0); if (part >= mp.getCount()) { throw new StepFailedException("PartIndex too large.", this); } return arrayToString(mp.getBodyPart(part).getHeader(getHeaderName())); } throw new StepFailedException("PartIndex supplied for a non-MultiPart message.", this); }
From source file:fr.gouv.culture.vitam.eml.EmlExtract.java
private static final String handleMessage(Message message, Element metadata, Element prop, String id, VitamArgument argument, ConfigLoader config) throws IOException, MessagingException { Object content = message.getContent(); String[] cte = message.getHeader("Content-Transfer-Encoding"); String[] aresult = null;//from ww w .jav a 2 s . c o m if (cte != null && cte.length > 0) { aresult = extractContentType(message.getContentType(), cte[0]); } else { aresult = extractContentType(message.getContentType(), null); } String result = ""; if (content instanceof String) { Element body = XmlDom.factory.createElement("body"); body.addAttribute("mime", aresult[0]); if (aresult[1] != null) { body.addAttribute("charset", aresult[1]); } metadata.add(body); //result = saveBody((String) content.toString(), aresult, id, argument, config); result = saveBody(message.getInputStream(), aresult, id, argument, config); } else if (content instanceof Multipart) { // handle multi part prop.addAttribute(EMAIL_FIELDS.hasAttachment.name, "true"); Multipart mp = (Multipart) content; Element identification = XmlDom.factory.createElement(EMAIL_FIELDS.attachments.name); String value = handleMultipart(mp, identification, id, argument, config); if (identification.hasContent()) { metadata.add(identification); } if (argument.extractKeyword) { result = value; } } return result; }
From source file:fr.gouv.culture.vitam.eml.EmlExtract.java
private static final String handleMessageRecur(Message message, Element identification, String id, VitamArgument argument, ConfigLoader config) throws IOException, MessagingException { Object content = message.getContent(); String result = ""; if (content instanceof String) { String[] cte = message.getHeader("Content-Transfer-Encoding"); String[] aresult = null;/* w w w. j a v a 2s . c om*/ if (cte != null && cte.length > 0) { aresult = extractContentType(message.getContentType(), cte[0]); } else { aresult = extractContentType(message.getContentType(), null); } Element emlroot = XmlDom.factory.createElement("body"); // <identity format="Internet Message Format" mime="message/rfc822" puid="fmt/278" extensions="eml"/> Element subidenti = XmlDom.factory.createElement("identification"); Element identity = XmlDom.factory.createElement("identity"); identity.addAttribute("format", "Internet Message Body Format"); identity.addAttribute("mime", aresult[0] != null ? aresult[0] : "unknown"); identity.addAttribute("extensions", aresult[3] != null ? aresult[3].substring(1) : "unknown"); if (aresult[1] != null) { identity.addAttribute("charset", aresult[1]); } identification.add(identity); emlroot.add(subidenti); identification.add(emlroot); //result += " " + saveBody((String) content.toString(), aresult, id, argument, config); result += " " + saveBody(message.getInputStream(), aresult, id, argument, config); // ignore string } else if (content instanceof Multipart) { Multipart mp = (Multipart) content; if (argument.extractKeyword) { result = handleMultipartRecur(mp, identification, id, argument, config); } else { handleMultipartRecur(mp, identification, id, argument, config); } // handle multi part } return result; }
From source file:es.ucm.fdi.dalgs.mailbox.service.MailBoxService.java
/** * Returns new messages and fetches details for each message. */// www . java 2s. co m @Transactional(readOnly = false) public ResultClass<Boolean> downloadEmails() { ResultClass<Boolean> result = new ResultClass<>(); Properties properties = getServerProperties(protocol, host, port); Session session = Session.getDefaultInstance(properties); try { // connects to the message store Store store = session.getStore(protocol); store.connect(userName, password); // opens the inbox folder Folder folderInbox = store.getFolder("INBOX"); folderInbox.open(Folder.READ_ONLY); // fetches new messages from server Message[] messages = folderInbox.getMessages(); for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; String[] idHeaders = msg.getHeader("MESSAGE-ID"); if (idHeaders != null && idHeaders.length > 0) { MessageBox exists = repositoryMailBox.getMessageBox(idHeaders[0]); if (exists == null) { MessageBox messageBox = new MessageBox(); messageBox.setSubject(msg.getSubject()); messageBox.setCode(idHeaders[0]); Address[] fromAddresses = msg.getFrom(); String from = InternetAddress.toString(fromAddresses); if (from.startsWith("=?")) { from = MimeUtility.decodeWord(from); } messageBox.setFrom(from); String to = InternetAddress.toString(msg.getRecipients(RecipientType.TO)); if (to.startsWith("=?")) { to = MimeUtility.decodeWord(to); } messageBox.setTo(to); String[] replyHeaders = msg.getHeader("References"); if (replyHeaders != null && replyHeaders.length > 0) { StringTokenizer tokens = new StringTokenizer(replyHeaders[0]); MessageBox parent = repositoryMailBox.getMessageBox(tokens.nextToken()); if (parent != null) parent.addReply(messageBox); } result = parseSubjectAndCreate(messageBox, msg); } } } folderInbox.close(false); store.close(); return result; } catch (NoSuchProviderException ex) { logger.error("No provider for protocol: " + protocol); ex.printStackTrace(); } catch (MessagingException ex) { logger.error("Could not connect to the message store"); ex.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } result.setSingleElement(false); return result; }
From source file:com.liferay.message.boards.internal.pop.MessageListenerImpl.java
protected boolean isAutoReply(Message message) throws MessagingException { String[] autoReply = message.getHeader("X-Autoreply"); if (ArrayUtil.isNotEmpty(autoReply)) { return true; }// w w w . ja v a 2 s .co m String[] autoReplyFrom = message.getHeader("X-Autoreply-From"); if (ArrayUtil.isNotEmpty(autoReplyFrom)) { return true; } String[] mailAutoReply = message.getHeader("X-Mail-Autoreply"); if (ArrayUtil.isNotEmpty(mailAutoReply)) { return true; } return false; }
From source file:it.greenvulcano.gvesb.virtual.smtp.SMTPCallOperationTest.java
/** * Tests email send/* w w w.j a va2 s. c o m*/ * * @throws Exception * if any error occurs */ public final void testSendEmail() throws Exception { Node node = XMLConfig.getNode("GVCore.xml", "//*[@name='SendEmail']"); CallOperation op = new SMTPCallOperation(); op.init(node); GVBuffer gvBuffer = new GVBuffer(TEST_SYSTEM, TEST_SERVICE); gvBuffer.setObject(TEST_MESSAGE); gvBuffer.setProperty("MAIL_SENDER", "SENDER ADDITIONAL INFO"); op.perform(gvBuffer); //assertTrue(server.waitForIncomingEmail(5000, 1)); Message[] messages = server.getReceivedMessages(); assertEquals(1, messages.length); Message email = messages[0]; Multipart mp = (Multipart) email.getContent(); assertEquals("Notifica SendEmail", email.getSubject()); assertEquals(TEST_MESSAGE, GreenMailUtil.getBody(mp.getBodyPart(0))); System.out.println("---------MAIL DUMP: START"); System.out.println("Headers:\n" + GreenMailUtil.getHeaders(email)); System.out.println("---------"); System.out.println("Body:\n" + GreenMailUtil.getBody(email)); System.out.println("---------MAIL DUMP: END"); assertEquals("Notifica SendEmail", email.getHeader("Subject")[0]); assertEquals("1", email.getHeader("X-Priority")[0]); }