i want to delete messages from speicifc sender in my INBOX folder using java.
Here i found this code to get all emails from gmail.
How can i get the specific sender (sender#gmail.com) and delete it or move it to trash folder.
Thank you
Code:
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.pop3.POP3Folder;
import java.util.Properties;
import javax.mail.Flags;
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("pop3s");
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 = "myemail#gmail.com";// change accordingly
String password = "password";// change accordingly
check(host, mailStoreType, username, password);
}
}
Using Gmail's RESTful API this is possible
Users.messages: list to get the messages
and
Users.messages: trash to send to trash
Related
I'm trying to create a Java application that only receives emails from my private email (not gmail), but I keep getting errors, whether it's a connection failed or SSL handshake problems, the last error I got is:
Javax net SSL sslhandshakeexception Remote host terminated the handshake.
My java class is :
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 CheckingMail {
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.pop3s.ssl.protocols", "TLSv1.2");
properties.setProperty("mail.pop3.ssl.trust", "*"); // Trust all Servers
properties.setProperty("mail.pop3.ssl.trust", "private hostname"); // Trust all Servers
Session emailSession = Session.getDefaultInstance(properties);
//create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("pop3s");
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 = "private host name";// change accordingly
String mailStoreType = "pop3";
String username = "my email";// change accordingly
String password = "my password";// change accordingly
check(host, mailStoreType, username, password);
}
}
I'm trying to get all mails of my gmail but I can only get 250. According to https://javaee.github.io/javamail/FAQ#gmailsettings, I had already set the number of mail limit to 1000 but it still only fetch 250 mails. Here's my code
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 Getreply {
public static void check() {
String host = "pop.gmail.com";
String mailStoreType = "pop3";
String username = "";
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("pop3s");
store.connect(host, username, 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];
Object body = message.getContent();
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: " + body );
}
//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();
}
}
}
Does anyone know how can I get all?
Check your POP settings in Gmail or switch to IMAP.
I have just test it if you have no need to use pop you should try imap
your chech method will be like this below. Idid test it i can my mails without restriction. But also if you configure your gmail account for a specific number you will receive that number.
public static void check() {
String host = "imap.gmail.com";
String username = "user";
String password = "passwd";
try {
//create properties field
Properties properties = new Properties();
properties.setProperty("mail.imap.ssl.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
//create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("imap");
store.connect(host, username, 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];
Object body = message.getContent();
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: " + body );
}
//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();
}
}
I am using Java Mail API along with the following code to read email from my gmail account.
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 CheckMails {
public static void check(String host, String storeType, String user,
String password)
{
try {
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("pop3s");
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 = "myemai#gmail.com";// change accordingly
String password = "*******";// change accordingly
check(host, mailStoreType, username, password);
}
}
But I am getting the following exceptions:
javax.mail.AuthenticationFailedException: [AUTH] Web login required: ` https://support.google.com/mail/bin/answer.py?answer=78754`
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:209)
at javax.mail.Service.connect(Service.java:364)
at javax.mail.Service.connect(Service.java:245)
at CheckMails.check(CheckMails.java:26)
at CheckMails.main(CheckMails.java:66)
But i have recieved an email from gmail in my inbox which is saying that
"We recently blocked-in a sign in attempt to your Google Account".
How can i make the program to work properly?
Change Your emailSession variable with
Session emailSession = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
As said by Gmail
Some apps and devices use less secure sign-in technology, which makes
your account more vulnerable. You can turn off access for these apps,
which we recommend, or turn on access if you want to use them despite
the risks. Learn more
Just click below link and disable Gmail security settings.It will work.
Disable Security settings
Here is a nice article about Password Authentication in Java Mail Api
We can read messages from gmail inbox but can we read from a label?
If I take the following example from http://harikrishnan83.wordpress.com/2009/01/24/access-gmail-with-imap-using-java-mail-api/
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 InboxReader {
public static void main(String args[]) {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "<username>", "password");
System.out.println(store);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for(Message message:messages) {
System.out.println(message);
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}
}
}
If I change "inbox" by a label name it's throwing an error: inbox is not found.
Any help, please?
Try the following code which is working for me :
store.getFolder("FolderNameGoesHere");
private static Store getConnection() throws MessagingException {
Properties properties;
Session session;
Store store;
properties = new Properties();
properties.setProperty("mail.host", "imap.gmail.com");
properties.setProperty("mail.port", "995");
properties.setProperty("mail.transport.protocol", "imaps");
session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("dummy#gmail.com",
"dummy");
}
});
store = session.getStore("imaps");
store.connect();
return store;
}
public static boolean isMailReceivedBySubject(String subject,String folder) throws MessagingException {
Store store = null;
boolean emailReceived = false;
try {
store = getConnection();
Folder mailFolder = store.getFolder(folder);
mailFolder.open(Folder.READ_WRITE);
SearchTerm st = new AndTerm(new SubjectTerm(subject), new BodyTerm(subject));
Message[] messages = mailFolder.search(st);
for (Message message : messages) {
System.out.println("message : " + message.getSubject());
if (message.getSubject().contains(subject)) {
System.out.println("Found the email subject : " + subject);
emailReceived = true;
break;
}
}
return emailReceived;
}finally {
if (store != null) {
store.close();
}
}
}
i want to insert the result of my coding to database, how can i do it?
i have a coding that use java mail to get email, the code run successfully, but then i want to store it (the email) to my database.
this is my code :
package ta_aing;
import com.mysql.jdbc.PreparedStatement;
import java.util.*;
import javax.mail.*;
import java.sql.Connection;
import java.sql.Statement;
import ta_aing.connection;
public class baca_email {
public static void main(String[] args) {
Properties props = new Properties();
connection datMan = new connection();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap.gmail.com", "email", "password");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message msg = inbox.getMessage(inbox.getMessageCount());
Address[] in = msg.getFrom();
for (Address address : in) {
System.out.println("FROM:" + address.toString());
}
Multipart mp = (Multipart) msg.getContent();
BodyPart bp = mp.getBodyPart(0);
System.out.println("SENT DATE:" + msg.getSentDate());
System.out.println("SUBJECT:" + msg.getSubject());
System.out.println("CONTENT:" + bp.getContent());
String sql = "insert into email (sender, sent_date, subject, content) values (address.toString, msg.getSentDate,msg.getSubject,bp.getContent)";
Connection conn;
conn = datMan.logOn();
PreparedStatement statement;
} catch (Exception mex) {
mex.printStackTrace();
}
}
}
DO not set the attributes in query string, use ? instead for prepared statement, JDBC pools the prepared statements and changes the values of ? on the fly to save space. putting it in query defeats the purpose.
String sql = "insert into email (sender, sent_date, subject, content) values (" +
"?, ?,?,?)";
PreparedStatement statement = con.prepareStatement(updateString);
statement.setString(1,address.toString());
statement.setString(2,msg.toString());
statement.setString(3,msg.getSubject());
statement.setString(4,bp.getContent());
statement.executeQuery();
just use
Statement s = conn.createStatement();
s.executeUpdate(sql);
the conn is object for the connection with database
this is how i done with it.. thanks for all who trying to helping..
package ta_aing;
import com.mysql.jdbc.PreparedStatement;
import java.util.*;
import javax.mail.*;
import java.sql.Connection;
import java.sql.Statement;
import ta_aing.connection;
/**
*
* #author Yoas
*/
public class cobaaaaa {
public static void main(String[] args) {
Properties props = new Properties();
connection datMan = new connection();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap.gmail.com", "email", "password");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
System.out.println(inbox.getMessageCount());
Message [] msg = inbox.getMessages();
Connection conn;
conn = datMan.logOn();
for (int c=0;c<msg.length;c++){
Address[] in = msg[c].getFrom();
for (Address address : in) {
System.out.println("FROM:" + address.toString());
}
Multipart mp = (Multipart) msg[c].getContent();
BodyPart bp = mp.getBodyPart(0);
System.out.println("SENT DATE:" + msg[c].getSentDate());
System.out.println("SUBJECT:" + msg[c].getSubject());
System.out.println("CONTENT:" + bp.getContent());
Statement st;
st = (Statement) conn.createStatement();
for(int i = 0;i<in.length;i++){
st.executeUpdate("insert into email values(null,'"+in[i].toString()+"','"+msg[c].toString()+"','"+msg[c].getSubject()+"','"+bp.getContent()+"')");
}
}
conn.close();
} catch (Exception mex) {
mex.printStackTrace();
}
}
}