How to print all inbox emails - java

I am pretty new to Java and know nothing about ports or servers or sockets so i was hoping someone could help me. I want to make a little program that will print all the messages in your inbox (read and unread).
I found this code online but it only gives me my earliest message in my sent folder.
public class EmailService {
String server = "pop.gmail.com";
int port = 995;
static String username;
static String password;
SSLSocket socket;
BufferedReader input;
PrintWriter output;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
username = s.next() + "#gmail.com";
password = s.next();
new EmailService();
}
public EmailService() {
try {
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
socket = (SSLSocket)sslsocketfactory.createSocket(server, port);
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// After each println you MUST flush the buffer, or it won't work properly.
// The true argument makes an automatic flush after each println.
output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
connect();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void connect() throws IOException {
System.out.print("Greeting message: ");
String response = readOneLine();
System.out.println(response);
// Username
output.println("USER " + username);
response = readOneLine();
System.out.println(response);
// Password
output.println("PASS " + password);
response = readOneLine();
System.out.println(response);
output.println("RETR 1");
while (!response.equals(".")) {
response = readOneLine();
System.out.println(response);
}
}
public String readOneLine() throws IOException {
return input.readLine();
}
}
How would I change this code to get me all the messages in my inbox?

Related

How would I send a username/password from a Socket-run Java Client to a Server, verify the details, and then send a boolean result back to the client?

I've been working on a university project for a bit where I essentially coded a GUI along with a few other features on it. Recently, we've been tasked with implementing a server/client communication on the application, and the topic hasn't really been explained very well to us so I have been struggling. My idea for the implementation is to take the username & password that the client provides at the login screen, send it to a Server class, verify the details, and then send a boolean value of either true or false, depending on whether or not they have the correct details. This hasn't worked, and I don't believe the username/password test variables in the server class take on any values. I will share the relevant snippets of code from both the Client & Server class down below.
Client Part:
private void loginMessage() {
/*
* This is the default login message that will be displayed. We could add
* checkers and such to the information we receive from the username/password
* fields, however that is outside of the scope of our current homework
* assignment. I did, however, make sure to store the username in a string and
* personalize the welcome message.
*/
String uName = txtUsername.getText();
try {
dout.writeUTF(uName);
} catch (Exception e) {
}
String password = new String(usPassword.getPassword());
try {
dout.writeUTF(password);
} catch (Exception e) {
}
try {
boolean loginSuccess = din.readBoolean();
if (loginSuccess) {
JOptionPane.showMessageDialog(this,
"Thank you for logging in " + uName
+ ". You will now get redirected to our Customer Zone, where you can make purchases. Press OK to continue.",
"Success!", JOptionPane.INFORMATION_MESSAGE);
finished = true;
} else {
JOptionPane.showMessageDialog(this,
"Error. Either your username or password is incorrect. Please try again.", "Error",
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
}
}
private void cancel() {
/*
* This is the cancel operation. We will close the application when the cancel
* option is selected.
*/
System.exit(1);
}
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1", 7000);
InputStream in = socket.getInputStream();
DataInputStream din = new DataInputStream(in);
// send a message from client to server
OutputStream out = socket.getOutputStream();
DataOutputStream dout = new DataOutputStream(out);
} catch (Exception e) {
}
// We define a new MyApplication object in order to run our application.
MyApplication x = new MyApplication();
Progress a = new Progress();
Secondpage s = new Secondpage();
Thread t1 = new Thread(x);
t1.start();
try {
t1.join();
} catch (Exception e) {
e.printStackTrace();
}
a.start();
try {
a.join();
} catch (Exception e) {
e.printStackTrace();
}
s.start();
try {
s.join();
} catch (Exception e) {
e.printStackTrace();
}
}
Server Part:
public class MyServer {
Socket serverSocket;
BufferedReader br;
FileReader fr;
static String uname;
static String pwd;
static String filepath = "login.txt";
static String sep = ",";
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(7000);
System.out.println("Waiting for a client...");
Socket mySocket = serverSocket.accept();
System.out.println("I have a client");
DataInputStream clientIn = new DataInputStream(mySocket.getInputStream());
DataOutputStream clientOut = new DataOutputStream(mySocket.getOutputStream());
uname = clientIn.readUTF();
pwd = clientIn.readUTF();
System.out.println("I have a username " + uname + pwd);
boolean verif = verifyUserLogin(uname, pwd, filepath, sep);
clientOut.writeBoolean(verif);
System.out.println("Username: " + uname);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static boolean verifyUserLogin(String user, String pwd, String fp, String sep) {
String currentLine;
String data[];
try {
// We use FileReader to read file, and BufferedReader to read character stream.
FileReader fr = new FileReader(fp);
try (BufferedReader br = new BufferedReader(fr)) {
while ((currentLine = br.readLine()) != null) {
data = currentLine.split(sep);
if (data[0].equals(user) && data[1].equals(pwd)) {
return true;
}
}
}
} catch (Exception e) {
}
return false;
}
}
Now, my issue is I am struggling with sending the login and password strings over to the server. I don't think the username & password variables in the Server class are even holding any values to be honest, and I am unsure of how to fix this. I'm kind of lost, and really need some help. Thank you very much :)

