List of usage examples for javax.mail Message getFrom
public abstract Address[] getFrom() throws MessagingException;
From source file:es.ucm.fdi.dalgs.mailbox.service.MailBoxService.java
/** * Returns new messages and fetches details for each message. */// w ww . 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.intranet.intr.inbox.EmpControllerInbox.java
public correoNoLeidos ltaRecibidos2(String name, int num) { correoNoLeidos lta = new correoNoLeidos(); Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); try {/*ww w . ja v a2s.c o m*/ users u = usuarioService.getByLogin(name); 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); Calendar fecha3 = Calendar.getInstance(); fecha3.roll(Calendar.MONTH, false); Message msg[] = inbox.search(new ReceivedDateTerm(ComparisonTerm.GT, fecha3.getTime())); //Message msg[] = inbox.getMessages(); System.out.println("MAILS: " + msg.length); for (Message message : msg) { try { if (num == message.getMessageNumber()) { //message.setFlag(Flags.Flag.SEEN, true); lta.setNum(message.getMessageNumber()); lta.setFecha(message.getSentDate().toString()); lta.setDe(message.getFrom()[0].toString()); lta.setAsunto(message.getSubject().toString()); correoNoLeidos co = new correoNoLeidos(); List<String> arc = new ArrayList<String>(); List<String> rar = new ArrayList<String>(); correoNoLeidos cc = analizaParteDeMensaje2(co, arc, rar, message); lta.setImagenes(cc.getImagenes()); lta.setRar(cc.getRar()); lta.setContenido(cc.getContenido()); String cont = ""; String contenido = ""; //lta.setContenido(analizaParteDeMensaje2(message)); } } catch (Exception e) { System.out.println("No Information"); } } } catch (MessagingException e) { System.out.println(e.toString()); } return lta; }
From source file:org.gcaldaemon.core.GmailEntry.java
public final GmailMessage[] receive(String title) throws Exception { // Open 'INBOX' folder Folder inbox = mailbox.getFolder("INBOX"); inbox.open(Folder.READ_WRITE);//from w w w. j a v a 2 s . c om Message[] messages = inbox.getMessages(); if (messages == null || messages.length == 0) { return new GmailMessage[0]; } // Loop on messages LinkedList list = new LinkedList(); for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; if (!msg.isSet(Flag.SEEN)) { String subject = msg.getSubject(); if (title == null || title.length() == 0 || title.equals(subject)) { GmailMessage gm = new GmailMessage(); Address[] from = msg.getFrom(); msg.setFlag(Flag.SEEN, true); if (from == null || from.length == 0) { continue; } gm.subject = subject; gm.from = from[0].toString(); gm.memo = String.valueOf(msg.getContent()); list.addLast(gm); } } } inbox.close(true); // Return the array of the messages GmailMessage[] array = new GmailMessage[list.size()]; list.toArray(array); return array; }
From source file:com.jaeksoft.searchlib.crawler.mailbox.crawler.MailboxAbstractCrawler.java
final public void readMessage(IndexDocument crawlIndexDocument, IndexDocument parserIndexDocument, Folder folder, Message message, String id) throws Exception { crawlIndexDocument.addString(MailboxFieldEnum.message_id.name(), id); crawlIndexDocument.addString(MailboxFieldEnum.message_number.name(), Integer.toString(message.getMessageNumber())); if (message instanceof MimeMessage) crawlIndexDocument.addString(MailboxFieldEnum.content_id.name(), ((MimeMessage) message).getContentID()); crawlIndexDocument.addString(MailboxFieldEnum.subject.name(), message.getSubject()); putAddresses(crawlIndexDocument, message.getFrom(), MailboxFieldEnum.from_address.name(), MailboxFieldEnum.from_personal.name()); putAddresses(crawlIndexDocument, message.getReplyTo(), MailboxFieldEnum.reply_to_address.name(), MailboxFieldEnum.reply_to_personal.name()); putAddresses(crawlIndexDocument, message.getRecipients(RecipientType.TO), MailboxFieldEnum.recipient_to_address.name(), MailboxFieldEnum.recipient_to_personal.name()); putAddresses(crawlIndexDocument, message.getRecipients(RecipientType.CC), MailboxFieldEnum.recipient_cc_address.name(), MailboxFieldEnum.recipient_cc_personal.name()); putAddresses(crawlIndexDocument, message.getRecipients(RecipientType.BCC), MailboxFieldEnum.recipient_bcc_address.name(), MailboxFieldEnum.recipient_bcc_personal.name()); Date dt = message.getSentDate(); if (dt != null) crawlIndexDocument.addString(MailboxFieldEnum.send_date.name(), dt.toString()); dt = message.getReceivedDate();//from w w w. j av a 2 s .co m if (dt != null) crawlIndexDocument.addString(MailboxFieldEnum.received_date.name(), dt.toString()); if (message.isSet(Flag.ANSWERED)) crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "ANSWERED"); if (message.isSet(Flag.DELETED)) crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "DELETED"); if (message.isSet(Flag.DRAFT)) crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "DRAFT"); if (message.isSet(Flag.FLAGGED)) crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "FLAGGED"); if (message.isSet(Flag.SEEN)) crawlIndexDocument.addString(MailboxFieldEnum.flags.name(), "SEEN"); if (message instanceof MimeMessage) { MimeMessageParser mimeMessageParser = new MimeMessageParser((MimeMessage) message).parse(); crawlIndexDocument.addString(MailboxFieldEnum.html_content.name(), mimeMessageParser.getHtmlContent()); crawlIndexDocument.addString(MailboxFieldEnum.plain_content.name(), mimeMessageParser.getPlainContent()); for (DataSource dataSource : mimeMessageParser.getAttachmentList()) { crawlIndexDocument.addString(MailboxFieldEnum.email_attachment_name.name(), dataSource.getName()); crawlIndexDocument.addString(MailboxFieldEnum.email_attachment_type.name(), dataSource.getContentType()); if (parserSelector == null) continue; Parser attachParser = parserSelector.parseStream(null, dataSource.getName(), dataSource.getContentType(), null, dataSource.getInputStream(), null, null, null); if (attachParser == null) continue; List<ParserResultItem> parserResults = attachParser.getParserResults(); if (parserResults != null) for (ParserResultItem parserResult : parserResults) crawlIndexDocument.addFieldIndexDocument(MailboxFieldEnum.email_attachment_content.name(), parserResult.getParserDocument()); } } }
From source file:org.openiam.idm.srvc.msg.service.MailSenderClient.java
public void send(Message msg) { Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.transport.protocol", "smtp"); if (username != null && !username.isEmpty()) { properties.setProperty("mail.user", username); properties.setProperty("mail.password", password); }/* w w w.j a v a2s .c o m*/ if (port != null && !port.isEmpty()) { properties.setProperty("mail.smtp.port", port); } Session session = Session.getDefaultInstance(properties); MimeMessage message = new MimeMessage(session); try { message.setFrom(msg.getFrom()); if (msg.getTo().size() > 1) { List<InternetAddress> addresses = msg.getTo(); message.addRecipients(TO, addresses.toArray(new Address[addresses.size()])); } else { message.addRecipient(TO, msg.getTo().get(0)); } if (msg.getBcc() != null && msg.getBcc().size() != 0) { if (msg.getTo().size() > 1) { List<InternetAddress> addresses = msg.getBcc(); message.addRecipients(BCC, addresses.toArray(new Address[addresses.size()])); } else { message.addRecipient(TO, msg.getBcc().get(0)); } } if (msg.getCc() != null && msg.getCc().size() > 0) { if (msg.getCc().size() > 1) { List<InternetAddress> addresses = msg.getCc(); message.addRecipients(CC, addresses.toArray(new Address[addresses.size()])); } else { message.addRecipient(CC, msg.getCc().get(0)); } } message.setSubject(msg.getSubject(), "UTF-8"); MimeBodyPart mbp1 = new MimeBodyPart(); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); if (msg.getBodyType() == Message.BodyType.HTML_TEXT) { mbp1.setContent(msg.getBody(), "text/html"); } else { mbp1.setText(msg.getBody(), "UTF-8"); } if (port != null && !port.isEmpty()) { properties.setProperty("mail.smtp.port", port); } mp.addBodyPart(mbp1); if (msg.getAttachments().size() > 0) { for (String fileName : msg.getAttachments()) { // create the second message part MimeBodyPart mbpFile = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(fileName); mbpFile.setDataHandler(new DataHandler(fds)); mbpFile.setFileName(fds.getName()); mp.addBodyPart(mbpFile); } } // add the Multipart to the message message.setContent(mp); if (username != null && !username.isEmpty()) { properties.setProperty("mail.user", username); properties.setProperty("mail.password", password); properties.put("mail.smtp.auth", auth); properties.put("mail.smtp.starttls.enable", starttls); Transport mailTransport = session.getTransport(); mailTransport.connect(host, username, password); mailTransport.sendMessage(message, message.getAllRecipients()); } else { Transport.send(message); log.debug("Message successfully sent."); } } catch (Throwable e) { log.error("Exception while sending mail", e); } }
From source file:de.kp.ames.web.function.access.imap.ImapConsumer.java
/** * @param m// www . j a v a 2 s . com * @return * @throws Exception */ private String mail2HTML(Message m) throws Exception { /* * Date & subject */ String date = m.getSentDate().toString(); String subject = m.getSubject(); /* * Body */ String body = getBody(m); /* * From */ String from = ""; Address[] addresses = m.getFrom(); for (Address address : addresses) { InternetAddress internetAddress = (InternetAddress) address; from = internetAddress.getPersonal(); } return HtmlRenderer.mail2HTML(from, date, subject, body); }
From source file:com.liferay.mail.imap.IMAPAccessor.java
public void storeEnvelopes(long folderId, Folder jxFolder, Message[] jxMessages) throws PortalException { StopWatch stopWatch = new StopWatch(); stopWatch.start();//from w ww.j a va2s .c om try { FetchProfile fetchProfile = new FetchProfile(); fetchProfile.add(UIDFolder.FetchProfileItem.ENVELOPE); fetchProfile.add(UIDFolder.FetchProfileItem.FLAGS); fetchProfile.add(UIDFolder.FetchProfileItem.UID); jxFolder.fetch(jxMessages, fetchProfile); for (Message jxMessage : jxMessages) { String sender = InternetAddressUtil.toString(jxMessage.getFrom()); String to = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.TO)); String cc = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.CC)); String bcc = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.BCC)); Date sentDate = jxMessage.getSentDate(); String subject = jxMessage.getSubject(); String flags = getFlags(jxMessage); long remoteMessageId = getUID(jxFolder, jxMessage); String contentType = jxMessage.getContentType(); try { MessageLocalServiceUtil.getMessage(folderId, remoteMessageId); } catch (NoSuchMessageException nsme) { MessageLocalServiceUtil.addMessage(_user.getUserId(), folderId, sender, to, cc, bcc, sentDate, subject, StringPool.BLANK, flags, remoteMessageId, contentType); } } com.liferay.mail.model.Folder folder = FolderLocalServiceUtil.getFolder(folderId); FolderLocalServiceUtil.updateFolder(folderId, folder.getFullName(), folder.getDisplayName(), jxFolder.getMessageCount()); } catch (MessagingException me) { throw new MailException(me); } if (_log.isDebugEnabled()) { stopWatch.stop(); _log.debug("Downloaded " + jxMessages.length + " messages from folder " + jxFolder.getFullName() + " completed in " + stopWatch.getTime() + " ms"); } }
From source file:org.sourceforge.net.javamail4ews.transport.EwsTransport.java
private void createAddresses(EmailMessage pEmailMessage, Message pMessage, Address[] pToAddresses, Address[] pCcAddresses, Address[] pBccAddresses) throws Exception { if (pMessage instanceof MimeMessage) { MimeMessage lMimeMessage = (MimeMessage) pMessage; if (pToAddresses.length <= 0) { pToAddresses = lMimeMessage.getRecipients(javax.mail.Message.RecipientType.TO); }/*from w w w . j ava2s . c o m*/ if (pCcAddresses.length <= 0) { pCcAddresses = lMimeMessage.getRecipients(javax.mail.Message.RecipientType.CC); } if (pBccAddresses.length <= 0) { pBccAddresses = lMimeMessage.getRecipients(javax.mail.Message.RecipientType.BCC); } } Address[] from = pMessage.getFrom(); if (from != null && from.length > 0) { pEmailMessage.setFrom(emailAddressFromInternetAddress(from[0])); } for (Address aAddress : pToAddresses) { logger.info("Adding adress {} as TO recepient", aAddress.toString()); pEmailMessage.getToRecipients().add(emailAddressFromInternetAddress(aAddress)); } if (pCcAddresses != null) { for (Address aAddress : pCcAddresses) { logger.info("Adding adress {} as CC recepient", aAddress.toString()); pEmailMessage.getCcRecipients().add(emailAddressFromInternetAddress(aAddress)); } } if (pBccAddresses != null) { for (Address aAddress : pBccAddresses) { logger.info("Adding adress {} as BCC recepient", aAddress.toString()); pEmailMessage.getBccRecipients().add(emailAddressFromInternetAddress(aAddress)); } } }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!/*from ww w .j a v a 2 s .c om*/ * * @param message DOCUMENT ME! * * @return DOCUMENT ME! * * @throws MessagingException DOCUMENT ME! */ public static String decodeFromName(Message message) throws MessagingException { Address[] xaddresses = message.getFrom(); return decodeAddressesName(xaddresses); }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * Decode from address(es) of the message into UTF strings. This is a * convenience method provided to simplify application code. * * @param message The message to interogate * * @return String List of decoded addresses * * @exception MessagingException if the message contents are invalid *//*from w w w . j ava 2 s.c o m*/ public static String decodeFrom(Message message) throws MessagingException, Exception { Address[] xaddresses = message.getFrom(); return decodeAddresses(xaddresses); }