Bom Dia Pessoal, estou fazendo um programa que lê a caixa de entrada de uma conta de e-mail e verifica seus anexos, porém, nesta conta recebo alguns e-mails com codificação de em base de 64 bits e quando meu programa lê esse e-mail apresenta o erro abaixo:
Exception in thread “Timer-0” java.lang.ClassCastException: om.sun.mail.util.BASE64DecoderStream cannot be cast to javax.mail.Multipart
Ja pesquisei e não consegui encontrar algo concreto para resolver meu problema.
O erro acusa para a linha: multipart = (Multipart) message[i].getContent();
Peço ajuda para tal problema.
Segue abaixo a classe que lê os e-mail:
package leremail;
import java.io.IOException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.activation.DataHandler;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
public class verificaEmail {
Session session;
Store store;
Folder folder;
Part part;
Message message[];
Authenticator authenticator;
int contador_email = 0;
String data_email, hora_email;
String extensao_arquivo;
public int verificaEmailServidor(String servidor, String usuario, String senha, String pasta_email) throws NoSuchProviderException, SQLException {
// String extensao_arquivo;
String nome_arquivo;
// Classe para copiar os arquivos
CopiaXMLPathComum copiaXMLPathComum = new CopiaXMLPathComum();
ImprimeXML ixml = new ImprimeXML();
Properties properties = System.getProperties();
session = Session.getDefaultInstance(properties);
// Informa qual protocolo utilizar para comunicação com o Servidor
store = session.getStore("pop3");
try {
// passa ao conector usuario, senha e servidor para conexao
store.connect(servidor, usuario, senha);
// selecione a caixa de entrada
folder = store.getFolder(pasta_email); //INBOX
if (!folder.exists()) {
System.out.println("Nao existe:" + pasta_email + "! Verifique o nome correto da Caixa de Entrada! Saindo");
} else {
folder.open(Folder.READ_WRITE);
message = folder.getMessages();
for (int i = 0; i < message.length; i++) {
// Data de recebimento
Date sent = message[i].getSentDate();
if (sent != null) {
System.out.println("Sent: " + sent);
}
data_email = new SimpleDateFormat("dd/MM/yyyy").format(sent);
hora_email = new SimpleDateFormat("HH:mm:ss").format(sent);
byte[] buf = new byte[4096];
// Captura os Anexos no e-mail e salva em uma pasta temporaria no computador do usuario
Multipart multipart;
try {
multipart = (Multipart) message[i].getContent();
for (int x = 0; x < multipart.getCount(); x++) {
BodyPart bodyPart = multipart.getBodyPart(x);
String anexo = bodyPart.getDisposition();
if (anexo != null && (anexo.equals(BodyPart.ATTACHMENT))) {
DataHandler handler = bodyPart.getDataHandler();
nome_arquivo = handler.getName();
extensao_arquivo = handler.getName();
extensao_arquivo = extensao_arquivo.substring(extensao_arquivo.length() - 3, extensao_arquivo.length());
if (extensao_arquivo.toUpperCase().equals("XML")) {
InputStream is = multipart.getBodyPart(x).getInputStream();
FileOutputStream fos = new FileOutputStream("C:\\temp\\" + nome_arquivo);
int bytesRead;
while ((bytesRead = is.read(buf)) != -1) {
fos.write(buf, 0, bytesRead);
}
fos.close(); // Fecha o arquivo da pasta temp para ser renomeado e copiado ao path_comum
contador_email++; // essa linha eh nova, apagar caso voltar o codigo antigo aqui
// Imprime automaticamente o XML
//ixml.Imprime("C:\\temp\\" + nome_arquivo);
copiaXMLPathComum.CopiaXML("C:\\temp\\", "R:\\celular\\", data_email, hora_email);
} else {
//System.out.println("Anexo não é XML, pulando...");
}
extensao_arquivo = null;
}
message[i].setFlag(Flags.Flag.DELETED, true);
}
} catch (IOException ex) {
Logger.getLogger(verificaEmail.class.getName()).log(Level.SEVERE, null, ex);
}
}
folder.close(true);
store.close();
}
} catch (MessagingException ex) {
Logger.getLogger(verificaEmail.class.getName()).log(Level.SEVERE, null, ex);
}
return contador_email;
}
}