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);
}
}
How can I connect to remote MySQL database through SSH from java application? Small code example is helpful for me and I'd appreciate this.
My understanding is that you want to access a mysql server running on a remote machine and listening on let's say port 3306 through a SSH tunnel.
To create such a tunnel from port 1234 on your local machine to port 3306 on a remote machine using the command line ssh client, you would type the following command from your local machine:
ssh -L 1234:localhost:3306 mysql.server.remote
To do the same thing from Java, you could use JSch, a Java implementation of SSH2. From its website:
JSch allows you to connect to an sshd server and use port forwarding, X11 forwarding, file transfer, etc., and you can integrate its functionality into your own Java programs. JSch is licensed under BSD style license.
For an example, have a look at PortForwardingL.java. Once the session connected, create your JDBC connection to MySQL using something like jdbc:mysql://localhost:1234/[database] as connection URL.
My detail code is below:
package mypackage;
import java.sql.*;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UpdateMySqlDatabase {
static int lport;
static String rhost;
static int rport;
public static void go(){
String user = "ripon";
String password = "wasim";
String host = "myhost.ripon.wasim";
int port=22;
try
{
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
lport = 4321;
rhost = "localhost";
rport = 3306;
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
int assinged_port=session.setPortForwardingL(lport, rhost, rport);
System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);
}
catch(Exception e){System.err.print(e);}
}
public static void main(String[] args) {
try{
go();
} catch(Exception ex){
ex.printStackTrace();
}
System.out.println("An example for updating a Row from Mysql Database!");
Connection con = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://" + rhost +":" + lport + "/";
String db = "testDB";
String dbUser = "wasim";
String dbPasswd = "riponalwasim123";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, dbUser, dbPasswd);
try{
Statement st = con.createStatement();
String sql = "UPDATE MyTableName " +
"SET email = 'ripon.wasim#smile.com' WHERE email='peace#happy.com'";
int update = st.executeUpdate(sql);
if(update >= 1){
System.out.println("Row is updated.");
}
else{
System.out.println("Row is not updated.");
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
While the existing answers are correct, they obscure the significant code in bloats of other code.
This is the basic code you need to tunnel your JDBC (or any other) database connection through an SSH channel:
String jumpserverHost = "ssh.example.com";
String jumpserverUsername = "sshuser";
// The hostname/IP address and port, you would use on the SSH server
// to connect to the database.
// If the database runs on the same machine as the SSH server, use "localhost".
String databaseHost = "database.example.com";
int databasePort = 3306;
String databaseUsername = "dbuser";
String databasePassword = "dbpass";
JSch jsch = new JSch();
// Public key authentication example
// (but you can use password authentication, if appropriate).
jsch.addIdentity("~/.ssh/id_rsa");
// Connect to SSH jump server (this does not show an authentication code)
Session session = jsch.getSession(jumpserverUsername, jumpserverHost);
session.connect();
// Forward randomly chosen local port through the SSH channel to database host/port
int forwardedPort = session.setPortForwardingL(0, databaseHost, databasePort);
// Connect to the forwarded port (the local end of the SSH tunnel)
// If you don't use JDBC, but another database client,
// just connect it to the localhost:forwardedPort
String url = "jdbc:mysql://localhost:" + forwardedPort;
Connection con =
DriverManager.getConnection(url, databaseUsername, databasePassword);
You will also have to deal with host key verification. For that see:
How to resolve Java UnknownHostKey, while using JSch SFTP library?
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class CTestDriver {
private static void doSshTunnel(String strSshUser, String strSshPassword, String strSshHost, int nSshPort,
String strRemoteHost, int nLocalPort, int nRemotePort) throws JSchException {
final JSch jsch = new JSch();
Session session = jsch.getSession(strSshUser, strSshHost, 22);
session.setPassword(strSshPassword);
final Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
session.setPortForwardingL(nLocalPort, strRemoteHost, nRemotePort);
}
public static void main(String[] args) {
try {
String strSshUser = "ssh_user_name"; // SSH loging username
String strSshPassword = "abcd1234"; // SSH login password
String strSshHost = "your.ssh.hostname.com"; // hostname or ip or
// SSH server
int nSshPort = 22; // remote SSH host port number
String strRemoteHost = "your.database.hostname.com"; // hostname or
// ip of
// your
// database
// server
int nLocalPort = 3366; // local port number use to bind SSH tunnel
int nRemotePort = 3306; // remote port number of your database
String strDbUser = "db_user_name"; // database loging username
String strDbPassword = "4321dcba"; // database login password
CTestDriver.doSshTunnel(strSshUser, strSshPassword, strSshHost, nSshPort, strRemoteHost, nLocalPort,
nRemotePort);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:" + nLocalPort, strDbUser,
strDbPassword);
con.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
System.exit(0);
}
}
}
package framework.restapi.utils;
import java.sql.*;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
public class SQLConnection {
private static Connection connection = null;
private static Session session = null;
private static void connectToServer(String dataBaseName) throws SQLException {
connectSSH();
connectToDataBase(dataBaseName);
}
private static void connectSSH() throws SQLException {
String sshHost = "";
String sshuser = "";
String dbuserName = "";
String dbpassword = "";
String SshKeyFilepath = "/Users/XXXXXX/.ssh/id_rsa";
int localPort = 8740; // any free port can be used
String remoteHost = "127.0.0.1";
int remotePort = 3306;
String localSSHUrl = "localhost";
/***************/
String driverName = "com.mysql.jdbc.Driver";
try {
java.util.Properties config = new java.util.Properties();
JSch jsch = new JSch();
session = jsch.getSession(sshuser, sshHost, 22);
jsch.addIdentity(SshKeyFilepath);
config.put("StrictHostKeyChecking", "no");
config.put("ConnectionAttempts", "3");
session.setConfig(config);
session.connect();
System.out.println("SSH Connected");
Class.forName(driverName).newInstance();
int assinged_port = session.setPortForwardingL(localPort, remoteHost, remotePort);
System.out.println("localhost:" + assinged_port + " -> " + remoteHost + ":" + remotePort);
System.out.println("Port Forwarded");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void connectToDataBase(String dataBaseName) throws SQLException {
String dbuserName = "sf2_showpad_biz";
String dbpassword = "lOAWEnL3K";
int localPort = 8740; // any free port can be used
String localSSHUrl = "localhost";
try {
//mysql database connectivity
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setServerName(localSSHUrl);
dataSource.setPortNumber(localPort);
dataSource.setUser(dbuserName);
dataSource.setAllowMultiQueries(true);
dataSource.setPassword(dbpassword);
dataSource.setDatabaseName(dataBaseName);
connection = dataSource.getConnection();
System.out.print("Connection to server successful!:" + connection + "\n\n");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void closeConnections() {
CloseDataBaseConnection();
CloseSSHConnection();
}
private static void CloseDataBaseConnection() {
try {
if (connection != null && !connection.isClosed()) {
System.out.println("Closing Database Connection");
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void CloseSSHConnection() {
if (session != null && session.isConnected()) {
System.out.println("Closing SSH Connection");
session.disconnect();
}
}
// works ONLY FOR single query (one SELECT or one DELETE etc)
private static ResultSet executeMyQuery(String query, String dataBaseName) {
ResultSet resultSet = null;
try {
connectToServer(dataBaseName);
Statement stmt = connection.createStatement();
resultSet = stmt.executeQuery(query);
System.out.println("Database connection success");
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet;
}
public static void DeleteOrganisationReferencesFromDB(String organisationsLike) {
try {
connectToServer("ServerName");
Statement stmt = connection.createStatement();
ResultSet resultSet = stmt.executeQuery("select * from DB1");
String organisationsToDelete = "";
List<String> organisationsIds = new ArrayList<String>();
// create string with id`s values to delete organisations references
while (resultSet.next()) {
String actualValue = resultSet.getString("id");
organisationsIds.add(actualValue);
}
for (int i = 0; i < organisationsIds.size(); i++) {
organisationsToDelete = " " + organisationsToDelete + organisationsIds.get(i);
if (i != organisationsIds.size() - 1) {
organisationsToDelete = organisationsToDelete + ", ";
}
}
stmt.executeUpdate(" DELETE FROM `DB1`.`table1` WHERE `DB1`.`table1`.`organisation_id` in ( " + organisationsToDelete + " );");
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeConnections();
}
}
public static List<String> getOrganisationsDBNamesBySubdomain(String organisationsLike) {
List<String> organisationDbNames = new ArrayList<String>();
ResultSet resultSet = executeMyQuery("select `DB`.organisation.dbname from `DB1`.organisation where subdomain like '" + organisationsLike + "%'", "DB1");
try {
while (resultSet.next()) {
String actualValue = resultSet.getString("dbname");
organisationDbNames.add(actualValue);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeConnections();
}
return organisationDbNames;
}
public static List<String> getAllDBNames() {
// get all live db names incentral DB
List<String> organisationDbNames = new ArrayList<String>();
ResultSet resultSet = executeMyQuery("show databases", "DB1");
try {
while (resultSet.next()) {
String actualValue = resultSet.getString("Database");
organisationDbNames.add(actualValue);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeConnections();
}
return organisationDbNames;
}
public static void deleteDataBasesByName(List<String> DataBasesNamesList) {
try {
connectSSH();
int dataBasesAmount = DataBasesNamesList.size();
for (int i = 0; i < dataBasesAmount; i++) {
connectToDataBase(DataBasesNamesList.get(i));
Statement stmt = connection.createStatement();
stmt.executeUpdate("DROP database `" + DataBasesNamesList.get(i) + "`");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
CloseDataBaseConnection();
closeConnections();
}
}
}
First of all, thank you works great!
Though, I wonder if I should reuse that Session for every (potentially simultaneous) SQL Connection, or if I should create a new Session every time and only refresh it if for some reason it has expired.
Currently, I would every time I make a connection make a new instance of that Controller here and then do the SQL queries with the connection I got from it, then close it manually.
Would also be nice if I could make the class useable with try-with-resource and it closing itself. Will look into that. Cause I don´t wanna miss closing it.
That´s how the thing looks like, I'm getting DB Connections from right now.
public class ConnectionManager {
private Connection con = null;
private Session session = null;
public Connection getConnection() {
Connection con = null;
var settings = new DbSettingsController();
boolean useSSH = settings.getSetting(SettingKey.UseSSH).equals("true");
String sshPort = settings.getSetting(SettingKey.SSHPort);
String sqlIp = settings.getSetting(SettingKey.MySqlIP);
String sqlPort = settings.getSetting(SettingKey.MySqlPort);
if(useSSH) {
JSch jSch = new JSch();
try {
this.session = jSch.getSession(settings.getSetting(SettingKey.SSHUser),
settings.getSetting(SettingKey.SSHHost),
Integer.valueOf(sshPort));
this.session.setPassword(settings.getSetting(SettingKey.SSHPassword));
this.session.setConfig("StrictHostKeyChecking", "no");
this.session.connect();
this.session.setPortForwardingL(Integer.parseInt(sshPort), sqlIp, Integer.parseInt(sqlPort));
} catch (JSchException e) {
e.printStackTrace();
}
}
var connectionString = String.format("jdbc:mysql://%s:%s/%s?autoReconnect=true&useSSL=false",
sqlIp, useSSH ? sshPort : sqlPort,
settings.getSetting(SettingKey.MySqlShema));
var user = settings.getSetting(SettingKey.MySqlUser);
var password = settings.getSetting(SettingKey.MySqlPassword);
try {
con = DriverManager.getConnection(connectionString, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
public void close() {
if(this.con != null) {
try {
this.con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(this.session != null) {
this.session.disconnect();
}
}
If you wonder DbSettingsController I´ve made myself too, just puts settings in a Text column in a local SQLite DB, with a key assigned to it (that enum´s int value). Was just copy paste code I reused from some other project, so it was simple and fast to just do that this way.
I want my system to notify the admin whenever there is an applicant applying the job through the system. Is it possible to have multiple action in one jsp form? One goes to servlet, another one calls another class to notify the admin via java mail. Or i need to create another submit button that can notify the admin? if so how can i do that with the class below? or is there any way to notify the admin via email?
this is the code to sendemail
package SendEmail;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.internet.MimeMessage;
public class EmailSend {
public static void main(String args[]){
try{
String host ="smtp.gmail.com" ;
String user = "myemail";
String pass = "x";
String to = "anotheremail";
String from = "myemail";
String subject = "New Application Have Arrived";
String messageText = "Please Check Career Website";
boolean sessionDebug = false;
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.required", "true");
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)}; //address of sender
msg.setRecipients(Message.RecipientType.TO, address); //receiver to email
msg.setSubject(subject); msg.setSentDate(new Date()); //message send date
msg.setText(messageText); //actual message
Transport transport=mailSession.getTransport("smtp");
transport.connect(host, user, pass);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
System.out.println("Message send successfully");
}catch(Exception ex)
{
System.out.println(ex);
}
}
}
i did it like this so that i dont have to do two action on my jsp form haha im dumb
package controller;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
import java.util.Properties;
import java.util.Random;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.RequestDispatcher;
#WebServlet("/uploadServlet")
#MultipartConfig(maxFileSize = 16177215)
public class UploadFileController extends HttpServlet
{
public static String user= "root";
public static String password = "x";
public static Connection getConnection() throws ClassNotFoundException{
Connection conn=null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/kps","root","X");
System.out.println("Connected");
}catch(SQLException e){System.err.println(e);}
return conn;
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
InputStream inputStream = null;
Random rand = new Random();
int n = rand.nextInt(9999) + 1;
String idTemp=(String.valueOf(n));
String title=(request.getParameter("title"));
Part filePart = request.getPart("file_uploaded");
if (filePart != null)
{
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
try
{
Connection conn = UploadFileController.getConnection();
//Connection conn= dbconn.Connection();
String sql = "INSERT INTO files (id, title, file) values (?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, idTemp);
statement.setString(2, title);
if (inputStream != null)
{
statement.setBinaryStream(3, inputStream, (int) filePart.getSize());
}
int row = statement.executeUpdate();
if (row > 0)
{
try{
String host ="smtp.gmail.com" ;
String user = "email";
String pass = "password";
String to = "another email";
String from = "email";
String subject = "New Application Have Arrived";
String messageText = "Please Check Career Website";
boolean sessionDebug = false;
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.required", "true");
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)}; //address of sender
msg.setRecipients(Message.RecipientType.TO, address); //receiver to email
msg.setSubject(subject); msg.setSentDate(new Date()); //message send date
msg.setText(messageText); //actual message
Transport transport=mailSession.getTransport("smtp");
transport.connect(host, user, pass);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
System.out.println("Message send successfully");
}catch(Exception ex)
{
System.out.println(ex);
}
out.println("File uploaded!!!");
conn.close();
RequestDispatcher rs = request.getRequestDispatcher("try.jsp");
rs.include(request, response);
}
else
{
out.println("Couldn't upload your file!!!");
conn.close();
RequestDispatcher rs = request.getRequestDispatcher("error.jsp");
rs.include(request, response);
}
}catch(Exception e){e.printStackTrace();
}
}
}
so yeah i asked stupid question, forgive me im a newbie
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
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();
}
}
}