List of usage examples for javax.mail Message getFrom
public abstract Address[] getFrom() throws MessagingException;
From source file:org.sourceforge.net.javamail4ews.transport.EwsTransport.java
public void sendMessage(Message pMessage, Address[] addresses, Address[] ccaddresses, Address[] bccaddresses) throws MessagingException { try {// ww w .j a v a 2 s . co m EmailMessage msg = new EmailMessage(getService()); createHeaders(msg, pMessage); createAddresses(msg, pMessage, addresses, ccaddresses, bccaddresses); createSubject(msg, pMessage); createBody(msg, pMessage); sendMessage(msg); } catch (MessagingException e) { throw e; } catch (Exception e) { String message = e.getMessage(); if (message != null && message.contains( "The user account which was used to submit this request does not have the right to send mail" + " on behalf of the specified sending account")) { SMTPSendFailedException ex = new SMTPSendFailedException("send", 551, "Could not send : insufficient right to send on behalf of '" + pMessage.getFrom()[0] + "'", e, null, pMessage.getAllRecipients(), null); // ( // "Could not send : insufficient right to send on behalf of " + pMessage.getFrom()[0], e); throw ex; } else if (message != null) throw new MessagingException(message, e); else throw new MessagingException("no detailed message provided", e); } }
From source file:org.apache.jmeter.protocol.mail.sampler.MailReaderSampler.java
private void appendMessageData(SampleResult child, Message message) throws MessagingException, IOException { StringBuilder cdata = new StringBuilder(); cdata.append("Date: "); // $NON-NLS-1$ cdata.append(message.getSentDate());// TODO - use a different format here? cdata.append(NEW_LINE);/* w w w. j a v a 2s. co m*/ cdata.append("To: "); // $NON-NLS-1$ Address[] recips = message.getAllRecipients(); // may be null for (int j = 0; recips != null && j < recips.length; j++) { cdata.append(recips[j].toString()); if (j < recips.length - 1) { cdata.append("; "); // $NON-NLS-1$ } } cdata.append(NEW_LINE); cdata.append("From: "); // $NON-NLS-1$ Address[] from = message.getFrom(); // may be null for (int j = 0; from != null && j < from.length; j++) { cdata.append(from[j].toString()); if (j < from.length - 1) { cdata.append("; "); // $NON-NLS-1$ } } cdata.append(NEW_LINE); cdata.append("Subject: "); // $NON-NLS-1$ cdata.append(message.getSubject()); cdata.append(NEW_LINE); cdata.append(NEW_LINE); Object content = message.getContent(); if (content instanceof MimeMultipart) { appendMultiPart(child, cdata, (MimeMultipart) content); } else if (content instanceof InputStream) { child.setResponseData(IOUtils.toByteArray((InputStream) content)); } else { cdata.append(content); child.setResponseData(cdata.toString(), child.getDataEncodingNoDefault()); } }
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 {//from www .ja va2s . co m 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:com.ikon.util.MailUtils.java
/** * Convert Mime Message to Mail//from w w w . j av a2 s. com */ public static Mail messageToMail(Message msg) throws MessagingException, IOException { com.ikon.bean.Mail mail = new com.ikon.bean.Mail(); Calendar receivedDate = Calendar.getInstance(); Calendar sentDate = Calendar.getInstance(); // Can be void if (msg.getReceivedDate() != null) { receivedDate.setTime(msg.getReceivedDate()); } // Can be void if (msg.getSentDate() != null) { sentDate.setTime(msg.getSentDate()); } String body = getText(msg); // log.info("getText: "+body); if (body.charAt(0) == 'H') { mail.setMimeType(MimeTypeConfig.MIME_HTML); } else if (body.charAt(0) == 'T') { mail.setMimeType(MimeTypeConfig.MIME_TEXT); } else { mail.setMimeType(MimeTypeConfig.MIME_UNDEFINED); } String content = body.substring(1); // Need to replace 0x00 because PostgreSQL does not accept string containing 0x00 content = FormatUtil.fixUTF8(content); // Need to remove Unicode surrogate because of MySQL => SQL Error: 1366, SQLState: HY000 content = FormatUtil.trimUnicodeSurrogates(content); mail.setContent(content); if (msg.getFrom().length > 0) { mail.setFrom(MimeUtility.decodeText(msg.getFrom()[0].toString())); } mail.setSize(msg.getSize()); mail.setSubject((msg.getSubject() == null || msg.getSubject().isEmpty()) ? NO_SUBJECT : msg.getSubject()); mail.setTo(addressToString(msg.getRecipients(Message.RecipientType.TO))); mail.setCc(addressToString(msg.getRecipients(Message.RecipientType.CC))); mail.setBcc(addressToString(msg.getRecipients(Message.RecipientType.BCC))); mail.setReceivedDate(receivedDate); mail.setSentDate(sentDate); return mail; }
From source file:de.saly.elasticsearch.support.IndexableMailMessage.java
public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent, final boolean withAttachments, final boolean stripTags, List<String> headersToFields) throws MessagingException, IOException { final IndexableMailMessage im = new IndexableMailMessage(); @SuppressWarnings("unchecked") final Enumeration<Header> allHeaders = jmm.getAllHeaders(); final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>(); while (allHeaders.hasMoreElements()) { final Header h = allHeaders.nextElement(); headerList.add(new IndexableHeader(h.getName(), h.getValue())); }// w ww.j a va 2s . c om im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()])); im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields)); if (jmm.getFolder() instanceof POP3Folder) { im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm)); im.setMailboxType("POP"); } else { im.setMailboxType("IMAP"); } if (jmm.getFolder() instanceof UIDFolder) { im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm)); } im.setFolderFullName(jmm.getFolder().getFullName()); im.setFolderUri(jmm.getFolder().getURLName().toString()); im.setContentType(jmm.getContentType()); im.setSubject(jmm.getSubject()); im.setSize(jmm.getSize()); im.setSentDate(jmm.getSentDate()); if (jmm.getReceivedDate() != null) { im.setReceivedDate(jmm.getReceivedDate()); } if (jmm.getFrom() != null && jmm.getFrom().length > 0) { im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0])); } if (jmm.getRecipients(RecipientType.TO) != null) { im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO))); } if (jmm.getRecipients(RecipientType.CC) != null) { im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC))); } if (jmm.getRecipients(RecipientType.BCC) != null) { im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC))); } if (withTextContent) { // try { String textContent = getText(jmm, 0); if (stripTags) { textContent = stripTags(textContent); } im.setTextContent(textContent); // } catch (final Exception e) { // logger.error("Unable to retrieve text content for message {} due to {}", // e, ((MimeMessage) jmm).getMessageID(), e); // } } if (withAttachments) { try { final Object content = jmm.getContent(); // look for attachments if (jmm.isMimeType("multipart/*") && content instanceof Multipart) { List<ESAttachment> attachments = new ArrayList<ESAttachment>(); final Multipart multipart = (Multipart) content; for (int i = 0; i < multipart.getCount(); i++) { final BodyPart bodyPart = multipart.getBodyPart(i); if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && !StringUtils.isNotBlank(bodyPart.getFileName())) { continue; // dealing with attachments only } final InputStream is = bodyPart.getInputStream(); final byte[] bytes = IOUtils.toByteArray(is); IOUtils.closeQuietly(is); attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName())); } if (!attachments.isEmpty()) { im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()])); im.setAttachmentCount(im.getAttachments().length); attachments.clear(); attachments = null; } } } catch (final Exception e) { logger.error( "Error indexing attachments (message will be indexed but without attachments) due to {}", e, e.toString()); } } im.setFlags(IMAPUtils.toStringArray(jmm.getFlags())); im.setFlaghashcode(jmm.getFlags().hashCode()); return im; }
From source file:de.saly.elasticsearch.importer.imap.support.IndexableMailMessage.java
public static IndexableMailMessage fromJavaMailMessage(final Message jmm, final boolean withTextContent, final boolean withHtmlContent, final boolean preferHtmlContent, final boolean withAttachments, final boolean stripTags, List<String> headersToFields) throws MessagingException, IOException { final IndexableMailMessage im = new IndexableMailMessage(); @SuppressWarnings("unchecked") final Enumeration<Header> allHeaders = jmm.getAllHeaders(); final Set<IndexableHeader> headerList = new HashSet<IndexableHeader>(); while (allHeaders.hasMoreElements()) { final Header h = allHeaders.nextElement(); headerList.add(new IndexableHeader(h.getName(), h.getValue())); }/* w w w . j av a2 s . c o m*/ im.setHeaders(headerList.toArray(new IndexableHeader[headerList.size()])); im.setSelectedHeaders(extractHeaders(im.getHeaders(), headersToFields)); if (jmm.getFolder() instanceof POP3Folder) { im.setPopId(((POP3Folder) jmm.getFolder()).getUID(jmm)); im.setMailboxType("POP"); } else { im.setMailboxType("IMAP"); } if (jmm.getFolder() instanceof UIDFolder) { im.setUid(((UIDFolder) jmm.getFolder()).getUID(jmm)); } im.setFolderFullName(jmm.getFolder().getFullName()); im.setFolderUri(jmm.getFolder().getURLName().toString()); im.setContentType(jmm.getContentType()); im.setSubject(jmm.getSubject()); im.setSize(jmm.getSize()); im.setSentDate(jmm.getSentDate()); if (jmm.getReceivedDate() != null) { im.setReceivedDate(jmm.getReceivedDate()); } if (jmm.getFrom() != null && jmm.getFrom().length > 0) { im.setFrom(Address.fromJavaMailAddress(jmm.getFrom()[0])); } if (jmm.getRecipients(RecipientType.TO) != null) { im.setTo(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.TO))); } if (jmm.getRecipients(RecipientType.CC) != null) { im.setCc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.CC))); } if (jmm.getRecipients(RecipientType.BCC) != null) { im.setBcc(Address.fromJavaMailAddress(jmm.getRecipients(RecipientType.BCC))); } if (withTextContent) { // try { String textContent = getText(jmm, 0, preferHtmlContent); if (stripTags) { textContent = stripTags(textContent); } im.setTextContent(textContent); // } catch (final Exception e) { // logger.error("Unable to retrieve text content for message {} due to {}", // e, ((MimeMessage) jmm).getMessageID(), e); // } } if (withHtmlContent) { // try { String htmlContent = getText(jmm, 0, true); im.setHtmlContent(htmlContent); // } catch (final Exception e) { // logger.error("Unable to retrieve text content for message {} due to {}", // e, ((MimeMessage) jmm).getMessageID(), e); // } } if (withAttachments) { try { final Object content = jmm.getContent(); // look for attachments if (jmm.isMimeType("multipart/*") && content instanceof Multipart) { List<ESAttachment> attachments = new ArrayList<ESAttachment>(); final Multipart multipart = (Multipart) content; for (int i = 0; i < multipart.getCount(); i++) { final BodyPart bodyPart = multipart.getBodyPart(i); if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()) && !StringUtils.isNotBlank(bodyPart.getFileName())) { continue; // dealing with attachments only } final InputStream is = bodyPart.getInputStream(); final byte[] bytes = IOUtils.toByteArray(is); IOUtils.closeQuietly(is); attachments.add(new ESAttachment(bodyPart.getContentType(), bytes, bodyPart.getFileName())); } if (!attachments.isEmpty()) { im.setAttachments(attachments.toArray(new ESAttachment[attachments.size()])); im.setAttachmentCount(im.getAttachments().length); attachments.clear(); attachments = null; } } } catch (final Exception e) { logger.error( "Error indexing attachments (message will be indexed but without attachments) due to {}", e, e.toString()); } } im.setFlags(IMAPUtils.toStringArray(jmm.getFlags())); im.setFlaghashcode(jmm.getFlags().hashCode()); return im; }
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 {//w ww . 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.exist.xquery.modules.mail.MessageListFunctions.java
private Sequence getMessageListAsXML(Sequence[] args, Sequence contextSequence) throws XPathException { Message[] msgList;//w w w .j ava 2 s. c om Sequence ret = Sequence.EMPTY_SEQUENCE; // was a msgList handle specified? if (args[0].isEmpty()) { throw (new XPathException(this, "Message List handle not specified")); } // get the MessageList long msgListHandle = ((IntegerValue) args[0].itemAt(0)).getLong(); msgList = MailModule.retrieveMessageList(context, msgListHandle); if (msgList == null) { throw (new XPathException(this, "Invalid Message List handle specified")); } if (msgList.length > 0) { boolean includeHeaders = args[1].effectiveBooleanValue(); MemTreeBuilder builder = context.getDocumentBuilder(); builder.startDocument(); builder.startElement(new QName("messages", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("count", null, null), String.valueOf(msgList.length)); try { for (int i = 0; i < msgList.length; i++) { Message message = msgList[i]; builder.startElement(new QName("message", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("number", null, null), String.valueOf(message.getMessageNumber())); // Sent Date if (message.getSentDate() != null) { builder.startElement(new QName("sent", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.characters(formatDate(message.getSentDate())); builder.endElement(); } // Received Date if (message.getReceivedDate() != null) { builder.startElement(new QName("received", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.characters(formatDate(message.getReceivedDate())); builder.endElement(); } // From if (message.getFrom() != null) { builder.startElement(new QName("from", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.characters(message.getFrom()[0].toString()); builder.endElement(); } // Recipients builder.startElement(new QName("recipients", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); // To Recipients Address[] toAddresses = message.getRecipients(Message.RecipientType.TO); if (toAddresses != null) { for (Address to : toAddresses) { builder.startElement( new QName("recipient", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("type", null, null), "to"); builder.characters(to.toString()); builder.endElement(); } } // cc Recipients Address[] ccAddresses = message.getRecipients(Message.RecipientType.CC); if (ccAddresses != null) { for (Address ccAddress : ccAddresses) { builder.startElement( new QName("recipient", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("type", null, null), "cc"); builder.characters(ccAddress.toString()); builder.endElement(); } } // bcc Recipients Address[] bccAddresses = message.getRecipients(Message.RecipientType.BCC); if (bccAddresses != null) { for (Address bccAddress : bccAddresses) { builder.startElement( new QName("recipient", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("type", null, null), "bcc"); builder.characters(bccAddress.toString()); builder.endElement(); } } builder.endElement(); // Flags Flags flags = message.getFlags(); Flags.Flag[] systemFlags = flags.getSystemFlags(); String[] userFlags = flags.getUserFlags(); if (systemFlags.length > 0 || userFlags.length > 0) { builder.startElement(new QName("flags", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); for (Flags.Flag systemFlag : systemFlags) { if (systemFlag == Flags.Flag.ANSWERED) { builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("type", null, null), "answered"); builder.endElement(); } else if (systemFlag == Flags.Flag.DELETED) { builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("type", null, null), "deleted"); builder.endElement(); } else if (systemFlag == Flags.Flag.DRAFT) { builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("type", null, null), "draft"); builder.endElement(); } else if (systemFlag == Flags.Flag.FLAGGED) { builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("type", null, null), "flagged"); builder.endElement(); } else if (systemFlag == Flags.Flag.RECENT) { builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("type", null, null), "recent"); builder.endElement(); } else if (systemFlag == Flags.Flag.SEEN) { builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("type", null, null), "seen"); builder.endElement(); } } for (String userFlag : userFlags) { builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("type", null, null), "user"); builder.addAttribute(new QName("value", null, null), userFlag); builder.endElement(); } builder.endElement(); } // Headers if (includeHeaders) { Enumeration headers = message.getAllHeaders(); if (headers.hasMoreElements()) { builder.startElement(new QName("headers", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); while (headers.hasMoreElements()) { Header header = (Header) headers.nextElement(); builder.startElement( new QName("header", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.addAttribute(new QName("name", null, null), header.getName()); builder.addAttribute(new QName("value", null, null), header.getValue()); builder.endElement(); } builder.endElement(); } } // Subject builder.startElement(new QName("subject", MailModule.NAMESPACE_URI, MailModule.PREFIX), null); builder.characters(message.getSubject()); builder.endElement(); builder.endElement(); } } catch (MessagingException me) { throw (new XPathException(this, "Failed to retrieve messages from list", me)); } builder.endElement(); ret = (NodeValue) builder.getDocument().getDocumentElement(); } return (ret); }
From source file:net.fenyo.mail4hotspot.service.AdvancedServicesImpl.java
private void _processMails(final String username, final boolean headerOnly) { Long session_id = null;/*ww w . j av a 2s . c o m*/ boolean should_remove_user_id_processing = false; final GeneralServices.UserAndAccounts userAndAccounts = generalServices.getUserAndAccounts(username); if (!validAccount(userAndAccounts.accounts)) { log.warn("invalid number of accounts"); return; } try { synchronized (userIdsProcessing) { if (userIdsProcessing.contains(userAndAccounts.user.getId())) { // log.warn("account is currently processed"); return; } else { should_remove_user_id_processing = true; userIdsProcessing.add(userAndAccounts.user.getId()); } } final Account account = userAndAccounts.accounts.iterator().next(); // on supprime les mails qui sont plus vieux que la marque et rcuprs il y a plus d'un certain temps // s'il n'y a pas de marque, on ne supprime rien generalServices.removeOldMessages(account); final List<String> msgids = generalServices.getMsgIds(account); final List<String> msgids_older_than_mark = generalServices.getMessageIdsOlderThanMark(account); // final String message_id_mark = generalServices.getMessageIdMark(account); // if (message_id_mark != null) { // // trouver comment se servir de "assert(msgids.contains(message_id_mark));" // if (msgids.contains(message_id_mark) == false) { // log.error("assertion failed"); // System.exit(1); // } // } final MailManager manager = new MailManager(); try { manager.connectToProvider(account.getProvider(), account.getUsername(), account.getPassword()); if (manager.getMessages() == null) log.error("manager.getMessages() == null"); else { final Message[] messages = manager.getMessages(); boolean marked = false; String first_message_id = null; for (int msg_idx = messages.length - 1; (msg_idx >= 0) && (messages.length - msg_idx <= MAX_MAILS_PER_SESSION); msg_idx--) { final Message message = messages[msg_idx]; final String[] msgidHeaders = message.getHeader("Message-Id"); if (msgidHeaders == null || msgidHeaders.length == 0) log.warn("ignoring message without Message-Id"); else { if (first_message_id == null) first_message_id = msgidHeaders[0]; if (!msgids.contains(msgidHeaders[0])) { // this is a new mail final InboxMail inboxMail = new InboxMail(); inboxMail.setUnread(true); inboxMail.setHeaderOnly(headerOnly); // Message-Id inboxMail.setMessageId( GenericTools.truncate(msgidHeaders[0], InboxMail.MAX_MESG_ID_LENGTH)); // From final Address[] from_addr = message.getFrom(); if (from_addr != null) { final StringBuffer from_addresses = new StringBuffer(); for (int i = 0; i < from_addr.length; i++) { if (i > 0) from_addresses.append("; "); from_addresses.append(from_addr[0].toString()); } inboxMail.setFromAddr(GenericTools.truncate(from_addr[0].toString(), InboxMail.MAX_ADDRESS_LENGTH)); } // To final Address[] to_addr = message.getRecipients(RecipientType.TO); if (to_addr != null) { final StringBuffer to_addresses = new StringBuffer(); for (int i = 0; i < to_addr.length; i++) { if (i > 0) to_addresses.append("; "); to_addresses.append(to_addr[0].toString()); } inboxMail.setToAddr(GenericTools.truncate(to_addr[0].toString(), InboxMail.MAX_ADDRESS_LENGTH)); } // Cc final Address[] cc_addr = message.getRecipients(RecipientType.CC); if (cc_addr != null) { final StringBuffer cc_addresses = new StringBuffer(); for (int i = 0; i < cc_addr.length; i++) { if (i > 0) cc_addresses.append("; "); cc_addresses.append(cc_addr[0].toString()); } inboxMail.setCcAddr(GenericTools.truncate(cc_addr[0].toString(), InboxMail.MAX_ADDRESS_LENGTH)); } // Subject if (message.getSubject() != null) inboxMail.setSubject(GenericTools.truncate(message.getSubject(), InboxMail.MAX_SUBJECT_LENGTH)); // Dates inboxMail.setSentDate(message.getSentDate()); inboxMail.setReceivedDate(new java.util.Date()); if (!headerOnly) { // Content try { inboxMail.setContent( GenericTools.truncate(manager.getMessageContentString(message), InboxMail.MAX_CONTENT_LENGTH)); } catch (final IOException ex) { ex.printStackTrace(); } catch (final MessagingException ex) { ex.printStackTrace(); } } // persists entity if (headerOnly) { // header only == objectif : ce qui est dj dans la bote mail du provider ne sera jamais rcupr // le plus rcent mail (on commence par les plus rcents et on marque le 1er), qu'on n'a pas dj vu (car on ne passe ici que pour les mails pas dj vus), est marqu if (!marked) { session_id = generalServices.saveInboxMailMark(account, inboxMail, session_id); marked = true; } else session_id = generalServices.saveInboxMail(account, inboxMail, session_id); } else { session_id = generalServices.saveInboxMail(account, inboxMail, session_id); } } else { // on a dj ce message-id if (headerOnly) { // header only == objectif : ce qui est dj dans la bote mail du provider ne sera jamais rcupr // le plus rcent mail (on commence par les plus rcents et on marque le 1er), qu'on n'a pas dj vu (car on ne passe ici que pour les mails pas dj vus), est marqu if (!marked) { generalServices.saveMark(account, msgidHeaders[0]); marked = true; } } else { // pas en mode header only => on vrifie si on a rencontr la marque // if (msgidHeaders[0].equals(message_id_mark)) { // marque rencontre => on arrte // break; // } // log.debug("msgids_older_than_mark size:" + msgids_older_than_mark.size()); if (msgids_older_than_mark != null && msgids_older_than_mark.contains(msgidHeaders[0])) { // marque rencontre => on arrte break; } } } } } // aprs la boucle sur les messages (donc soit sortie du break car rencontre de la marque, soit boucle termine) // on met donc jour la marque avec le 1er message (le plus rcent rcupr) if (!headerOnly && first_message_id != null) generalServices.saveMark(account, first_message_id); } } catch (final AuthenticationFailedException ex) { log.info("TRACE: authentication failure;" + username + ";" + ex.toString() + ";"); generalServices.saveProviderError(account, ex.toString()); } catch (final MessagingException ex) { ex.printStackTrace(); } finally { try { manager.disconnect(); } catch (final MessagingException ex) { ex.printStackTrace(); } } } finally { synchronized (userIdsProcessing) { if (should_remove_user_id_processing && userIdsProcessing.contains(userAndAccounts.user.getId())) userIdsProcessing.remove(userAndAccounts.user.getId()); } } }
From source file:org.campware.cream.modules.scheduledjobs.Pop3Job.java
private void doReceiveMessages() throws Exception { log.debug("Checking mail "); String host = Turbine.getConfiguration().getString("mail.pop3.host"); String username = Turbine.getConfiguration().getString("mail.pop3.user"); String password = Turbine.getConfiguration().getString("mail.pop3.password"); // Create empty properties Properties props = new Properties(); // Get session Session session = Session.getDefaultInstance(props, null); // Get the store Store store = session.getStore("pop3"); // Connect to store store.connect(host, username, password); // Get folder Folder folder = store.getFolder("INBOX"); // Open read-only folder.open(Folder.READ_WRITE);// ww w. ja v a 2s .c o m // Get attributes & flags for all messages // Message[] messages = folder.getMessages(); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.ENVELOPE); fp.add(FetchProfile.Item.FLAGS); fp.add("X-Mailer"); folder.fetch(messages, fp); for (int i = 0; i < messages.length; i++) { log.debug("Retrieving message " + i); // Process each message // InboxEvent entry = new InboxEvent(); Address fromAddress = new InternetAddress(); String from = new String(); String name = new String(); String email = new String(); String replyTo = new String(); String subject = new String(); String content = new String(); Date sentDate = new Date(); int emailformat = 10; Message m = messages[i]; // and now, handle the content Object o = m.getContent(); // find content type if (m.isMimeType("text/plain")) { content = "<PRE style=\"font-size: 12px;\">" + (String) o + "</PRE>"; emailformat = 10; } else if (m.isMimeType("text/html")) { content = (String) o; emailformat = 20; } else if (m.isMimeType("text/*")) { content = (String) o; emailformat = 30; } else if (m.isMimeType("multipart/alternative")) { try { content = handleAlternative(o, content); emailformat = 20; } catch (Exception ex) { content = "Problem with the message format. Messssage has left on the email server."; emailformat = 50; log.error(ex.getMessage(), ex); } } else if (m.isMimeType("multipart/*")) { try { content = handleMulitipart(o, content, entry); emailformat = 40; } catch (Exception ex) { content = "Problem with the message format. Messssage has left on the email server."; emailformat = 50; log.error(ex.getMessage(), ex); } } else { content = "Problem with the message format. Messssage has left on the email server."; emailformat = 50; log.debug("Could not handle properly"); } email = ((InternetAddress) m.getFrom()[0]).getAddress(); name = ((InternetAddress) m.getFrom()[0]).getPersonal(); replyTo = ((InternetAddress) m.getReplyTo()[0]).getAddress(); sentDate = m.getSentDate(); subject = m.getSubject(); log.debug("Got message " + email + " " + name + " " + subject + " " + content); Criteria contcrit = new Criteria(); contcrit.add(ContactPeer.EMAIL, (Object) email, Criteria.EQUAL); if (ContactPeer.doSelect(contcrit).size() > 0) { log.debug("From known contact"); Contact myContact = (Contact) ContactPeer.doSelect(contcrit).get(0); entry.setCustomerId(myContact.getCustomerId()); entry.setContactId(myContact.getContactId()); } else { // find if customer exists Criteria criteria = new Criteria(); criteria.add(CustomerPeer.EMAIL, (Object) email, Criteria.EQUAL); if (CustomerPeer.doSelect(criteria).size() > 0) { log.debug("From known customer"); Customer myDistrib = (Customer) CustomerPeer.doSelect(criteria).get(0); entry.setCustomerId(myDistrib.getCustomerId()); } } entry.setInboxEventCode(getTempCode()); entry.setEventType(10); entry.setEventChannel(10); entry.setEmailFormat(emailformat); entry.setSubject(subject); entry.setSenderEmail(email); entry.setSenderName(name); entry.setSenderReplyTo(replyTo); entry.setSentTime(sentDate); entry.setBody(content); entry.setIssuedDate(new Date()); entry.setCreatedBy("system"); entry.setCreated(new Date()); entry.setModifiedBy("system"); entry.setModified(new Date()); Connection conn = Transaction.begin(InboxEventPeer.DATABASE_NAME); boolean success = false; try { entry.save(conn); entry.setInboxEventCode(getRowCode("IE", entry.getInboxEventId())); entry.save(conn); Transaction.commit(conn); success = true; } finally { log.debug("Succcessfully stored in db: " + success); if (!success) Transaction.safeRollback(conn); } if (emailformat != 50) { m.setFlag(Flags.Flag.DELETED, true); } } // Close pop3 connection folder.close(true); store.close(); }