Ler emails recebidos usando API JavaMail
11/09/2012
0
Desde ja Agradeço!!
Thiago Moises
Post mais votado
14/09/2012
fuçando na net mais uma vez fui achando algum material e implementei minha classe:
-Criei uma variavel para configurar o SSL do hotmail
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
- Fiz algumas mudanças na configuração
Properties pop3Props = new Properties(); pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false"); pop3Props.setProperty("mail.pop3.port", "995"); pop3Props.setProperty("mail.pop3.socketFactory.port", "995");
-Adicionei a configuração de URL (que estava faltando!!)
URLName url = new URLName("pop3", host, 995, "",username, passwoed);
no final a classe ficou dessa forma:
import com.sun.mail.pop3.*; import java.util.*; import javax.activation.DataHandler; import javax.mail.*; import javax.mail.internet.*; public class ReadMultipartMail { public static void main(String args[]) throws Exception { String host = "pop3.live.com"; String username = "meuemail"; String passwoed = "senha"; Properties props = System.getProperties(); String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Properties pop3Props = new Properties(); pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false"); pop3Props.setProperty("mail.pop3.port", "995"); pop3Props.setProperty("mail.pop3.socketFactory.port", "995"); URLName url = new URLName("pop3", host, 995, "",username, passwoed); Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(usename, passwoed); } }); Store store = new POP3SSLStore(session, url); store.connect(); Folder folder = store.getFolder("inbox"); if (!folder.exists()) { System.out.println("No INBOX..."); System.exit(0); } folder.open(Folder.READ_WRITE); Message[] msg = folder.getMessages(); for (int i = 0; i < msg.length; i++) { System.out.println("------------ Message " + (i + 1) + " ------------"); String from = InternetAddress.toString(msg[i].getFrom()); if (from != null) { System.out.println("From: " + from); } String replyTo = InternetAddress.toString( msg[i].getReplyTo()); if (replyTo != null) { System.out.println("Reply-to: " + replyTo); } String to = InternetAddress.toString( msg[i].getRecipients(Message.RecipientType.TO)); if (to != null) { System.out.println("To: " + to); } String subject = msg[i].getSubject(); if (subject != null) { System.out.println("Subject: " + subject); } Date sent = msg[i].getSentDate(); if (sent != null) { System.out.println("Sent: " + sent); } System.out.println(); System.out.println("Message : "); Multipart multipart = (Multipart) msg[i].getContent(); for (int x = 0; x < multipart.getCount(); x++) { BodyPart bodyPart = multipart.getBodyPart(x); String disposition = bodyPart.getDisposition(); if (disposition != null && (disposition.equals(BodyPart.ATTACHMENT))) { System.out.println("Mail have some attachment : "); DataHandler handler = bodyPart.getDataHandler(); System.out.println("file name : " + handler.getName()); } else { System.out.println(bodyPart.getContent()); } } System.out.println(); } folder.close(true); store.close(); }
agora só falta ddescobrir como selecionar somente o email que eu qro.
Mais ja eh um começo
Valew Davi. Vc ajudou muito...
Alias.. Vc estava certo. A congiguração do meu properties estava errada....
Abraços
Thiago Moises
Mais Posts
12/09/2012
Davi Costa
att Davi
12/09/2012
Thiago Moises
Fucando na net e depois d muito trabalho eu consegui algumas classes que mostram exemplos. Porem todas elas me gera um Exception parecido.
Aqui esta minha classe:
import java.util.*; import javax.activation.DataHandler; import javax.mail.*; import javax.mail.internet.*; public class ReadMultipartMail_1 { public static void main(String args[]) throws Exception { final String host = "pop3.live.com"; final String username = "meuEmail"; final String passwoed = "minhaSenha"; try{ Properties props = new Properties(); props.put("mail.transport.protocol", "pop3"); props.put("mail.smtp.host", host); props.put("mail.smtp.socketFactory.port", "995"); props.put("mail.smtp.socketFactory.fallback", "false"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "995"); // Get session Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, passwoed); } }); //session.setDebug(true); // Get the store System.out.println("Session complete"); Store store = session.getStore("pop3"); System.out.println("Store complete"); store.connect(host,username,passwoed); System.out.println(store.isConnected()); // Get folder Folder folder = store.getDefaultFolder(); folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); // Get directory Message message[] = folder.getMessages(); for (int i=0, n=message.length; i<n; i++) { System.out.println(i + ": " + message[i].getFrom()[0] + "\t" + message[i].getSubject()); } // Close connection folder.close(false); store.close(); }catch(Exception e){ System.out.println(e); e.printStackTrace();} } }
o exception gerado é esse:
javax.mail.MessagingException: Connect failed; nested exception is: nested exception is: java.net.ConnectException: Connection timed out: connect java.net.ConnectException: Connection timed out: connect at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:148) at javax.mail.Service.connect(Service.java:275) at javax.mail.Service.connect(Service.java:156) at Funcoes.Email.ReadMultipartMail_1.main(ReadMultipartMail_1.java:38) Caused by: java.net.ConnectException: Connection timed out: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366) at java.net.Socket.connect(Socket.java:529) at java.net.Socket.connect(Socket.java:478) at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:232) at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189) at com.sun.mail.pop3.Protocol.<init>(Protocol.java:81) at com.sun.mail.pop3.POP3Store.getPort(POP3Store.java:201) at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:144) ... 3 more
alguem ai sabe porque esse erro eh gerado???
Obrigado
12/09/2012
Davi Costa
att Davi
13/09/2012
Thiago Moises
26/10/2014
Soeusei1991
Alguém sabe como resolver esse erro?
26/10/2014
Soeusei1991
encontrei esse tópico que me ajudou a solucionar o problema.
http://stackoverflow.com/questions/23116465/java-lang-classcastexception-java-lang-string-cannot-be-cast-to-javax-mail-mult
//Your message content returning String and you are trying to type cast to Multipart. Object content = msg.getContent(); if (content instanceof String) { String body = (String)content; ... } else if (content instanceof Multipart) { Multipart mp = (Multipart)content; ... }
08/03/2016
Cleber Machado
Estou com este problema, alguém tem alguma dica:
javax.mail.MessagingException: Connect failed;
nested exception is:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:213)
at javax.mail.Service.connect(Service.java:366)
at javax.mail.Service.connect(Service.java:246)
at testeUnitarios.CheckingMails.check(CheckingMails.java:30)
at testeUnitarios.CheckingMails.main(CheckingMails.java:70)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1937)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1478)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:212)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:957)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:892)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1050)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1363)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1391)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1375)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:598)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:372)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
at com.sun.mail.pop3.Protocol.<init>(Protocol.java:112)
at com.sun.mail.pop3.POP3Store.getPort(POP3Store.java:265)
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:207)
... 4 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1460)
... 17 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:145)
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:131)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
... 23 more
Clique aqui para fazer login e interagir na Comunidade :)