Server not receiving requests from client

Basically I'm writing a 2 way communication client server program. The client sends requests to the server and server responds accordingly. The requests have to do with adding or removing tokens from a list of tokens stored on the server. The client side seems to work fine, the requests are being sent to the server. However it seems that the server is not receiving any request from the client and I have no idea why. I've attached the code:
client
package;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class TokenClient {
private static final int PORT_NUMBER = 9999;
private Socket socket;
private InputStream inStream;
private OutputStream outStream;
private Scanner inStreamScanner;
private PrintWriter outStreamPrinter;
public static void main(String[] args) {
new TokenClient().go();
}
void go() {
try {
System.out.println(
"Enter commands of the form \"CONNECT IP-address\", \"SUBMIT token\", \"REMOVE token\" or \"QUIT\"\n");
Scanner consoleScanner = new Scanner(System.in);
// java.io.BufferedReader consoleInputReader = new
// BufferedReader(new InputStreamReader(System.in));
String command = "";
while (!command.equals("QUIT") && consoleScanner.hasNextLine()) {
command = consoleScanner.nextLine(); // consoleInputReader.readLine();
processCommand(command);
}
System.out.println("Goodbye!");
consoleScanner.close();
} catch (IOException e) {
System.out.println("An exception occurred: " + e);
e.printStackTrace();
}
}
void processCommand(String userCommand) throws IOException {
if (userCommand.startsWith("SUBMIT"))
sendMessageToServer(userCommand);
else if (userCommand.startsWith("REMOVE"))
sendMessageToServer(userCommand);
else if (userCommand.equals("QUIT"))
closeConnectionToServer();
else if (userCommand.startsWith("CONNECT")) {
closeConnectionToServer();
connectToServer(userCommand);
} else
System.out.println("Invalid user command: " + userCommand);
}
void closeConnectionToServer() {
if (socket != null && !socket.isClosed()) {
try {
System.out.println("Disconnecting from server...");
sendMessageToServer("QUIT");
socket.close();
System.out.println("Connection to server closed.");
} catch (IOException e) {
System.out.println("An exception occurred: " + e);
e.printStackTrace();
}
}
}
void connectToServer(String connectCommand) throws IOException {
String ipAddress = connectCommand.substring(8).trim();
System.out.println("Connecting to server at " + ipAddress + ", port " + PORT_NUMBER + "...");
socket = new Socket(ipAddress, PORT_NUMBER);
inStream = socket.getInputStream();
outStream = socket.getOutputStream();
inStreamScanner = new Scanner(inStream);
outStreamPrinter = new PrintWriter(outStream);
System.out.println("Connected to server.");
}
void sendMessageToServer(String command) {
System.out.println("Sending message to server: " + command + "...");
if (socket == null || socket.isClosed())
System.out.println("Not possible - not connected to a server");
else {
outStreamPrinter.println(command); // send the message to the server
// NB: client doesn't check if tokens are valid
outStreamPrinter.flush(); // do so immediately
// Receive response from server:
if (!command.equals("QUIT") && inStreamScanner.hasNextLine()) {
String response = inStreamScanner.nextLine();
System.out.println("Response from server: " + response);
}
}
}
}
server
package;
import java.net.*;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
public class server {
private static Socket s;
private static Scanner inStreamScanner;
private static int PORT_NUMBER = 9999;
private static InputStream inStream;
private static OutputStream outStream;
private static PrintWriter outStreamPrinter;
private static ArrayList<String> ts = new ArrayList<String>();
public static void main(String[] args) throws IOException{
ServerSocket ss = new ServerSocket(PORT_NUMBER);
server serverInstance = new server();
server.s = ss.accept();
System.out.println("Client connected");
inStream = s.getInputStream();
outStream = s.getOutputStream();
inStreamScanner = new Scanner(inStream);
outStreamPrinter = new PrintWriter(outStream);
serverInstance.run();
}
public void run() {
try {
try {
doService();
} finally {
s.close();
}
} catch (IOException e) {
System.err.println(e);
}
}
public void doService() throws IOException{
while(true) {
if(inStreamScanner.hasNext())
return;
else {
outStreamPrinter.println("NO REQUEST");
outStreamPrinter.flush();
String request = inStreamScanner.next();
outStreamPrinter.println("Request received: " +request);
outStreamPrinter.flush();
handleServerRequest(request);
}
}
}
public void handleServerRequest(String request) throws IOException{
if(request.startsWith("SUBMIT")) {
String token = extractNum(request);
addtoTS(token);
} else if(request.startsWith("REMOVE")) {
String token = extractNum(request);
removefromTS(token);
} else if(request.startsWith("QUIT")) {
s.close();
} else {
outStreamPrinter.println("UNKNOWN REQUEST");
outStreamPrinter.flush();
}
}
public String extractNum(String request) {
String str = request;
String numberOnly = str.replaceAll("[^0-9]", " ");
return numberOnly;
}
public void addtoTS(String token) {
if(ts.contains(token)) {
outStreamPrinter.println("OK");
outStreamPrinter.flush();
}else {
ts.add(token);
outStreamPrinter.println("OK");
outStreamPrinter.flush();
}
}
public void removefromTS(String token) {
if(ts.contains(token)) {
ts.remove(token);
outStreamPrinter.println("OK");
outStreamPrinter.flush();
}else {
outStreamPrinter.println("ERROR: TOKEN NOT FOUND");
outStreamPrinter.flush();
}
}
}
I haven't run the code, but there seems to be an issue in your doService() method on the server side. You have an infinite loop, but the entire method returns (and thus the program also quits) as soon as the input stream recieves a new line character (when the client sends a request). So, it seems your program would quit when it receives the first command from the client. I'd also recommend closing more gently (ie check in the loop for end rather than closing the socket directly).
So, I'd define a private class variable boolean listening; or something like that. Then in the main() method, set it to true after the socket has been initialized (when the client has connected).
Change your doService() to something similar to the following:
public void doService() throws IOException
{
while(listening)
{
if(inputStreamReader.hasNext())
{
String request = inStreamScanner.next();
outStreamPrinter.println("Request received: " +request);
outStreamPrinter.flush();
handleServerRequest(request);
}
}
}
And change how you handle the QUIT command:
from
else if(request.startsWith("QUIT"))
{
s.close();
}
to
else if(request.startsWith("QUIT"))
{
listening = false;
}
The socket will be closed by the finally in run().

