This method gives the number of emails in the inbox.But it gives me this exception :
javax.mail.MessagingException: Connect failed;
nested exception is:
java.net.ConnectException: Connection timed out: connecterror
-
Session session = Session.getInstance(new Properties());
try {
Store store = session.getStore("pop3");
store.connect("pop.gmail.com" , "username" , "password");
Folder fldr = store.getFolder("INBOX");
fldr.open(Folder.READ_WRITE);
int count = fldr.getMessageCount();
System.out.println(count);
} catch(Exception exc) {
System.out.println(exc + "error");
}
Try this :
Properties props = new Properties();
props.put("mail.pop3.host" , "pop.gmail.com");
props.put("mail.pop3.user" , "username");
// Start SSL connection
props.put("mail.pop3.socketFactory" , 995 );
props.put("mail.pop3.socketFactory.class" , "javax.net.ssl.SSLSocketFactory" );
props.put("mail.pop3.port" , 995);
Session session = Session.getDefaultInstance(props , new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication( "username" , "password");
}
});
try {
Store store = session.getStore("pop3");
store.connect("pop.gmail.com" , "username" , "password");
Folder fldr = store.getFolder("INBOX");
fldr.open(Folder.HOLDS_MESSAGES);
int count = fldr.getMessageCount();
System.out.println(count);
} catch(Exception exc) {
System.out.println(exc + " error");
}
Also visit this question
Probably because the server refuses to connect.
Try connecting from "telnet". Once you can connect at all, then you should be able to connect from your Java program.
Here are some troubleshooting tips:
http://www.anta.net/misc/telnet-troubleshooting/pop.shtml
https://www-304.ibm.com/support/docview.wss?uid=swg21097014
http://support.microsoft.com/kb/885685
Try changing
store.connect("pop.gmail.com" , "username" , "password");
to
store.connect("pop.gmail.com" , 995, "username" , "password");
Disclaimer: I have not tested this.
Gmail requires a secure SSL connection, and maybe javax.mail.Service isn't providing that. I think the more likely explanation, though, is that you're simply not connecting to the right port, so I've explicitly specified the correct port number for Gmail's POP3 service.
Try following a "how to use gmail as an smtp server" tutorial. Google also has a configuration page with all the settings you'll need.
Related
I am trying to write a simple program in Java, in order to check my mailbox and get whatever email is in the inbox.
I have read various tutorials and watched a video in youtube and I found out that most people do something similar to this
So the I have taken the code found there:
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
public class CheckingMails {
public static void check(String host, String storeType, String user,
String password)
{
try {
//create properties field
Properties properties = new Properties();
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
//create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("pop3");
store.connect(host, user, password);
//create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
//close the store and folder objects
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String host = "pop.gmail.com";// change accordingly
String mailStoreType = "pop3";
String username = "giannisthedrummer2#gmail.com";// change accordingly
String password = "********";// change accordingly
check(host, mailStoreType, username, password);
}
}
But I can't get my mails. Instead this error appears:
javax.mail.AuthenticationFailedException: EOF on socket
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:104)
at javax.mail.Service.connect(Service.java:233)
at javax.mail.Service.connect(Service.java:134)
at CheckingMails.check(CheckingMails.java:29)
at CheckingMails.main(CheckingMails.java:69)
I have enabled the POP and IMAP accesibility features on my email, as well as enabled less secure connections.
I downloaded the necessary .jar files from mail.jar and activation.jar
After looking around a bit, I found out that the issue probably is coming from Google's side, meaning that the authentication is going worng. The password and the name is correct (I have checked that multiple times). I have enabled both IMAP and POP connections and I have allowed less secure connections, but still I get an javax.mail.AuthenticationFailedException error.
Any ideas why is this happening?
You're connecting on the SSL port but not enabling SSL. Follow the Gmail instructions in the JavaMail FAQ. Get rid of the port setting and set mail.pop3.ssl.enable.
And make sure you understand the limitations of pop3 vs. imap.
do below change to your Gmail account to access it from outside
Login to Gmail.
Access the URL as https://www.google.com/settings/security/lesssecureapps
Select "Turn on"
For the people that will struggle in the future in the same way I did:
After applying the suggestion from Bill Shannon, I got another error,which I found out that it was coming due to the fact that I hadn't configure the ssl certificates properly. Since I have little to no clue about those, I was searching around the internet to find
Properties properties = new Properties();
properties.put("mail.imap.host", host);
properties.put("mail.imap.user", user);
properties.setProperty("mail.imap.ssl.enable", "true");
properties.put("mail.imap.ssl.trust", "*");
I changed the pop3 protocol to IMAP, because the later allows me to perform more tasks, but for the sole purpose of retrieving my emails both work in the same way.
The last line, in my understanding will accept any certificate, which probably is not the right way to go about it, but at the moment I don't know which one is the correct one.
Thank you all for your help.
****** It is important that the user, enables the POP3/IMAP connections in their accounts and also turn on the less secure applications, as it was stated previously. ******
I try to access email account on a certain email server via "imap" through java mail. I did some research on this. And I find the following code which works for gmail.
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
public class DeleteMessageExample {
public static void main (String args[]) throws Exception {
String host = args[0];
String username = args[1];
String password = args[2];
// Get session
Session session = Session.getInstance(
System.getProperties(), null);
// Get the store
Store store = session.getStore("imaps");
store.connect(host, username, password);
// Get folder
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
BufferedReader reader = new BufferedReader (
new InputStreamReader(System.in));
// 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());
System.out.println("Do you want to delete message? [YES to delete]");
String line = reader.readLine();
// Mark as deleted if appropriate
if ("YES".equals(line)) {
message[i].setFlag(Flags.Flag.DELETED, true);
}
}
// Close connection
folder.close(true);
store.close();
}
}
However, I need to specify the args[0] to be imap.gmail.com args[1] to be usrname, args[2] to be password. And if I replace imap.gmail.com by the ip address 74.125.224.86, it no longer work.
My question is suppose I have an account on yahoo mail, what the hostname I should use?
I tried imap.yahoo.com, mail.yahoo.com and the ip address.
If you know the answer, would you mind also told me what is the regular rule to find out what kind hostname I should use?
Thanks a lot.
Unlike Gmail, Yahoo Mail's IMAP services is not a totally standard IMAP service. You need send some special tokens before you login. You need to modify the JavaMail API in order to connect to Yahoo Mail through IMAP. The latest JavaMail 1.4.4-SNAPSHOT release supports Yahoo Mail as well. You can get it here
i'm want to store emails from Gmail into my mysql database.
i found Inboxreader with google but the part for connection to mysql is not working.
the username, database name, password is correct.
can anyone help me.
Thank you.
here is the part of the code
{
Properties details= new Properties();
details.load(new FileInputStream("details.properties"));
String userName = details.getProperty("root");
String password = details.getProperty("password");
String url = details.getProperty("jdbc:mysql://localhost/test");
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
PreparedStatement st= conn.prepareStatement("insert into 'Email_list' values(?)");
for(String mail:mails)
{
try{
st.setString(1, mail);
st.execute();
}catch(Exception e){}
}
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
e.printStackTrace();
}
finally
Here is the error code:
Cannot connect to database server
java.sql.SQLException: The url cannot be null
Reading:23
at java.sql.DriverManager.getConnection(DriverManager.java:554)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at inboxreader.InboxReader.connecttoMySql(InboxReader.java:181)
at inboxreader.InboxReader.Start(InboxReader.java:82)
at inboxreader.InboxReader.main(InboxReader.java:34)
Thank you
This is your problem:
String url = details.getProperty("jdbc:mysql://localhost/test");
You are getting a null value in url. That's because there is no property called jdbc:mysql://localhost/test in your properties file.
You have two options. One would be using url directly with something like:
String url = "jdbc:mysql://localhost/test";
The other option would be having a correctly set up property in details.properties:
# hello, I am details.properties file
jdbc.url=jdbc:mysql://localhost/test
Then, in your Java code you would read url from property like this:
String url = details.getProperty("jdbc.url"); // note that we're changing property name
You're trying to get the value of a property from details like this:
String url = details.getProperty("jdbc:mysql://localhost/test");
It seems to me that the name of the property there is actually your value.
Thats because you don't have one key "jdbc:mysql://localhost/test" in your properties file. Let's say that details.properties have this content:
url=jdbc:mysql://localhost/test
So your code should be
String url = details.getProperty("url");
I am sure that your property key ha issue :
String url = details.getProperty("jdbc:mysql://localhost/test");
You should first validate that weather you have correct key or not
if (details.getProperty("jdbc:mysql://localhost/test") != null ||
details.getProperty("jdbc:mysql://localhost/test").trim().length > 0){
url =details.getProperty("jdbc:mysql://localhost/test");
}else{
return new Exception("Wrong property key");
}
The code below uses javamail API to access gmail,
String host = "pop.gmail.com";
int port = 995;
Properties properties = new Properties();
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
final javax.mail.Session session = javax.mail.Session.getInstance(properties);
store = session.getStore("pop3s");
store.connect(host, port, mCredentialaNme, mCredentialApss);
// ***************************************************************
Folder personalFolders[] = store.getDefaultFolder().list( "*" );
// ***************************************************************
for (Folder object : personalFolders) {
// ***********************************
System.out.println( object.list("*") );
// ***********************************
if ((object.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0){
object.open(Folder.READ_ONLY);
Message messes[] = object.getMessages();
System.out.println(object.getFullName());
System.out.println("====================");
for (Message object1 : messes) {
System.out.println(object1.getFrom() + " - " + object1.getSubject());
}
object.close(false);
}
}
if (store.isConnected()) {
store.close();
}
The trouble is that this code only lists the INBOX folder whereas there are no less than 20 labels defined.
What should be done to get the code to list/access these nested folders/labels?
Don't use POP, use IMAP if you want labels/folders.
As noted in the javamail docs, due to the nature of the POP protocol, a POP message store always
Contains only one folder, "INBOX".
I am trying to perform a search of my gmail using Java. With JavaMail I can do a message by message search like so:
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "myUsername", "myPassword");
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
SearchTerm term = new SearchTerm() {
#Override
public boolean match(Message mess) {
try {
return mess.getContent().toString().toLowerCase().indexOf("boston") != -1;
} catch (IOException ex) {
Logger.getLogger(JavaMailTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (MessagingException ex) {
Logger.getLogger(JavaMailTest.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
};
Message[] searchResults = inbox.search(term);
for(Message m:searchResults)
System.out.println("MATCHED: " + m.getFrom()[0]);
But this requires downloading each message. Of course I can cache all the results, but this becomes a storage concern with large gmail boxes and also would be very slow (I can only imagine how long it would take to search through gigabytes of text...).
So my question is, is there a way of searching through mail on the server, a la gmail's search field? Maybe through Microsoft Exchange?
Hours of Googling has turned up nothing.
You can let the server do the search for you, with the appropriate IMAP command. The SEARCH command will only get you so far, what you probably need is the SORT command. SORT isn't implemented in JavaMail but the documentation shows how you can implement it yourself:
http://java.sun.com/products/javamail/javadocs/com/sun/mail/imap/IMAPFolder.html#doCommand(com.sun.mail.imap.IMAPFolder.ProtocolCommand)
(I couldn't figure out how to link to a URL with parentheses)
Connect to the Exchange IMAP store and use javax.mail.search.SearchTerm