Alguém sabe como acessar o anexo com Java Mail?
Exemplo tenho um e-mail com um anexo na caixa, meu app vai lá, pega a msg mais o anexo pra mim.
Alguem conhece?
vlw
Alguém sabe como acessar o anexo com Java Mail?
Exemplo tenho um e-mail com um anexo na caixa, meu app vai lá, pega a msg mais o anexo pra mim.
Alguem conhece?
vlw
[color=darkblue] Não sei se é bem isso o que precisa, mas segue:[/color]
EXEMPLO COMPLETO DE ENVIO DE E-MAIL COM ANEXO USANDO JSP + JAVAMAIL
[color=darkblue] Não sei se é bem isso o que precisa, mas segue:[/color]EXEMPLO COMPLETO DE ENVIO DE E-MAIL COM ANEXO USANDO JSP + JAVAMAIL
Não seria o envio, preciso que meu app acesse o e-mail, pegue o anexo, salve em uma pasta, marque o e-mail como lido, é isso, mas vlw os links =)
Sobre o envio em si peguei essas pra ver:
http://javafree.uol.com.br/forum/viewtopic.php?p=22161#22161
http://java.sun.com/products/javamail/FAQ.html
http://java.sun.com/developer/onlineTraining/JavaMail/contents.html#InstallJAF
http://java.sun.com/products/javamail/learning/tutorial/index.html
http://commons.apache.org/email/
http://www.apache.org/foundation/getinvolved.html
http://www.guj.com.br/posts/list/62607.java
http://commons.apache.org/email/api-release/index.html
eae doido …
http://www.hiteshagrawal.com/java/reading-pop3-mails-using-java
eh um codigo bem feinho mas aparentemente serve.
the google search = read email server java
poe la aparece mais coisas 
tem casos que costuma dar alguns paus, fiz uma aplicação que faz isso, e tenho alguns problemas, mas boa sorte hehe
qualquer coisa diz ai
rsrs
eae doido …http://www.hiteshagrawal.com/java/reading-pop3-mails-using-java
eh um codigo bem feinho mas aparentemente serve.
the google search = read email server java
poe la aparece mais coisas
tem casos que costuma dar alguns paus, fiz uma aplicação que faz isso, e tenho alguns problemas, mas boa sorte hehe
qualquer coisa diz ai
rsrs
Haha era isso mesmo, vlw 
eae doido …http://www.hiteshagrawal.com/java/reading-pop3-mails-using-java
eh um codigo bem feinho mas aparentemente serve.
the google search = read email server java
poe la aparece mais coisas
tem casos que costuma dar alguns paus, fiz uma aplicação que faz isso, e tenho alguns problemas, mas boa sorte hehe
qualquer coisa diz ai
rsrs
Haha era isso mesmo, vlw
![]()
Bom isso funfou para o e-mail externo e tal, mas aqui internamente é Lotus Notes, e está dando o seguinte erro:
Pegando a sessão para acesso de e-mail.
javax.mail.AuthenticationFailedException: Error. The system was unable to log bregaida/CB in.
Não há processos para ler o e-mail.
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:158)
at javax.mail.Service.connect(Service.java:291)
at javax.mail.Service.connect(Service.java:172)
at ReadEmails.processMail(ReadEmails.java:56)
at ReadEmails.<init>(ReadEmails.java:27)
at ReadEmails.main(ReadEmails.java:165)
Tem idéia? 
Assim Funfou com IMAP 8)
Properties prop = new Properties();
session = Session.getInstance(prop);
URLName url = new URLName(imap, host, porta, diretorioServidor, login, senha);
store = session.getStore(url);
store.connect();
Assim Funfou com IMAP 8)Properties prop = new Properties(); session = Session.getInstance(prop); URLName url = new URLName(imap, host, porta, diretorioServidor, login, senha); store = session.getStore(url); store.connect();
:)P
Assim Funfou com IMAP 8)Properties prop = new Properties(); session = Session.getInstance(prop); URLName url = new URLName(imap, host, porta, diretorioServidor, login, senha); store = session.getStore(url); store.connect();:)P
Mais uma dúvida, tem como eu marcar o e-mail como lido? :wink:
Também queria saber como pego o OutputStream e faço ele gravar na pasta eu fiz assim mas n funfou: 
String disposition = part.getDisposition();
if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) {
salvarArquivo(part.getFileName(), part.getInputStream());
}
}
File file = new File(pasta);
for (int i=0; file.exists(); i++) {
file = new File( pasta+fileName+i);
}
No momento não tenho em mãos como se faz isso, mas tem como sim, e eh facinho 
quando chegar em casa posto o esquema
KISS …
(Keep it Stuped and Simple)
No momento não tenho em mãos como se faz isso, mas tem como sim, e eh facinho![]()
quando chegar em casa posto o esquema
KISS …
(Keep it Stuped and Simple)
hahaha vlw, enqto isso vou tentando achar no Google =)
No momento não tenho em mãos como se faz isso, mas tem como sim, e eh facinho![]()
quando chegar em casa posto o esquema
KISS …
(Keep it Stuped and Simple)hahaha vlw, enqto isso vou tentando achar no Google =)
No momento não tenho em mãos como se faz isso, mas tem como sim, e eh facinho![]()
quando chegar em casa posto o esquema
KISS …
(Keep it Stuped and Simple)hahaha vlw, enqto isso vou tentando achar no Google =)
Resolvi amanhã posto a solução, só falta agora ler somente e-mails nao lidos pois ele está lendo todos e marcar os novos como lido, dai acabo de uma vez =)
Resolução para salvar o anexo:
private void salvarArquivo(Part part) throws IOException, MessagingException {
String pasta = "c:/teste/teste/";
FileOutputStream fileOutputStream = new FileOutputStream(pasta+part.getFileName());
Object obj = part.getContent();
if( obj instanceof InputStream ){
InputStream is = (InputStream) obj;
int ch = -1;
while( (ch = is.read() ) != -1 ){
fileOutputStream.write(ch);
}
}
}
No final ficou assim 8)
Hehehe vlw a ajuda 
public class ReadEmails {
// Constructor Call
public ReadEmails() throws MessagingException {
processMail();
}
/**
* Responsável pelas mensagens na tela
* @param data
*/
private void printData(String data) {
System.out.println(data);
}
public void processMail() throws MessagingException {
Store store = null;
Folder folder = null;
Message message = null;
Message[] messages = null;
Object msgObj = null;
String sender = null;
String subject = null;
Multipart multipart = null;
Part part = null;
String contentType = null;
try {
store = conexaoServidorEMail();
folder = getPastaCaixaEntrada(store);
messages = folder.getMessages();
for (int messageNumber = 0; messageNumber < messages.length; messageNumber++) {
message = messages[messageNumber];
msgObj = message.getContent();
// Determine o tipo de email
if (msgObj instanceof Multipart) {
printData("Encontrado e-mail com anexo.");
sender = ((InternetAddress) message.getFrom()[0]).getPersonal();
printData("Se a informação de entrada é pessoal, checar o endereço para envio de informação.");
if (sender == null) {
sender = ((InternetAddress) message.getFrom()[0]).getAddress();
printData("Sender vazio. Escrever Endereço:" + sender);
}
printData("Enviar -." + sender);
subject = message.getSubject();
printData("Assunto=" + subject);
multipart = (Multipart) message.getContent();
printData("Recuperar objeto multpart da mensagem.");
for (int i = 0; i < multipart.getCount(); i++) {
part = multipart.getBodyPart(i);
// pegando um tipo do conteúdo
contentType = part.getContentType();
// Tela do conteúdo
printData("Conteúdo: " + contentType);
if (contentType.startsWith("text/plain")) {
printData("---------lendo conteúdo do e-mail contendo text/plain -------------");
} else {
// Recebendo o nome do arquivo
@SuppressWarnings("unused")
String fileName = validarXML(part, store,folder,messages,i);
}
}
} else {
printData("Encontrado e-mail com anexos.");
sender = ((InternetAddress) message.getFrom()[0]).getPersonal();
printData("Se a informação de entrada é pessoal, checar o endereço para envio de informação.");
if (sender == null) {
sender = ((InternetAddress) message.getFrom()[0]).getAddress();
printData("Envio é nulo. Escrever endereço:" + sender);
}
// Get the subject information
subject = message.getSubject();
printData("Assunto=" + subject);
}
}
// Fecha a pasta
folder.close(true);
// Histório de mensagens
store.close();
} catch (AuthenticationFailedException e) {
store.close();
e.printStackTrace();
} catch (FolderClosedException e) {
store.close();
e.printStackTrace();
} catch (FolderNotFoundException e) {
store.close();
e.printStackTrace();
} catch (NoSuchProviderException e) {
store.close();
e.printStackTrace();
} catch (ReadOnlyFolderException e) {
store.close();
e.printStackTrace();
} catch (StoreClosedException e) {
store.close();
e.printStackTrace();
} catch (Exception e) {
store.close();
e.printStackTrace();
}
}
/**
* @param messages
* @param i
* @throws MessagingException
*/
private void excluirMensagemInbox(Message[] messages, int i) throws MessagingException {
BufferedReader reader = new BufferedReader (new InputStreamReader(System.in));
messages[i].setFlag(Flags.Flag.DELETED, true);
System.out.println("Msg Delete .....");
}
/**
* Envia os arquivos da pasta princiál para a pasta reserva
* @param store
* @param folder
* @param messages
* @throws MessagingException
*/
private void enviaArquivoPastaAuxiliar(Store store, Folder folder, Message[] messages, int i) throws MessagingException {
printData("Enviando os e-mails lidos para pasta Auxiliar");
Folder folderAux;
folderAux = getPastaAuxiliar(store);
folder.copyMessages(messages, folderAux);
folderAux.close(true);
excluirMensagemInbox(messages, i);
}
/**
* Recebe o anexo e valida se é um XML, se sim ele salva o arquivo em uma pasta
* @param part
* @return
* @throws MessagingException
* @throws IOException
*/
private String validarXML(Part part, Store store, Folder folder, Message[] messages, int i) throws MessagingException, IOException {
String fileName = part.getFileName();
printData("recebendo e validando os anexos=" + fileName);
if(fileName!=null){
int tamanhoString = fileName.length()-3;
if (!fileName.substring(tamanhoString).equals("xml")){
printData("Não era XML "+fileName+" - "+fileName.substring(tamanhoString));
return fileName;
}else{
String disposition = part.getDisposition();
if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) {
salvarArquivo(part);
enviaArquivoPastaAuxiliar(store, folder, messages, i);
}
}
}
return fileName;
}
/**
* Salva o arquivo em uma pasta
* @param part
* @throws MessagingException
* @throws IOException
*/
private void salvarArquivo(Part part) throws IOException, MessagingException {
String pasta = "c:/teste/teste";
printData("Salvando os arquivos XML.");
FileOutputStream fileOutputStream = new FileOutputStream(pasta+part.getFileName());
Object obj = part.getContent();
if( obj instanceof InputStream ){
InputStream is = (InputStream) obj;
int ch = -1;
while( (ch = is.read() ) != -1 ){
fileOutputStream.write(ch);
}
}
}
/**
* Acessa a Caixa de Entrada (Inbox)
* @param store
* @return
* @throws MessagingException
*/
private Folder getPastaCaixaEntrada(Store store) throws MessagingException {
Folder folder;
printData("Pegando pasta da Caixa de entrada.");
folder = store.getFolder("Inbox");
folder.open(Folder.READ_WRITE);
return folder;
}
/**
* Acessa a Pasta Auxiliar
* @param store
* @return
* @throws MessagingException
*/
private Folder getPastaAuxiliar(Store store) throws MessagingException {
Folder folder;
printData("Pegando pasta Auxiliar.");
folder = store.getFolder("PastaTeste");
folder.open(Folder.READ_WRITE);
return folder;
}
/**
* Autenticação e conexão com o Servidor de e-mail
* @return
* @throws NoSuchProviderException
* @throws MessagingException
*/
private Store conexaoServidorEMail() throws NoSuchProviderException, MessagingException {
Session session;
Store store;
printData("--------------Processo de leitura iniciado-----------------");
String imap = "imap";
String host = "host";
int porta = port;
String diretorioServidor = "diretorio";
String login = "login";
String senha = "senha";
Properties prop = new Properties();
session = Session.getInstance(prop);
URLName url = new URLName(imap, host, porta, diretorioServidor, login, senha);
store = session.getStore(url);
store.connect();
printData("Conexão estabelecida com servidor IMAP.");
return store;
}
}
Agora é só deixar esse código mais bonito e parrudo, mas já ta funfando 
Agora rolou outro problema, ele não copia apenas o e-mail que eu quero,ele está copiando todos :roll:
Bom achei a solução, ficou assim:
Classe de Constantes:
/**
* @author Eduardo Bregaida
*
*/
public class Constantes {
public static final String PASTA_XML = pasta onde o XML será salvo em seu computador;
public static final String IMAP = "imap";
public static final String HOST = Seu host;
public static final int PORTA = Sua porta;
public static final String ARQUIVO_MSG = Arquivo de mensagens do seu e-mail;
public static final String LOGIN = Seu login;
public static final String SENHA = Sua senha;
public static final String PASTA_PRINCIPAL = "Inbox";
public static final String PASTA_BACKUP = pasta caso você copie os e-mails da principal como fiz;
}
Classe ReadEmails
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import javax.mail.AuthenticationFailedException;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.FolderClosedException;
import javax.mail.FolderNotFoundException;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.ReadOnlyFolderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.StoreClosedException;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
/**
* @author Eduardo Bregaida
*
*/
public class ReadEmails {
private Store store = null;
private Folder folder = null;
private Message message = null;
private Message[] messages = null;
private Object msgObj = null;
private String sender = null;
@SuppressWarnings("unused")
private String subject = null;
private Multipart multipart = null;
private Part part = null;
private String contentType = null;
public ReadEmails() throws MessagingException {
processMail();
}
/**
* Processa o e-mail
*
*/
public void processMail() throws MessagingException {
try {
store = conexaoServidorEMail();
folder = getPastaCaixaEntrada(store);
messages = folder.getMessages();
for (int messageNumber = 0; messageNumber < messages.length; messageNumber++) {
message = messages[messageNumber];
msgObj = message.getContent();
// Determine o tipo de email
if (msgObj instanceof Multipart) {
subject = message.getSubject();
multipart = (Multipart) message.getContent();
for (int i = 0; i < multipart.getCount(); i++) {
part = multipart.getBodyPart(i);
// pegando um tipo do conteúdo
contentType = part.getContentType();
String fileName2 = part.getFileName();
if(fileName2 != null) {
System.out.println(messageNumber + " " + fileName2 + " | " + message.getSubject());
}
fileName2 = null;
// Tela do conteúdo
if (contentType.startsWith("text/plain")) {
} else {
String fileName = part.getFileName();
@SuppressWarnings("unused")
Message[] mensagensXML = separaMensagensXML(i, fileName);
}
}
} else {
sender = ((InternetAddress) message.getFrom()[0]).getPersonal();
if (sender == null) {
sender = ((InternetAddress) message.getFrom()[0]).getAddress();
}
// Get the subject information
subject = message.getSubject();
}
}
// Fecha a pasta
folder.close(true);
// Histório de mensagens
store.close();
System.out.println("Terminado");
} catch (AuthenticationFailedException e) {
store.close();
e.printStackTrace();
} catch (FolderClosedException e) {
store.close();
e.printStackTrace();
} catch (FolderNotFoundException e) {
store.close();
e.printStackTrace();
} catch (NoSuchProviderException e) {
store.close();
e.printStackTrace();
} catch (ReadOnlyFolderException e) {
store.close();
e.printStackTrace();
} catch (StoreClosedException e) {
store.close();
e.printStackTrace();
} catch (Exception e) {
store.close();
e.printStackTrace();
}
}
/**
* @param i
* @param fileName
* @return
* @throws MessagingException
* @throws IOException
*/
private Message[] separaMensagensXML(int i, String fileName) throws MessagingException, IOException {
Message[] mensagensXML = folder.getMessages();;
if (fileName != null) {
int tamanhoString = fileName.length() - 3;
for (int a = 0; a < messages.length; a++) {
if (fileName.substring(tamanhoString).equals("xml")) {
mensagensXML[a] = message;
}
}
}
// Recebendo o nome do arquivo
@SuppressWarnings("unused")
String fileName2 = validarXML(part, store, folder, mensagensXML, i);
return mensagensXML;
}
/**
* @param messages
* @param i
* @throws MessagingException
*/
private void excluirMensagemInbox(Message[] messages, int i) throws MessagingException {
@SuppressWarnings("unused")
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
messages[i].setFlag(Flags.Flag.DELETED, true);
}
/**
* Envia os arquivos da pasta princiál para a pasta reserva
*
* @param store
* @param folder
* @param messages
* @throws MessagingException
*/
private boolean enviaArquivoPastaAuxiliar(Store store, Folder folder, Message[] messages, int i) throws MessagingException {
return false;
Folder folderAux;
folderAux = getPastaAuxiliar(store);
folder.copyMessages(messages, folderAux);
folderAux.close(true);
excluirMensagemInbox(messages, i);
}
/**
* Recebe o anexo e valida se é um XML, se sim ele salva o arquivo em uma
* pasta
*
* @param part
* @return
* @throws MessagingException
* @throws IOException
*/
private String validarXML(Part part, Store store, Folder folder, Message[] messages, int i) throws MessagingException, IOException {
String fileName = part.getFileName();
if (fileName != null) {
int tamanhoString = fileName.length() - 3;
if (!fileName.substring(tamanhoString).equals("xml")) {
return fileName;
} else {
String disposition = part.getDisposition();
if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) {
salvarArquivo(part);
enviaArquivoPastaAuxiliar(store, folder, messages, i);
}
}
}
return fileName;
}
/**
* Salva o arquivo em uma pasta
*
* @param part
* @throws MessagingException
* @throws IOException
*/
private void salvarArquivo(Part part) throws IOException, MessagingException {
FileOutputStream fileOutputStream = new FileOutputStream(Constantes.PASTA_XML + part.getFileName());
Object obj = part.getContent();
if (obj instanceof InputStream) {
InputStream is = (InputStream) obj;
int ch = -1;
while ((ch = is.read()) != -1) {
fileOutputStream.write(ch);
}
}
}
/**
* Acessa a Caixa de Entrada (Inbox)
*
* @param store
* @return
* @throws MessagingException
*/
private Folder getPastaCaixaEntrada(Store store) throws MessagingException {
Folder folder;
folder = store.getFolder(Constantes.PASTA_PRINCIPAL);
folder.open(Folder.READ_WRITE);
return folder;
}
/**
* Acessa a Pasta Auxiliar
*
* @param store
* @return
* @throws MessagingException
*/
private Folder getPastaAuxiliar(Store store) throws MessagingException {
Folder folder;
folder = store.getFolder(Constantes.PASTA_BACKUP);
folder.open(Folder.READ_WRITE);
return folder;
}
/**
* Autenticação e conexão com o Servidor de e-mail
*
* @return
* @throws NoSuchProviderException
* @throws MessagingException
*/
private Store conexaoServidorEMail() throws NoSuchProviderException, MessagingException {
Session session;
Store store;
Properties prop = new Properties();
session = Session.getInstance(prop);
URLName url = new URLName(Constantes.IMAP, Constantes.HOST, Constantes.PORTA, Constantes.ARQUIVO_MSG, Constantes.LOGIN, Constantes.SENHA);
store = session.getStore(url);
store.connect();
return store;
}
}
Classe Principal (Main):
import javax.mail.MessagingException;
/**
* @author Eduardo Bregaida
*
*/
public class PrincipalNfe {
public static void main(String[] args) {
@SuppressWarnings("unused")
ReadEmails readMail =null;
try {
readMail = new ReadEmails();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
Manifest:
Manifest-Version: 1.1
Main-Class: PrincipalNfe
Class-Path: lib-dep/activation.jar
lib-dep/dsn.jar
lib-dep/imap.jar
lib-dep/mail.jar
lib-dep/mailapi.jar
lib-dep/pop3.jar
lib-dep/smtp.jar
Oi Eduardo Bregaida,
Tudo bom?
Testei esse seu código aqui na maquina da empresa e não consegui acessar o meu e-mail.
Parece que o proxy daqui só aceita requisições HTTP.
Será que você pode me ajudar com alguma ideia para eu conseguir acessar os meus e-mails?
Aguardo resposta.
Obrigado.
Leandro.
Oi Eduardo Bregaida,
Tudo bom?
Testei esse seu código aqui na maquina da empresa e não consegui acessar o meu e-mail.
Parece que o proxy daqui só aceita requisições HTTP.
Será que você pode me ajudar com alguma ideia para eu conseguir acessar os meus e-mails?
Aguardo resposta.
Obrigado.
Leandro.
opa vê se te ajuda, consegui assim: http://javawora.blogspot.com/2009/10/recebendo-e-mails-e-anexos-com-javamail.html
[]ssss
Gostaria de saber se com esse seu programa eu consigo acessar um email do notes
e verificar se ele contem algum anexo xml?
vlw
Gostaria de saber se com esse seu programa eu consigo acessar um email do notes
e verificar se ele contem algum anexo xml?vlw
Foi exatamente isso q fiz rs 
Pra quem quer utilizar o gmail, para fazer um backup utilizem o código abaixo no método conexaoServidorEMail :
private Store conexaoServidorEMail() throws NoSuchProviderException, MessagingException {
Session session;
Store store;
printData("--------------Processo de leitura iniciado-----------------");
String imap = "imap";
String host = "pop.gmail.com";
int porta = 587;
String diretorioServidor = "diretorio";
String login = "SEU USUARIO";
String senha = "SUA SENHA";
Properties prop = new Properties();
session = Session.getInstance(prop);
URLName url = new URLName(imap, host, porta, diretorioServidor, login, senha);
//store = session.getStore(url);
store = session.getStore("pop3s");
store.connect(host, login, senha);
printData("Conexão estabelecida com servidor IMAP.");
return store;
}
Caros,
Estou com dificuldade de configurar o imap do terra.com, algue, pode me ajudar?
No pop3 rodei o programa, mais quando tento configurar com IMAP da erro erro quando vai conectar (java.lang.NullPointerException).
Desde já obrigado.
Leandro
Galera, boa tarde…
executei o programa Eduardo aqui em minha maquina. Ele salva o arquivo na pasta desejada porem ele não salva o conteudo do arquivo xml
Alguem pode me ajudar ?
desde já agradeço.
Galera, boa tarde…
executei o programa Eduardo aqui em minha maquina. Ele salva o arquivo na pasta desejada porem ele não salva o conteudo do arquivo xml
Alguem pode me ajudar ?desde já agradeço.
Deixei um código no GitHub que tem uma parte útil para os anexos. https://github.com/Bregaida/LeituraEmail
Sei que essa dúvida do Gleybson já se resolveu, mas para futuras dúvidas, tem essa solução. 8)
O arquivo xml em alguns casos vem vazio pq o part.getContent() não vem com o conteudo correto, algumas vezes ele traz uma string com todo conteudo de dentro do arquivo, alguém sabe como resolver isto?
Não entendi, esse arquivo está vindo no corpo do email ou em anexo?
[]sss
Postei a última solução completa aqui: https://github.com/Bregaida/LeituraEmail espero que ajude 
Só fazendo uma correção para quem quer usar GMail é imaps e não imap como citado anteriormente, baseado no fonte que deixei basta ajustar como abaixo:
//Gmail
public static final String PASTA_XML = "c:/SuaPasta";
public static final String IMAP = "imaps";
public static final String HOST = "imap.gmail.com";
public static final int PORTA = 993;
public static final String ARQUIVO_MSG = "Inbox";
public static final String LOGIN = "[email removido]";
public static final String SENHA = "suaSenha";
public static final String PASTA_PRINCIPAL = "Inbox";
public static final String PASTA_BACKUP = "backup";
Ola, estou criando um webservices com a função parecida da sua solução Eduardo Bregaida.
queria deixar uma alteração que fiz devido a uma problema ao carregar alguns dos arquivos XMLs, eu alterei a seguinte linha mudando o encoding:
InputStream is = new ByteArrayInputStream(((String) obj).getBytes("iso-8859-1"));
Muito Grato pela solução disponibilizada.
Ola, estou criando um webservices com a função parecida da sua solução Eduardo Bregaida.
queria deixar uma alteração que fiz devido a uma problema ao carregar alguns dos arquivos XMLs, eu alterei a seguinte linha mudando o encoding:InputStream is = new ByteArrayInputStream(((String) obj).getBytes("iso-8859-1"));Muito Grato pela solução disponibilizada.
Perfeito, obrigado
Olá galera, preciso de um help
Estou tentando acessar o Gmail
public static final String PASTA_XML = "C:\\Trabalhos\\XML\\";
public static final String IMAP = "imaps";
public static final String HOST = "imap.gmail.com";
public static final int PORTA = 993;
public static final String ARQUIVO_MSG = "Inbox";
public static final String LOGIN = "[email removido]";
public static final String SENHA = "*******";
public static final String PASTA_PRINCIPAL = "Inbox";
public static final String PASTA_BACKUP = "backup";
e está dando o seguinte erro
[color=red]javax.mail.MessagingException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target;
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.imap.IMAPStore.protocolConnect(IMAPStore.java:670)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at br.com.email.dados.email.ManipularEmail.conectar(ManipularEmail.java:42)
at br.com.email.dados.acao.ReadEmails.(ReadEmails.java:51)
at br.com.email.dados.main.PrincipalNfe.main(PrincipalNfe.java:22)
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[/color]
Consegui resolver
Antes da Conexão precisa configurar o Properties para aceitar todos os TrustStore
[color=red]MailSSLSocketFactory socketFactory= new MailSSLSocketFactory();
socketFactory.setTrustAllHosts(true);
prop.put(“mail.imaps.ssl.socketFactory”, socketFactory);[/color]
Valeu, funcionou perfeito obrigado
Consegui resolverAntes da Conexão precisa configurar o Properties para aceitar todos os TrustStore
[color=red]MailSSLSocketFactory socketFactory= new MailSSLSocketFactory(); socketFactory.setTrustAllHosts(true); prop.put(“mail.imaps.ssl.socketFactory”, socketFactory);[/color]Valeu, funcionou perfeito obrigado
Com Gmail ajudei uma pessoa um tempo atrás ficou assim:
Helcio, demorou mas consegui, tenta assim:
//Gmail
public static final String PASTA_XML = "c:/SuaPasta";
public static final String IMAP = "imaps";
public static final String HOST = "imap.gmail.com";
public static final int PORTA = 993;
public static final String ARQUIVO_MSG = "Inbox";
public static final String LOGIN = "[email removido]";
public static final String SENHA = "suaSenha";
public static final String PASTA_PRINCIPAL = "Inbox";
public static final String PASTA_BACKUP = "backup";
Vi que resolveu seu problema, mas fica a dica para futuros problemas que alguém tiver. 