Socket server stuck

I'm trying to make a server/client to send text from client to server then sending back an ok message or something similar back to the client, but for some error that I can't see, either the server gets stuck right before sending the ok back to the client, or the client does not receive the message (I think it's the first one though).
Any help is appreciated.
This is the server code:
class ActiveServer extends Thread {
InputStream inStream;
OutputStream outStream;
public ActiveServer(InputStream inStream, OutputStream outStream) {
this.inStream = inStream;
this.outStream = outStream;
}
#Override
public void run() {
boolean ret = false;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
PrintWriter writer = new PrintWriter(outStream);) {
String line = null;
while((line = reader.readLine()) != null) {
String[] str = line.split(";");
line = null;
switch (str[0]) {
case "insert" : //ret = SQLOptions.insert(str[1], str[2]);
System.out.println(str[1]);
break;
}
writer.print(ret);
writer.flush();
// As far as i can see it gets stuck at the end of this while, but I don't know why.
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Server {
private static final int PORT = 39165;
public static void main(String[] args) {
try (ServerSocket server = new ServerSocket(PORT);) {
System.out.println("Servidor online");
ExecutorService service = Executors.newFixedThreadPool(10);
while (true) {
Socket client = server.accept();
InetAddress ip = client.getInetAddress();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date time = new Date();
System.out.print(sdf.format(time));
System.out.println(" " + ip + " connected");
InputStream inStream = client.getInputStream();
OutputStream outStream = client.getOutputStream();
service.execute(new ActiveServer(inStream,outStream));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
And here goes the client code:
public class Telnet {
static Console console = System.console();
public static void connect(String ip, String port) {
try(Socket socket = new Socket(ip, Integer.parseInt(port));
PrintWriter writer = new PrintWriter(socket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));) {
String msg = null;
while(true) {
msg = console.readLine();
writer.println(msg);
writer.flush();
if (msg.equals(".quit")) {
System.out.println("Exiting...");
break;
}
String input = reader.readLine();
System.out.println(input);
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
if(args.length < 2) {
err.println("Telnet <ip> <port>");
return;
}
if (console == null) {
err.println("A console is not available");
return;
}
connect(args[0], args[1]);
}
}
On the server side, you write the response without a terminating newline:
writer.print(ret);
But on the client side, you read until the end of line:
String input = reader.readLine();
The documentation for BufferedReader#readLine says:
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
Thus, the client will wait forever for the newline sequence which the server will never send.

Get an array from Server/Client app (Java)

So I have a Server/Client layer app running between my application and database. I would like to get an array from the Server. I will paste some pieces of code which I think is enough to give you an idea of what is going on:
I send to the server the keyword for search in database (user and his password)
fromUser = Musername + "," + Password;
out.println(fromUser);
Here is the code of the Server:
public class Server {
public static String[] theOutput;
public static String inputLine;
public static String[] string_array;
public static String output = "";
public static String[] process(String Input) throws Exception {
String[] data = Input.split(",");
// Call database class to get the results and store them into the array
load_login pridobi = new load_login();
theOutput = pridobi.nalozi(data[0], data[1]);
return theOutput;
}
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
// get the username and password
inputLine = in.readLine();
if (inputLine.length() != 0) {
string_array = process(inputLine);
}
// And here I would like to do something like that :/
out.println(string_array);
}
}
PS: NOTE that some array elements are actually long text.
I recommended you use other technically.
what happended if username and password that you send to the server contain a ",".
When you split you obtain a wrong data.
Before send: Example:
String username = URLEncoder.encoder("myusername", "utf-8");
String password = URLEncoder.encoder("mypassword", "utf-8");
String dataToSend = username + "," + password;
In your server:
String[] data = Input.split(",");
data[0] = URLDecoder.decoder(data[0],"utf-8");
data[1] = URLDecoder.decoder(data[1],"utf-8");
The server should response a string like this:
String responseData = URLEncoder.encoder(theOutput[0], "utf-8") + "," + URLEncoder.encoder(theOutput[1], "utf-8");
out.println(responseData);
The client side read the response like this:
String dataReceived = inputLine = in.readLine();
String data[] = dataReceived.split(",");
data[0] = URLDecoder.decoder(data[0],"utf-8");
data[1] = URLDecoder.decoder(data[1],"utf-8");

Printwriter not writing to outputStream

I'm trying to implement a basic web server in Java. When I direct a web browser to 127.0.0.1:8020/webpage.html, the server receives the request header, but when it tries to send the webpage back it doesn't show up on the browser.
Can anyone help?
public class WebServer
{
public static void main(String[] args)
{
try
{
ExecutorService scheduler = Executors.newCachedThreadPool();
ServerSocket server = new ServerSocket(8020);
while (true)
{
Socket client = server.accept();
Runnable r = new HTTPThread(client.getInputStream(), client.getOutputStream());
scheduler.execute(r);
System.out.println("LOG: New Thread Created");
}
}
catch (IOException e)
{
System.out.println("ERROR: Cannot listen on socket");
e.printStackTrace();
}
}
}
public class HTTPThread implements Runnable {
InputStream in;
OutputStream out;
private String fileName;
private String fileLoc;
private static final String rootLoc = "C:\\Users\\myName\\workspace\\HTTPServer\\src\\";
HTTPThread(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
}
public void run() {
try {
// show request headers and store http header
System.out.println("LOG: Preparing to read request");
String header = readInput(in);
System.out.println("LOG: Request read successfully!");
System.out.println(header);
// get file name from request header
fileLoc = rootLoc + header.substring(5, header.indexOf("H") - 1);
System.out.println(fileLoc);
PrintWriter writer = new PrintWriter(new OutputStreamWriter(out));
//send response header and body
writer.print("HTTP/1.0 200 OK\nContent-Type: text/html\n\n" + fileReader(fileLoc));
System.out.println("LOG: Response Sent");
out.close();
in.close();
}
catch (IOException e) {
System.out.println("ERROR: Could not listen on socket");
System.exit(-1);
}
}
//Returns content of webpage as a string (html)
public String fileReader(String file) {
StringBuilder text = new StringBuilder();
String NL = System.getProperty("line.separator");
Scanner scanner;
try {
scanner = new Scanner(new FileInputStream(file));
while (scanner.hasNextLine()) {
text.append(scanner.nextLine() + NL);
}
return text.toString();
} catch (FileNotFoundException e) {
System.out.println("ERROR: File Not Found");
System.exit(-1);
return null;
}
}
//Reads bytestream from client and returns a string
private String readInput(InputStream is) {
BufferedReader in = new BufferedReader(new InputStreamReader(is));
try
{
String current;
String header = "";
while (!(current = in.readLine()).isEmpty())
{
header += current + System.getProperty("line.separator");
}
return header;
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
}
Adding writer.close(); before out.close(); would fix it.
http responses have a very specific format. the protocol is very specific about which characters separate the header from the content. you have the wrong characters.
as a side note, never use PrintWriter on top of a network stream as it hides IOExceptions (in general, avoid PrintWriter).

Categories

Resources