Galera to me quebrando para ler e-mails e pegar somente o anexo e jogar ele para uma pasta, alguém já usou algo parecido? vi uns tutoriais mais nunhum funcionou!!!
Ler emails e pegar o anexo
D
5 Respostas
M
acho que isso ajuda.
D
Tá dando erro
Minha Classe de teste
package com.br.isdra.mail.recebendo;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;
public class Receiver {
public static void main(String args[]) {
try {
String popServer = "100.100.100.1"; //Ip do servidor de emails
String popUser = "[email removido]"; //O email.
String popPassword = "teste1"; //A senha de acesso
boolean ssl = true; //Se a conexao usa ou nao ssl.
receive(popServer, popUser, popPassword, ssl);
} catch (Exception ex) {
System.out.println("Usage: java com.lotontech.mail.SimpleReceiver" + " popServer popUser popPassword");
}
System.exit(0);
}
public static void receive(String popServer, String popUser, String popPassword, boolean isSsl) {
Store store = null;
Folder folder = null;
try {
// -- Get hold of the default session --
Properties props = System.getProperties();
Session session = Session.getDefaultInstance(props, null);
if (isSsl) {
session.getProperties().put("mail.smtp.auth", "true");
session.getProperties().put("mail.debug", "true");
session.getProperties().put("mail.smtp.port", "25");
session.getProperties().put("mail.smtp.socketFactory.port", "995");
session.getProperties().put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
session.getProperties().put("mail.smtp.socketFactory.fallback", "true");
session.getProperties().put("mail.smtp.starttls.enable", "true");
}
// -- Get hold of a POP3 message store, and connect to it --
store = session.getStore("pop3");
store.connect(popServer, popUser, popPassword);
// -- Try to get hold of the default folder --
folder = store.getDefaultFolder();
if (folder == null) {
throw new Exception("No default folder");
}
// -- ...and its INBOX --
folder = folder.getFolder("INBOX");
if (folder == null) {
throw new Exception("No POP3 INBOX");
}
// -- Open the folder for read only --
folder.open(Folder.READ_ONLY);
// -- Get the message wrappers and process them --
Message[] msgs = folder.getMessages();
for (int msgNum = 0; msgNum < msgs.length; msgNum++) {
printMessage(msgs[msgNum]);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
// -- Close down nicely --
try {
if (folder != null) {
folder.close(false);
}
if (store != null) {
store.close();
}
} catch (Exception ex2) {
ex2.printStackTrace();
}
}
}
public static void printMessage(Message message) {
try {
// Get the header information
String from = ((InternetAddress) message.getFrom()[0]).getPersonal();
if (from == null) {
from = ((InternetAddress) message.getFrom()[0]).getAddress();
}
System.out.println("FROM: " + from);
String subject = message.getSubject();
System.out.println("SUBJECT: " + subject);
Date dataa = message.getReceivedDate();
System.out.println("Numero da MSG: " + message.getMessageNumber());
System.out.println("Recebido em: " + dataa);
// -- Get the message part (i.e. the message itself) --
Part messagePart = message;
Object content = messagePart.getContent();
// -- or its first body part if it is a multipart message --
if (content instanceof Multipart) {
messagePart = ((Multipart) content).getBodyPart(0);
System.out.println("[ Multipart Message ]");
}
// -- Get the content type --
String contentType = messagePart.getContentType();
// -- If the content is plain text, we can print it --
System.out.println("CONTENT:" + contentType);
if (contentType.startsWith("text/plain") || contentType.startsWith("text/html")) {
InputStream is = messagePart.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String thisLine = reader.readLine();
while (thisLine != null) {
System.out.println(thisLine);
thisLine = reader.readLine();
}
}
System.out.println("-----------------------------");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
ERRO
javax.mail.AuthenticationFailedException: only valid after entering TLS mode
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:208)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at com.br.isdra.mail.recebendo.Receiver.receive(Receiver.java:42)
at com.br.isdra.mail.recebendo.Receiver.main(Receiver.java:16)
M
esta dando falha de autenticacao, verifique as configuracoes da conta.
D
Consegui fazer funcionar o recebimentos de e-mails e consigo verificar se tem anexos, só estou com problemas para extrair o anexo.
package com.br.isdra.mail;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.FetchProfile;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.ContentType;
import javax.mail.internet.ParseException;
import com.sun.mail.pop3.POP3SSLStore;
import com.sun.mail.util.MailSSLSocketFactory;
public class RecebendoEmails {
private Session session = null;
private Store store = null;
private String username, password;
private Folder folder;
public void setUsuarioSenha(String username, String password) {
this.username = username;
this.password = password;
}
public void connect() throws Exception {
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", "110");
pop3Props.setProperty("mail.pop3.socketFactory.port", "995");
MailSSLSocketFactory sf=null;
try
{
sf = new MailSSLSocketFactory();
}
catch (GeneralSecurityException e1)
{
e1.printStackTrace();
}
sf.setTrustAllHosts(true);
pop3Props.put("mail.pop3.ssl.enable", "true");
pop3Props.put("mail.pop3.ssl.socketFactory", sf);
URLName url = new URLName("pop3", "100.100.100.8", 995, "",username, password);
session = Session.getInstance(pop3Props, null);
store = new POP3SSLStore(session, url);
store.connect();
}
public void abrirCaixaEntrada(String folderName) throws Exception {
// Abra a pasta de e-mails
folder = store.getDefaultFolder();
folder = folder.getFolder(folderName);
if (folder == null) {
throw new Exception("Pacote Inválido");
}
// Tentar abrir para leitura / gravação e se isso falhar, tentar invisível
try {
folder.open(Folder.READ_WRITE);
} catch (MessagingException ex) {
folder.open(Folder.READ_ONLY);
}
}
public void mostrarTodasMensagens() throws Exception {
// Atributos e bandeiras de todas as mensagens ..
Message[] msgs = folder.getMessages();
// Use uma FetchProfile adequado
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
folder.fetch(msgs, fp);
for (int i = 0; i < msgs.length; i++) {
System.out.println("--------------------------");
System.out.println("MENSAGEM #" + (i + 1) + ":");
if (msgs[i] instanceof Message)
pr(" ");
Address[] a;
String remetente = "";
// FROM
if ((a = msgs[i].getFrom()) != null) {
for (int j = 0; j < a.length; j++){
pr("DE: " + a[j].toString());
remetente = a[j].toString();
}
}
// TO
String destinatario = "";
if ((a = msgs[i].getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < a.length; j++) {
pr("PARA: " + a[j].toString());
destinatario = a[j].toString();
}
}
// SUBJECT
pr("ASSUNTO: " + msgs[i].getSubject());
// DATE
Date d = msgs[i].getSentDate();
pr("Enviado Dia: " +
(d != null ? d.toString() : "UNKNOWN"));
String ct = msgs[i].getContentType();
try {
if(ct.contains("multipart/mixed")){
pr("CONTENT-TYPE: " + (new ContentType(ct)).toString() + " tem anexo");
if(destinatario.contains("[email removido]")){
String nomeArquivo = msgs[i].getFileName();
if(nomeArquivo != null) {
FileOutputStream fileOutputStream = new FileOutputStream("\\teste\\anexo" + msgs[i].getFileName());
Object obj = msgs[i].getContent();
if (obj instanceof InputStream) {
InputStream is = (InputStream) obj;
int ch = -1;
while ((ch = is.read()) != -1) {
fileOutputStream.write(ch);
}
}
}
}
}else{
pr("CONTENT-TYPE: " + (new ContentType(ct)).toString() + " ñ tem anexo");
}
} catch (ParseException pex) {
pr("BAD CONTENT-TYPE: " + ct);
}finally{
store.close();
}
/*
* Using isMimeType to determine the content type avoids
* fetching the actual content data until we need it.
*/
if (msgs[i].isMimeType("text/plain")) {
pr("Este é um texto simples");
pr("---------------------------");
System.out.println((String)msgs[i].getContent());
} else {
// just a separator
pr("---------------------------");
}
}
}
public int getQtdMensagens() throws Exception {
return folder.getMessageCount();
}
public int getQtdNovasMensagens() throws Exception {
return folder.getNewMessageCount();
}
static String indentStr = " ";
static int level = 0;
/**
* Imprimir uma, possivelmente recuado string.
*/
public static void pr(String s) {
System.out.print(indentStr.substring(0, level * 2));
System.out.println(s);
}
}
D
Coloquei agora o código para salvar na pasta mais não está pegando o nome do anexo e nem o conteúdo do anexo está correto
package com.br.isdra.mail;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.FetchProfile;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.ContentType;
import javax.mail.internet.ParseException;
import com.sun.mail.pop3.POP3SSLStore;
import com.sun.mail.util.MailSSLSocketFactory;
public class RecebendoEmails {
private Session session = null;
private Store store = null;
private String username, password;
private Folder folder;
public void setUsuarioSenha(String username, String password) {
this.username = username;
this.password = password;
}
public void connect() throws Exception {
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", "110");
pop3Props.setProperty("mail.pop3.socketFactory.port", "995");
MailSSLSocketFactory sf=null;
try
{
sf = new MailSSLSocketFactory();
}
catch (GeneralSecurityException e1)
{
e1.printStackTrace();
}
sf.setTrustAllHosts(true);
pop3Props.put("mail.pop3.ssl.enable", "true");
pop3Props.put("mail.pop3.ssl.socketFactory", sf);
URLName url = new URLName("pop3", "100.100.100.8", 995, "",username, password);
session = Session.getInstance(pop3Props, null);
store = new POP3SSLStore(session, url);
store.connect();
}
public void abrirCaixaEntrada(String folderName) throws Exception {
// Abra a pasta de e-mails
folder = store.getDefaultFolder();
folder = folder.getFolder(folderName);
if (folder == null) {
throw new Exception("Pacote Inválido");
}
// Tentar abrir para leitura / gravação e se isso falhar, tentar invisível
try {
folder.open(Folder.READ_WRITE);
} catch (MessagingException ex) {
folder.open(Folder.READ_ONLY);
}
}
public void mostrarTodasMensagens() throws Exception {
// Atributos e bandeiras de todas as mensagens ..
Message[] msgs = folder.getMessages();
// Use uma FetchProfile adequado
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
folder.fetch(msgs, fp);
for (int i = 0; i < msgs.length; i++) {
System.out.println("--------------------------");
System.out.println("MENSAGEM #" + (i + 1) + ":");
if (msgs[i] instanceof Message)
pr(" ");
Address[] a;
String remetente = "";
// FROM
if ((a = msgs[i].getFrom()) != null) {
for (int j = 0; j < a.length; j++){
pr("DE: " + a[j].toString());
remetente = a[j].toString();
}
}
// TO
String destinatario = "";
if ((a = msgs[i].getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < a.length; j++) {
pr("PARA: " + a[j].toString());
destinatario = a[j].toString();
}
}
// SUBJECT
pr("ASSUNTO: " + msgs[i].getSubject());
// DATE
Date d = msgs[i].getSentDate();
pr("Enviado Dia: " +
(d != null ? d.toString() : "UNKNOWN"));
String ct = msgs[i].getContentType();
try {
if(ct.contains("multipart/mixed")){
pr("CONTENT-TYPE: " + (new ContentType(ct)).toString() + " tem anexo");
if(destinatario.contains("[email removido]")){
try {
InputStream is = msgs[i].getInputStream();
File temp = new File("\\teste\\anexo\\");
if (!temp.exists()) {
if (!temp.mkdir()) {
System.out.println("false");
}
}
FileOutputStream fos = new FileOutputStream("\\teste\\anexo\\" + msgs[i].getFileName() + ".xls");
int x = -1;
while ((x = is.read()) != -1) {
fos.write((char) x);
}
fos.flush();
fos.close();
System.out.println("true");
} catch (IOException e) {
e.printStackTrace();
System.out.println("false");
} catch (MessagingException e) {
e.printStackTrace();
System.out.println("false");
} catch (Throwable e) {
e.printStackTrace();
System.out.println("false");
}
}
}else{
pr("CONTENT-TYPE: " + (new ContentType(ct)).toString() + " ñ tem anexo");
}
} catch (ParseException pex) {
pr("BAD CONTENT-TYPE: " + ct);
}finally{
store.close();
}
/*
* Using isMimeType to determine the content type avoids
* fetching the actual content data until we need it.
*/
if (msgs[i].isMimeType("text/plain")) {
pr("Este é um texto simples");
pr("---------------------------");
System.out.println((String)msgs[i].getContent());
} else {
// just a separator
pr("---------------------------");
}
}
}
public int getQtdMensagens() throws Exception {
return folder.getMessageCount();
}
public int getQtdNovasMensagens() throws Exception {
return folder.getNewMessageCount();
}
static String indentStr = " ";
static int level = 0;
/**
* Imprimir uma, possivelmente recuado string.
*/
public static void pr(String s) {
System.out.print(indentStr.substring(0, level * 2));
System.out.println(s);
}
}
Criado 26 de dezembro de 2011
Ultima resposta 27 de dez. de 2011
Respostas 5
Participantes 2