List of usage examples for javax.mail Message getFrom
public abstract Address[] getFrom() throws MessagingException;
From source file:com.cubusmail.mail.MessageHandler.java
/** * @throws NoSuchMessageException/*from w w w. j a v a 2s . com*/ * @throws MessagingException */ private void addReplyInfo(Message originalMessage) throws NoSuchMessageException, MessagingException { String fromString = MessageUtils.getMailAdressString(originalMessage.getFrom(), AddressStringType.COMPLETE); Locale locale = SessionManager.get().getLocale(); String[] args = new String[] { fromString }; String informationText = this.applicationContext.getMessage("message.reply.information.text.withoutDate", args, locale); if (!StringUtils.isEmpty(this.messageTextPlain)) { this.messageTextPlain = informationText + "\n\n" + this.messageTextPlain; } if (!StringUtils.isEmpty(this.messageTextHtml)) { this.messageTextHtml = "<p>" + informationText + "</p>" + this.messageTextHtml; } }
From source file:com.openkm.util.MailUtils.java
/** * Convert Mime Message to Mail/*from w w w. j av a 2s . c o m*/ */ public static Mail messageToMail(Message msg) throws MessagingException, IOException { com.openkm.bean.Mail mail = new com.openkm.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); } if (msg.getFrom() != null && msg.getFrom().length > 0) { mail.setFrom(addressToString(msg.getFrom()[0])); } mail.setSize(msg.getSize()); mail.setContent(body.substring(1)); 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:org.apache.hupa.server.handler.AbstractSendMessageHandler.java
/** * Send the message using SMTP, if the configuration uses authenticated SMTP, it uses * the user stored in session to get the given login and password. * /* w w w . j ava 2 s.c om*/ * @param user * @param session * @param message * @throws MessagingException */ protected void sendMessage(User user, Message message) throws MessagingException { Transport transport = cache.getMailTransport(useSSL); if (auth) { logger.debug("Use auth for smtp connection"); transport.connect(address, port, user.getName(), user.getPassword()); } else { transport.connect(address, port, null, null); } Address[] recips = message.getAllRecipients(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < recips.length; i++) { sb.append(recips[i]); if (i != recips.length - 1) { sb.append(", "); } } logger.info("Send message from " + message.getFrom()[0].toString() + " to " + sb.toString()); transport.sendMessage(message, recips); }
From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java
private String getEmailAddressFromMessage(Message m) throws MessagingException { Address[] sender = m.getFrom(); String creatorEmail = ""; if (sender.length > 0) { if (sender[0] instanceof InternetAddress) { creatorEmail = ((InternetAddress) sender[0]).getAddress(); } else {/*from www . j av a2s.c o m*/ try { InternetAddress ia[] = InternetAddress.parse(sender[0].toString()); if (ia.length > 0) { creatorEmail = ia[0].getAddress(); } } catch (AddressException ae) { } } } return creatorEmail; }
From source file:com.naryx.tagfusion.cfm.mail.cfPOP3.java
private void populateMessage(cfSession _Session, Message thisMessage, cfQueryResultData popData, boolean GetAll, File attachmentDir, Folder _parent) throws Exception { popData.addRow(1);/*from www . j a va2 s . c o m*/ int Row = popData.getNoRows(); Date date = thisMessage.getSentDate(); if (date != null) { cfDateData cfdate = new cfDateData(date); cfdate.setPOPDate(); popData.setCell(Row, 1, cfdate); } else { popData.setCell(Row, 1, new cfStringData("")); } popData.setCell(Row, 2, new cfStringData(formatAddress(thisMessage.getFrom()))); popData.setCell(Row, 3, new cfNumberData(thisMessage.getMessageNumber())); popData.setCell(Row, 4, new cfStringData(formatAddress(thisMessage.getReplyTo()))); popData.setCell(Row, 5, new cfStringData(thisMessage.getSubject())); popData.setCell(Row, 6, new cfStringData(formatAddress(thisMessage.getRecipients(Message.RecipientType.CC)))); popData.setCell(Row, 7, new cfStringData(formatAddress(thisMessage.getRecipients(Message.RecipientType.TO)))); String[] msgid = thisMessage.getHeader("Message-ID"); popData.setCell(Row, 8, new cfStringData(msgid != null ? msgid[0] : "")); popData.setCell(Row, 9, new cfStringData(getMessageUID(_parent, thisMessage))); popData.setCell(Row, 10, new cfStringData(formatHeader(thisMessage))); if (GetAll) { retrieveBody(_Session, thisMessage, popData, Row, attachmentDir); } }
From source file:com.intranet.intr.inbox.EmpControllerInbox.java
@RequestMapping(value = "/EajaxtestNoL", method = RequestMethod.GET) public @ResponseBody String ajaxtestNoL(Principal principal) { String name = principal.getName(); String result = ""; try {/*from w w w . j av a2s.c om*/ users u = usuarioService.getByLogin(name); Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna()); System.out.println("ola" + store); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_ONLY); FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); Calendar fecha3 = Calendar.getInstance(); fecha3.roll(Calendar.MONTH, false); Message msg[] = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, fecha3.getTime())); //Message msg[] = inbox.search(ft); System.out.println("MAILS: " + msg.length); for (Message message : msg) { try { /*System.out.println("DATE: "+message.getSentDate().toString()); System.out.println("FROM: "+message.getFrom()[0].toString()); System.out.println("SUBJECT: "+message.getSubject().toString()); System.out.println("CONTENT: "+message.getContent().toString()); System.out.println("******************************************"); */result = result + "<li>" + "<a href='#' class='clearfix'>" + "<span class='msg-body'>" + "<span class='msg-title'>" + "<span class='blue'>" + message.getFrom()[0].toString() + "</span>" + message.getSubject().toString() + "</span>" + "</span>" + "</a>" + "</li> "; } catch (Exception e) { // TODO Auto-generated catch block System.out.println("No Information"); } } } catch (Exception ex) { } return result; }
From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java
/** * Retrieve mail messages in a JSON representation * /*www.j a va2 s . c o m*/ * @return */ public JSONArray getJMessages() { JSONArray jMessages = new JSONArray(); if (store == null) return jMessages; try { /* * Connect to IMAP store */ store.connect(); /* * Retrieve & open INBOX folder */ Folder folder = store.getFolder(ImapConstants.INBOX); folder.open(Folder.READ_ONLY); Message[] messages = folder.getMessages(); for (int i = 0; i < messages.length; i++) { Message m = messages[i]; JSONObject jMessage = new JSONObject(); jMessage.put(ImapConstants.J_KEY, ""); // introduced to be compatible with posted emails jMessage.put(ImapConstants.J_ID, i); // message identifier to retrieve from external server jMessage.put(ImapConstants.J_SUBJECT, m.getSubject()); jMessage.put(ImapConstants.J_DATE, m.getSentDate()); String from = ""; Address[] addresses = m.getFrom(); for (Address address : addresses) { InternetAddress internetAddress = (InternetAddress) address; from = internetAddress.getPersonal(); } jMessage.put(ImapConstants.J_FROM, from); FileUtil attachment = getAttachment(m); if (attachment == null) { jMessage.put(ImapConstants.J_ATTACHMENT, false); } else { jMessage.put(ImapConstants.J_ATTACHMENT, true); } jMessages.put(jMessages.length(), jMessage); } folder.close(false); store.close(); } catch (Exception e) { e.printStackTrace(); } finally { } return jMessages; }
From source file:org.apache.nifi.processors.email.ConsumeEWS.java
/** * Disposes the message by converting it to a {@link FlowFile} transferring * it to the REL_SUCCESS relationship.//from w w w. ja v a 2s . c o m */ private void transfer(Message emailMessage, ProcessContext context, ProcessSession processSession) { long start = System.nanoTime(); FlowFile flowFile = processSession.create(); flowFile = processSession.append(flowFile, new OutputStreamCallback() { @Override public void process(final OutputStream out) throws IOException { try { emailMessage.writeTo(out); } catch (MessagingException e) { throw new IOException(e); } } }); long executionDuration = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); String fromAddressesString = ""; try { Address[] fromAddresses = emailMessage.getFrom(); if (fromAddresses != null) { fromAddressesString = Arrays.asList(fromAddresses).toString(); } } catch (MessagingException e) { this.logger.warn("Faild to retrieve 'From' attribute from Message."); } processSession.getProvenanceReporter().receive(flowFile, this.displayUrl, "Received message from " + fromAddressesString, executionDuration); this.getLogger().info("Successfully received {} from {} in {} millis", new Object[] { flowFile, fromAddressesString, executionDuration }); processSession.transfer(flowFile, REL_SUCCESS); try { emailMessage.setFlag(Flags.Flag.DELETED, this.shouldSetDeleteFlag); } catch (MessagingException e) { this.logger.warn("Failed to set DELETE Flag on the message, data duplication may occur."); } }
From source file:com.intranet.intr.inbox.SupControllerInbox.java
@RequestMapping(value = "/ajaxtestNoL", method = RequestMethod.GET) public @ResponseBody String ajaxtestNoL(Principal principal) { String name = principal.getName(); String result = ""; try {//from w w w . ja va 2s .c o m users u = usuarioService.getByLogin(name); Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("imap.1and1.es", u.getCorreoUsuario(), u.getCorreoContreasenna()); System.out.println("ola" + store); Folder inbox = store.getFolder("Inbox"); inbox.open(Folder.READ_ONLY); FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false); Calendar fecha3 = Calendar.getInstance(); fecha3.roll(Calendar.MONTH, false); Message msg[] = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, fecha3.getTime())); //Message msg[] = inbox.search(ft); System.out.println("MAILS: " + msg.length); for (Message message : msg) { try { /*System.out.println("DATE: "+message.getSentDate().toString()); System.out.println("FROM: "+message.getFrom()[0].toString()); System.out.println("SUBJECT: "+message.getSubject().toString()); System.out.println("CONTENT: "+message.getContent().toString()); System.out.println("******************************************"); */result = result + "<li>" + "<a href='#' class='clearfix'>" + "<span class='msg-body'>" + "<span class='msg-title'>" + "<span class='blue'>" + message.getFrom()[0].toString() + "</span>" + message.getSubject().toString() + "</span>" + "</span>" + "</a>" + "</li> "; } catch (Exception e) { // TODO Auto-generated catch block System.out.println("No Information"); } } } catch (Exception ex) { } return result; }
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 *//*from www . ja va2s . 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; }