public CustomProperties getMessageProperties(Message message, String prefix, CustomProperties p) throws MessagingException, IOException { CustomProperties envVars = new CustomProperties(); String msgSubject = stringify(message.getSubject()); envVars.put(prefix + "subject", msgSubject); envVars.put(prefix + "from", stringify(message.getFrom())); envVars.put(prefix + "replyTo", stringify(message.getReplyTo())); envVars.put(prefix + "flags", stringify(message.getFlags())); envVars.put(prefix + "folder", stringify(message.getFolder())); envVars.put(prefix + "messageNumber", stringify(message.getMessageNumber())); envVars.put(prefix + "receivedDate", stringify(message.getReceivedDate())); envVars.put(prefix + "sentDate", stringify(message.getSentDate())); envVars.put(prefix + "headers", stringify(message.getAllHeaders())); envVars.put(prefix + "content", stringify(message)); envVars.put(prefix + "contentType", stringify(message.getContentType())); envVars.put(prefix + "recipients", stringify(message.getAllRecipients())); // add parameters from email content final CustomProperties properties = CustomProperties.read(getText(message)); envVars.putAll(properties); // envVars.put(prefix + "emailParams", stringify(properties.getMap(), "=", "&")); // add "jobTrigger" if (p.has(subjectContains)) { String subject = p.get(subjectContains); // normalise strings, find index, then get text after it int idx = msgSubject.toLowerCase().indexOf(subject.toLowerCase()); int beginIndex = idx + subject.length(); if (idx > -1 && beginIndex < msgSubject.length()) { envVars.put(prefix + "jobTrigger", msgSubject.substring(beginIndex).trim()); } } return envVars; }
public static void main(String[] args) throws MessagingException, IOException { IMAPFolder folder = null; Store store = null; String subject = null; Flag flag = null; try { Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); props.setProperty("mail.imap.host", "imap.googlemail.com"); SimpleAuthenticator authenticator = new SimpleAuthenticator("*****@*****.**", "hhy8611hhyy"); Session session = Session.getDefaultInstance(props, null); // Session session = Session.getDefaultInstance(props, authenticator); store = session.getStore("imaps"); // store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy"); // store.connect("imap.googlemail.com","*****@*****.**", "hhy8611hhyy"); store.connect("*****@*****.**", "hhy8611hhy"); // folder = (IMAPFolder) store.getFolder("[Gmail]/Spam"); // This doesn't work for other email // account folder = (IMAPFolder) store.getFolder("inbox"); // This works for both email account if (!folder.isOpen()) folder.open(Folder.READ_WRITE); Message[] messages = messages = folder.getMessages(150, 150); // folder.getMessages(); System.out.println("No of get Messages : " + messages.length); System.out.println("No of Messages : " + folder.getMessageCount()); System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount()); System.out.println("No of New Messages : " + folder.getNewMessageCount()); System.out.println(messages.length); for (int i = 0; i < messages.length; i++) { System.out.println( "*****************************************************************************"); System.out.println("MESSAGE " + (i + 1) + ":"); Message msg = messages[i]; // System.out.println(msg.getMessageNumber()); // Object String; // System.out.println(folder.getUID(msg) subject = msg.getSubject(); System.out.println("Subject: " + subject); System.out.println("From: " + msg.getFrom()[0]); System.out.println("To: " + msg.getAllRecipients()[0]); System.out.println("Date: " + msg.getReceivedDate()); System.out.println("Size: " + msg.getSize()); System.out.println(msg.getFlags()); System.out.println("Body: \n" + msg.getContent()); System.out.println(msg.getContentType()); } } finally { if (folder != null && folder.isOpen()) { folder.close(true); } if (store != null) { store.close(); } } }
/** * metoda preuzmiPoruke preuzima poruke iz odabrane mape i puni listu poruka * * @throws MessagingException * @throws IOException */ private void preuzmiPoruke() throws MessagingException, IOException { Message[] messages; // Open the INBOX folder folder = store.getFolder(this.odabranaMapa); folder.open(Folder.READ_ONLY); messages = folder.getMessages(); this.poruke = new ArrayList<Poruka>(); for (int i = 0; i < messages.length; ++i) { Message m = messages[i]; Poruka p = new Poruka( m.getHeader("Message-ID")[0], m.getSentDate(), m.getFrom()[0].toString(), m.getSubject(), m.getContentType(), m.getSize(), 0, m.getFlags(), null, true, true, m.getContent().toString()); // TODO potraziti broj privitaka, sad je hardkodirano da ih je 0 this.poruke.add(p); } }
/** {@inheritDoc}. */ public String getContentType() { try { return myMessage.getContentType(); } catch (MessagingException e) { LOG.log(Level.SEVERE, "Exception while getting content-type", e); return "text/plain"; } }
/** * Method getContentType returns string/mime representation of the message type. * * @return String * @throws SieveMailException */ public String getContentType() throws SieveMailException { String result = null; if (mail != null) { try { result = mail.getContentType(); } catch (MessagingException e) { throw new SieveMailException(e); } } return result; }
/** * Retrieve message from retriever and check the body content * * @param retriever Retriever to read from * @param to Account to retrieve */ private void retrieveAndCheckBody(Retriever retriever, String to) throws MessagingException, IOException { Message[] messages = retriever.getMessages(to); assertEquals(1, messages.length); Message message = messages[0]; assertTrue(message.getContentType().equalsIgnoreCase("application/blubb")); // Check content InputStream contentStream = (InputStream) message.getContent(); byte[] bytes = IOUtils.toByteArray(contentStream); assertArrayEquals(createLargeByteArray(), bytes); // Dump complete mail message. This leads to a FETCH command without section or "len" specified. message.writeTo(new ByteArrayOutputStream()); }
/** * Get message header for MailMessage. * * @param msg * @param mailMsg * @throws MessagingException */ protected void processHeader(Message msg, MailMessage mailMsg) throws MessagingException { String xAutoResponseSuppressHeaderName = "X-Auto-Response-Suppress"; String xAutoReplyHeaderName = "X-Autoreply"; String xAutoRespondHeaderName = "X-Autorespond"; String xAutoSubmittedHeaderName = "auto-submitted"; String xAutoResponseSuppressVal = Arrays.toString(msg.getHeader(xAutoResponseSuppressHeaderName)); String xAutoReplyVal = Arrays.toString(msg.getHeader(xAutoReplyHeaderName)); String xAutoRespondVal = Arrays.toString(msg.getHeader(xAutoRespondHeaderName)); String xAutoSubmittedVal = Arrays.toString(msg.getHeader(xAutoSubmittedHeaderName)); String contentType = msg.getContentType(); // If any of those are present in an email, then that email is an auto-reply. String[] autoReplyArray = { xAutoResponseSuppressVal, xAutoReplyVal, xAutoRespondVal, xAutoSubmittedVal }; mailMsg.setAutoReply(autoReplyArray); mailMsg.setContentType(contentType); }
/** * Retrieve message from retriever and check the attachment and text content * * @param retriever Retriever to read from * @param to Account to retrieve */ private void retrieveAndCheck(Retriever retriever, String to) throws MessagingException, IOException { Message[] messages = retriever.getMessages(to); assertEquals(1, messages.length); Message message = messages[0]; assertTrue(message.getContentType().startsWith("multipart/mixed")); MimeMultipart body = (MimeMultipart) message.getContent(); assertTrue(body.getContentType().startsWith("multipart/mixed")); assertEquals(2, body.getCount()); // Message text final BodyPart textPart = body.getBodyPart(0); String text = (String) textPart.getContent(); assertEquals(createLargeString(), text); final BodyPart attachment = body.getBodyPart(1); assertTrue(attachment.getContentType().equalsIgnoreCase("application/blubb; name=file")); InputStream attachmentStream = (InputStream) attachment.getContent(); byte[] bytes = IOUtils.toByteArray(attachmentStream); assertArrayEquals(createLargeByteArray(), bytes); }
private static Renderable getMessage(Message message) { if (message == null) { return null; } try { if (message.getContentType().startsWith("text/plain")) { return new RenderablePlainText(message); } else { return new RenderableMessage(message); } // printMsg(latestMessage); } catch (MessagingException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } return null; }
private void mailReceiver(Message msg) throws Exception { // 发件人信息 Address[] froms = msg.getFrom(); if (froms != null) { // System.out.println("发件人信息:" + froms[0]); InternetAddress addr = (InternetAddress) froms[0]; System.out.println("发件人地址:" + addr.getAddress()); System.out.println("发件人显示名:" + addr.getPersonal()); } System.out.println("邮件主题:" + msg.getSubject()); // getContent() 是获取包裹内容, Part相当于外包装 Object o = msg.getContent(); if (o instanceof Multipart) { Multipart multipart = (Multipart) o; reMultipart(multipart); } else if (o instanceof Part) { Part part = (Part) o; rePart(part); } else { System.out.println("类型" + msg.getContentType()); System.out.println("内容" + msg.getContent()); } }
/** * Sends mail. * * @return */ public int send() { int status = 0; String messageBody = null; Properties props = null; Session session = null; Message message = null; Authenticator auth = null; Transport transport = null; if (smtpServerHost == null || "".equalsIgnoreCase(smtpServerHost)) { CyberoamLogger.sysLog.debug( "mail send is stopped because smtpserverhost in tbliviewconfig is not exist."); return -1; } try { CyberoamLogger.sysLog.debug("Getting System Properties ....."); props = System.getProperties(); CyberoamLogger.sysLog.debug("Setting SMTP Mail Host and SMTP Mail Port ....."); props.put(MAILSMTPHOST, smtpServerHost); props.put(MAILSMTPPORT, smtpServerPort); props.put(MAILDEBUG, VALUEFALSE); props.put(MAILSMTPAUTH, VALUEFALSE); CyberoamLogger.sysLog.debug( "SMTP Mail Host :: SMTP Mail Port - " + smtpServerHost + " :: " + smtpServerPort); if ("1".equals(smtpAuthFlag)) { props.put(MAILSMTPAUTH, VALUETRUE); props.put(MAILSMTPUSER, smtpUsername); auth = new SMTPAuthenticator(); } CyberoamLogger.sysLog.debug("Getting session for mail sending ....."); // if auth is null then session without authentication will be created. session = Session.getInstance(props, auth); CyberoamLogger.sysLog.debug("Initializing mail contents ....."); messageBody = mailContentFile; CyberoamLogger.sysLog.debug("Preparing a message body ....."); message = new MimeMessage(session); message.setHeader("X-Mailer", "Cyberoam Mail Client"); message.setHeader("Content-Type", "text/html; charset=UTF-8"); if (smtpDisplayName == null || "".equalsIgnoreCase(smtpDisplayName)) message.setFrom(new InternetAddress(smtpFromAddr)); else message.setFrom(new InternetAddress(smtpFromAddr, smtpDisplayName)); CyberoamLogger.sysLog.debug("Mail will be sent to: " + smtpToAddr); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(smtpToAddr, false)); InternetAddress replyAddress[] = new InternetAddress[1]; replyAddress[0] = new InternetAddress("*****@*****.**"); message.setReplyTo(replyAddress); message.setSentDate(new Date()); message.setSubject(mailSubject); message.setText(messageBody); message.setContent(messageBody, "text/html"); message.saveChanges(); CyberoamLogger.sysLog.debug("Message Content Type: " + message.getContentType()); CyberoamLogger.sysLog.debug("Mail is ready to send ....."); CyberoamLogger.sysLog.debug("Getting SMTP Transport Object for mail sending ....."); transport = session.getTransport("smtp"); if ("1".equals(smtpAuthFlag)) { CyberoamLogger.sysLog.debug("Connecting to SMTP MailServer Host with Authentication ....."); transport.connect(smtpServerHost, smtpUsername, smtpPassword); CyberoamLogger.sysLog.debug("Sending Mail ....."); transport.sendMessage(message, message.getAllRecipients()); } else { CyberoamLogger.sysLog.debug( "Connecting to SMTP MailServer Host without Authentication ....."); transport.connect(); CyberoamLogger.sysLog.debug("Sending Mail ....."); transport.sendMessage(message, message.getAllRecipients()); } transport.close(); CyberoamLogger.sysLog.debug("Mail sent OK."); AuditLog.mail.info("Mail with subject :\"" + mailSubject + "\" sent to " + smtpToAddr, null); } catch (MessagingException mex) { status = -1; AuditLog.mail.error("Mail sending failed : " + mex.getMessage(), null); CyberoamLogger.sysLog.debug("MailSender.sendWithAttachment.messageexception:" + mex, mex); } catch (Exception e) { status = -1; AuditLog.mail.error("Mail sending failed : " + e.getMessage(), null); CyberoamLogger.sysLog.debug("MailSender.sendWithAttachment.exception:" + e, e); } return status; }
/** * Aggregates the e-mail message by reading it and turning it either into a page or a file upload. * * @param message the e-mail message * @param site the site to publish to * @throws MessagingException if fetching the message data fails * @throws IOException if writing the contents to the output stream fails */ protected Page aggregate(Message message, Site site) throws IOException, MessagingException, IllegalArgumentException { ResourceURI uri = new PageURIImpl(site, UUID.randomUUID().toString()); Page page = new PageImpl(uri); Language language = site.getDefaultLanguage(); // Extract title and subject. Without these two, creating a page is not // feasible, therefore both messages throw an IllegalArgumentException if // the fields are not present. String title = getSubject(message); String author = getAuthor(message); // Collect default settings PageTemplate template = site.getDefaultTemplate(); if (template == null) throw new IllegalStateException("Missing default template in site '" + site + "'"); String stage = template.getStage(); if (StringUtils.isBlank(stage)) throw new IllegalStateException( "Missing stage definition in template '" + template.getIdentifier() + "'"); // Standard fields page.setTitle(title, language); page.setTemplate(template.getIdentifier()); page.setPublished(new UserImpl(site.getAdministrator()), message.getReceivedDate(), null); // TODO: Translate e-mail "from" into site user and throw if no such // user can be found page.setCreated(site.getAdministrator(), message.getSentDate()); // Start looking at the message body String contentType = message.getContentType(); if (StringUtils.isBlank(contentType)) throw new IllegalArgumentException("Message content type is unspecified"); // Text body if (contentType.startsWith("text/plain")) { // TODO: Evaluate charset String body = null; if (message.getContent() instanceof String) body = (String) message.getContent(); else if (message.getContent() instanceof InputStream) body = IOUtils.toString((InputStream) message.getContent()); else throw new IllegalArgumentException("Message body is of unknown type"); return handleTextPlain(body, page, language); } // HTML body if (contentType.startsWith("text/html")) { // TODO: Evaluate charset return handleTextHtml((String) message.getContent(), page, null); } // Multipart body else if ("mime/multipart".equalsIgnoreCase(contentType)) { Multipart mp = (Multipart) message.getContent(); for (int i = 0, n = mp.getCount(); i < n; i++) { Part part = mp.getBodyPart(i); String disposition = part.getDisposition(); if (disposition == null) { MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType("text/plain")) { return handleTextPlain((String) mbp.getContent(), page, null); } else { // TODO: Implement special non-attachment cases here of // image/gif, text/html, ... throw new UnsupportedOperationException( "Multipart message bodies of type '" + mbp.getContentType() + "' are not yet supported"); } } else if (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE)) { logger.info("Skipping message attachment " + part.getFileName()); // saveFile(part.getFileName(), part.getInputStream()); } } throw new IllegalArgumentException( "Multipart message did not contain any recognizable content"); } // ? else { throw new IllegalArgumentException("Message body is of unknown type '" + contentType + "'"); } }
/** * Check if the given message is claimed by any of the registred importers and handle it. * * @param message the message to import or to ignore * @param aCurrentAccount the currently selected account in the JGnucashEditor * @param aWritableModel the gnucash-file * @return true if the message has been handled successfully * @throws MessagingException in case of mail- issues * @throws IOException in case of io-issues * @throws JAXBException in case of XML-issues with the plugins */ private boolean importMessage( final Message message, final GnucashWritableAccount aCurrentAccount, final GnucashWritableFile aWritableModel) throws MessagingException, IOException, JAXBException { LOG.fine("========================================="); if (message.isSet(Flag.DELETED)) { return false; } LOG.info("Message: " + message.getSubject()); LOG.info("disposition: " + message.getDisposition()); LOG.info("contentType: " + message.getContentType()); if (message.isSet(Flag.SEEN)) { LOG.info("Flagged: SEEN"); } if (message.isSet(Flag.DRAFT)) { LOG.info("Flagged: DRAFT"); } if (message.isSet(Flag.ANSWERED)) { LOG.info("Flagged: ANSWERED"); } if (message.isSet(Flag.USER)) { LOG.info("Flagged: USER"); } if (message.isSet(Flag.FLAGGED)) { LOG.info("Flagged: FLAGGED"); } if (message.isSet(Flag.RECENT)) { LOG.info("Flagged: RECENT"); } if (message.isSet(Flag.DELETED)) { LOG.info("Flagged: DELETED"); } Flag[] systemFlags = message.getFlags().getSystemFlags(); for (Flag flag : systemFlags) { LOG.info("system-flag: " + flag.toString()); } String[] userFlags = message.getFlags().getUserFlags(); for (String flag : userFlags) { LOG.info("user-flag: " + flag); } Object readTextContent = message.getContent(); Object content = readTextContent; LOG.info("content: " + content.getClass().getName()); // if (message instanceof MimeMessage) { // MimeMessage msg = (MimeMessage) message; // msg.getco // } if (content instanceof InputStream && message.getContentType().toLowerCase().contains("multipart")) { content = new MimeMultipart(new InputStreamDataSource(message)); } if (content instanceof InputStream && message.getContentType().toLowerCase().startsWith("text")) { // call plugins for text/plain -messages too Collection<MailImportHandler> mailHandlers = PluginMain.getMailHandlers(); LOG.fine("handling as text/* via our #" + mailHandlers.size() + " plugins..."); for (MailImportHandler mailImportHandler : mailHandlers) { LOG.fine( "handling as text/* via our #" + mailHandlers.size() + " plugins...trying " + mailImportHandler.getClass().getName()); if (mailImportHandler.handleTextMail( aWritableModel, message.getSubject(), message, readTextContent(message))) { return true; } } } if (content instanceof Multipart) { Multipart mp = (Multipart) content; // call plugins Collection<MailImportHandler> mailHandlers = PluginMain.getMailHandlers(); LOG.fine("handling as multipart via our #" + mailHandlers.size() + " plugins..."); for (MailImportHandler mailImportHandler : mailHandlers) { LOG.fine( "handling as text/* via our #" + mailHandlers.size() + " plugins...trying " + mailImportHandler.getClass().getName()); if (mailImportHandler.handleMultiPartMail( aWritableModel, message.getSubject(), message, mp)) { return true; } } // for (int i = 0; i < mp.getCount(); i++) { // Part part = mp.getBodyPart(i); // String disposition = part.getDisposition(); // if (disposition == null) { // continue; // } // if (disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE)) // { // LOG.info("\tAttachment: " + part.getFileName() + " of type " + // part.getContentType()); // //part.getInputStream() // } // } } return false; }
/** * Receive Email from POPServer. Use POP3 protocal by default. Thus, call this method, you need to * provide a pop3 mail server address. * * @param emailAddress The email account in the POPServer. * @param password The password of email address. */ public static void receiveEmail(String host, String username, String password) { // param check. If param is null, use the default configured value. if (host == null) { host = POP3Server; } if (username == null) { username = POP3Username; } if (password == null) { password = POP3Password; } Properties props = System.getProperties(); // MailAuthenticator authenticator = new MailAuthenticator(username, password); try { Session session = Session.getDefaultInstance(props, null); // Store store = session.getStore("imap"); Store store = session.getStore("pop3"); // Connect POPServer store.connect(host, username, password); Folder inbox = store.getFolder("INBOX"); if (inbox == null) { throw new RuntimeException("No inbox existed."); } // Open the INBOX with READ_ONLY mode and start to read all emails. inbox.open(Folder.READ_ONLY); System.out.println("TOTAL EMAIL:" + inbox.getMessageCount()); Message[] messages = inbox.getMessages(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; String from = InternetAddress.toString(msg.getFrom()); String replyTo = InternetAddress.toString(msg.getReplyTo()); String to = InternetAddress.toString(msg.getRecipients(Message.RecipientType.TO)); String subject = msg.getSubject(); Date sent = msg.getSentDate(); Date ress = msg.getReceivedDate(); String type = msg.getContentType(); System.out.println((i + 1) + ".---------------------------------------------"); System.out.println("From:" + mimeDecodeString(from)); System.out.println("Reply To:" + mimeDecodeString(replyTo)); System.out.println("To:" + mimeDecodeString(to)); System.out.println("Subject:" + mimeDecodeString(subject)); System.out.println("Content-type:" + type); if (sent != null) { System.out.println("Sent Date:" + sdf.format(sent)); } if (ress != null) { System.out.println("Receive Date:" + sdf.format(ress)); } // //Get message headers. // @SuppressWarnings("rawtypes") // Enumeration headers = msg.getAllHeaders(); // while (headers.hasMoreElements()) { // Header h = (Header) headers.nextElement(); // String name = h.getName(); // String val = h.getValue(); // System.out.println(name + ": " + val); // } // //get the email content. // Object content = msg.getContent(); // System.out.println(content); // //print content // Reader reader = new InputStreamReader( // messages[i].getInputStream()); // int a = 0; // while ((a = reader.read()) != -1) { // System.out.print((char) a); // } } // close connection. param false represents do not delete messaegs on server. inbox.close(false); store.close(); // } catch(IOException e) { // LOGGER.error("IOException caught while printing the email content", e); } catch (MessagingException e) { LOGGER.error("MessagingException caught when use message object", e); } }