Hello I worked on this code to figure out how SMTP works with a java program and I got really far but I keep getting this error and I dont know whats wrong with it. It all seams to be what other similar programs that I looked at do but theirs seems to work.
It gets all the way down to the FROM line and then prints out this error
530 5.7.0 Must issue a STARTTLS command first. n1sm21348109bkv.14 - gsmtp
Exception in thread "main" java.lang.Exception: 250 reply not received from server.
at emailagent.EmailAgent.main(EmailAgent.java:73)
Any help with this would be appreciated
Thanks
import java.io.*;
import java.net.*;
import java.util.*;
public class EmailAgent
{
public static void main(String[] args) throws Exception
{
// Establish a TCP connection with the mail server.
System.out.println("Enter the mail server you wish to connect to (example: pop.gmail.com):\n");
String hostName = new String();
Scanner emailScanner = new Scanner(System.in);
hostName = emailScanner.next();
Socket socket = new Socket(hostName, 25);
// Create a BufferedReader to read a line at a time.
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
// Read greeting from the server.
String response = br.readLine();
System.out.println(response);
if (!response.startsWith("220"))
{
throw new Exception("220 reply not received from server.");
}
// Get a reference to the socket's output stream.
OutputStream os = socket.getOutputStream();
// Send HELO command and get server response.
String command = "HELO alice\r\n";
System.out.print(command);
os.write(command.getBytes("US-ASCII"));
response = br.readLine();
System.out.println(response);
if (!response.startsWith("250"))
{
throw new Exception("250 reply not received from server.");
}
// Send HELO command and get server response.
System.out.println("Enter the name of your mail domain (example: hotmail.com):");
String heloDomain = emailScanner.next();
String fullHeloCommand = "HELO " + heloDomain + "\r\n";
System.out.print(fullHeloCommand);
os.write(fullHeloCommand.getBytes("US-ASCII"));
response = br.readLine();
System.out.println(response);
if (!response.startsWith("250"))
{
throw new Exception("250 reply not received from server.\n");
}
// Send MAIL FROM command.
System.out.println("Please enter your e-mail address (example: me#myexample.com:\n");
String sourceAddress = emailScanner.next();
String mailFromCommand = "MAIL FROM: <" + sourceAddress + ">\r\n";
System.out.println(mailFromCommand);
os.write(mailFromCommand.getBytes("US-ASCII"));
response = br.readLine();
System.out.println(response);
if (!response.startsWith("250"))
{
throw new Exception("250 reply not received from server.\n");
}
// Send RCPT TO command.
System.out.println("Please type the destination e-mail address (example: example#nova.edu):\n");
String destEmailAddress = new String();
destEmailAddress = emailScanner.next();
String fullAddress = new String();
fullAddress = "RCPT TO: <" + destEmailAddress + ">\r\n";
System.out.println(fullAddress);
os.write(fullAddress.getBytes("US-ASCII"));
response = br.readLine();
System.out.println(response);
if(!response.startsWith("250"))
{
throw new Exception("250 reply not received from server.\n");
}
// Send DATA command.
String dataString = new String();
dataString = "DATA";
System.out.println(dataString);
os.write(dataString.getBytes("US-ASCII"));
response = br.readLine();
if(!response.startsWith("354"))
{
throw new Exception("354 reply not received from server.\n");
}
System.out.println(response);
// Send message data.
System.out.println("Enter your message, enter '.' on a separate line to end message data entry:\n");
String input = new String();
while(input.charAt(0) != '.')
{
input = emailScanner.next();
os.write(input.getBytes("US-ASCII"));
}
//End with line with a single period.
os.write(input.getBytes("US-ASCII"));
response = br.readLine();
System.out.println(response);
if(!response.startsWith("250"))
{
throw new Exception("250 reply not received from server\n");
}
// Send QUIT command.
String quitCommand = new String();
quitCommand = "QUIT";
os.write(quitCommand.getBytes("US-ASCII"));
}
}
The mail server you are attempting to connect to requires you establish a secure connection (TLS) in order to use mail services. Thats the error you are getting.
As far as the solution, I would highly recommend using the JavaMail library as it provides much of this functionality out of the box, and has been robustly tested 'in the wild'.
Related
I have trying to send multiple lines of code from a client to the server.
Here is the code on the server side
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
//read client input
//multi line
//https://stackoverflow.com/questions/43416889/java-filereader-only-seems-to-be-reading-the-first-line-of-text-document?newreg=2f77b35c458846dbb1290afce8853930
String line = "";
while((line =in.readLine()) != null) {
System.out.println(line);
}
System.out.println("is it here?");
Here is the code on the client side :
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
while (true) {
System.out.print("> ");
//content server input command (put, lamport clock, message)
String command = keyboard.readLine();
if (command.equals("quit")){
break;
}
//read from CSDB/txt1.txt
String message = readFileReturnString("CSDB/txt1.txt", StandardCharsets.UTF_8);
System.out.println(message);
//send to clientHandler through PrintWriter
out.println(command + " 3 \n" + message);
//receive response from ClientHandler (lamport clock)
String serverResponse = input.readLine();
System.out.println(serverResponse + socket);
}
Server side is able to print out all the text that is sent from the client side. However, the while loop doesn't break and System.out.println("is it here?"); has never been executed.
May I know why and how I can solve this problem please?
Your Client is waiting for some response of the Server. But the Server does not send any response. The Server writes to the System.out only. The Server has to write the response with the out.
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
out = new PrintWriter(client.getOutputStream(), true);
//read client input
//multi line
//https://stackoverflow.com/questions/43416889/java-filereader-only-seems-to-be-reading-the-first-line-of-text-document?newreg=2f77b35c458846dbb1290afce8853930
String line = "";
while((line =in.readLine()) != null) {
System.out.println(line);
out.println(line); // send Server response
}
System.out.println("is it here?");
# talex
Then you need to tell server when it should exit the loop. Yo may send special string or something.
This works fine.
String line = "";
while((line =in.readLine()) != null) {
System.out.println(line);
if (line.equals("break") {
break;
}
}
I tried building a TCP server and client using Java. They can connect, they work well, but I have a single error.
This is the server side:
package com.company;
import java.io.*;
import java.net.*;
public class Main {
public static void main (String[] args) throws IOException {
System.out.println("The server is ready");
ServerSocket serverSocket = new ServerSocket (1234);
Socket clientSocket = serverSocket.accept ();
BufferedReader in = new BufferedReader (new InputStreamReader (clientSocket.getInputStream ()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String message, modifiedMessage;
message = in.readLine ();
System.out.print("The received message from client: " + message);
modifiedMessage = message.toUpperCase();
out.print(modifiedMessage);
System.out.println ("\nModified message which is sent to client: " + modifiedMessage);
}
}
The server will have to receive a message from a client, then transforming it in an upper case string.
The client side is:
package com.company;
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1", 1234);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
System.out.println("Enter a lowercase sentence: ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in = new BufferedReader((new InputStreamReader(socket.getInputStream())));
String messageSent = reader.readLine();
System.out.println("The message sent is: " + messageSent);
out.println(messageSent);
String messageReceived = in.readLine();
System.out.println("The modified message is: " + messageReceived);
}
}
I want the client to be able to print both the lower case sentence and the received (modified) upper case sentence. The problem is that, when I enter a simple word, say hello, my client will only print the original string, not the modified one.
The output of the server is:
The received message from client: hello
The modified message sent to the client is: HELLO
But the output of the client is:
The message sent is: hello
The modified message is: null
I know that the server is able to convert the string to the upper-case version and to connect to my client. Why doesn't my client print the received message? Doesn't it actually receive it?
You need to flush the message. PrintWriter calls flush in println, print doesn't.
on the server side you need to change to:
out.println(modifiedMessage);
instead of
out.print(modifiedMessage);
i have a server and a client.
i'm connecting the server from the clients and immediately sends a message,
then i want the server to send message to the clients but when i send the message to the clients.
the input stream of the server which is in the client's code, looks like this:
#$#ok
the "#$#" is bytes that is not my string which i have no idea what are doing there.
this is my client function which connects to the server sends data and waits for the the server to send:
public void connectToServer(String ip, int port, String boardSize) throws UnknownHostException, IOException, ClassNotFoundException {
server = new Socket(ip, port);
serverInput = new BufferedReader(new InputStreamReader(server.getInputStream()));
PrintWriter serverOutput = new PrintWriter(new OutputStreamWriter(server.getOutputStream()));
ObjectOutputStream player1OutputData = new ObjectOutputStream(player1.getOutputStream());
ObjectOutputStream player2OutputData = new ObjectOutputStream(player2.getOutputStream());
serverOutput.println(boardSize);
serverOutput.flush();
String isGameStarted = serverInput.readLine();
if(isGameStarted.equals("ok")) {
...
}
}
and this is my server code which send the "ok" string:
BufferedReader player1Input = new BufferedReader(new InputStreamReader(player1.getInputStream()));
BufferedReader player2Input = new BufferedReader(new InputStreamReader(player2.getInputStream()));
PrintWriter player1Output = new PrintWriter(new OutputStreamWriter(player1.getOutputStream()));
PrintWriter player2Output = new PrintWriter(new OutputStreamWriter(player2.getOutputStream()));
String gameStarted = "ok"
player1Output.println(gameStarted);
player1Output.flush();
player2Output.println(gameStarted);
player2Output.flush();
System.out.println("message sent to clients: \"" + gameStarted + "\"");
player1OutputData.writeObject(gameBoard);
player2OutputData.writeObject(gameBoard);
i didnt send any garbage data, why would it be there?
and what should i do to clean it up?
thanks!
EDIT: ok so i think i know when this is happening,
after i send "ok" i want to send a string matrix to the clients as well, so when i do that for some reason the "String isGameStarted = serverInput.readLine();"
line isn't getting the "ok" string, it is getting the array, and after i remove those lines(where i send the array), the garbage bytes remain there, i don't know why.
So here's the thing, I have a basic java server that sends back to the client what ever it receives from it. The client is written in python. I'm able to make the first connection as in the server sends the client a message confirming the connection. But when I want the client to send the server something is does nothing. I'm not sure if the problem with the client not sending or the server not receiving.
Here's the code for the server:
int portNumber = Integer.parseInt(args[0]);
try (
ServerSocket serverSocket = new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter outs =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine, outputLine;
outputLine = "Hello socket, I'm server";
outs.println(outputLine);
outs.println("I' connected");
while ((inputLine = in.readLine()) != null) {
outputLine = inputLine;
outs.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
} }
and here's the client :
import socket
HOST = "localhost"
PORT = 8080
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
print (socket.getaddrinfo(HOST,PORT))
buffer_size = 100
while True :
data = sock.recv(buffer_size)
print ('you recieved :' , data)
test = input('send here\n')
sock.sendall(bytes(test, 'utf-8'))
print ('you sent : ' , test)
In the Python client:
Your prompt contains a \n but the result from input does not? Try adding a \n to test before sending.
I am writing a web client. I have the following code.
public class Connection extends Thread{
public final static int PORT = 1337;
private ServerSocket svrSocket = null;
private Socket con = null;
public Connection(){
try{
svrSocket = new ServerSocket(PORT);
System.out.println("Conected to: " + PORT);
}catch(IOException ex)
{
System.err.println(ex);
System.out.println("Unable to attach to port");
}
}
public void run(){
while(true)
{
try{
con = svrSocket.accept();//on this part the program stops
System.out.println("Client request accepted");
PrintWriter out = new PrintWriter(con.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
out.println("GET /<index.html> HTTP/1.1");
out.println("***CLOSE***");
System.out.println(in.readLine());
/*
String s;
while((s = in.readLine()) != null)
{
System.out.println(s);
}*/
out.flush();
out.close();
in.close();
con.close();
System.out.println("all closed");
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
}
The run method will be used latter on. That I have is a file called index.html. This file is in the same file as the java code. What I am trying to do with the request is send the HTML file. But if I run this program on a web browser localhost:1337 the following gets displayed.
GET /<index.html> HTTP/1.1
***CLOSE***
This should not get displayed. The page that results of the HTML code in the index.html should get displayed.
Index.html code:
<html>
<head>
<title> </title>
</head>
<body bgcolor = "#ffffcc" text = "#000000">
<h1>Hello</h1>
<p>This is a simple web page</p>
</body>
</html>
How do I get this html page to display in the browser?
Thank you
t seems that all is good on your code, it seems you need to read the HTTP header from the input stream so you can get the requested file name and then use the Socket output stream to write the response from the file.
OutputStream output = con.getOutputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String fileName = readHeader(in);
String baseDir = System.getProperty("my.base.dir", "/home/myname/httpserver");
boolean exist = true;
InputStream fileIn = null;
try {
File requestedFile = new File(baseDir, fileName);
fileIn = new FileInputStream(requestedFile);
} catch(Exception e){
exist = false;
}
String server = "Java Http Server";
String statusLine = null;
String typeLine = null;
String body = null;
String lengthLine = "error";
if (exist) {
statusLine = "HTTP/1.0 200 OK" + "\r\n";
//get content type by extension
typeLine = "Content-type: html/text \r\n";
lengthLine = "Content-Length: " + (new Integer(fileIn.available())).toString() + "\r\n";
} else {
statusLine = "HTTP/1.0 404 Not Found" + CRLF;
typeLine = "text/html";
body = "<HTML>" + "<HEAD><TITLE>404</TITLE></HEAD>" + "<BODY>404 Not Found"+"</BODY></HTML>";
}
output.write(statusLine.getBytes());
output.write(server.getBytes());
output.write(typeLine.getBytes());
output.write(lengthLine.getBytes());
output.write("\r\n".getBytes());
if (exist) {
byte[] buffer = new byte[1024];
int bytes = 0;
while ((bytes = fileIn.read(buffer)) != -1) {
output.write(buffer, 0, bytes);
}
} else {
output.write(body.getBytes());
}
//close sreams
You are confusing a couple of things. First of all: what you are writing is a server, not a client.
Second: You are not following the HTT Protocol.
The line GET /<index.html> HTTP/1.1 (which is wrong, it should be GET /index.html HTTP/1.1) is a request that is sent by the client (like a web browser). Instead, it is your server sending this.
A quick solution:
Instead of sending this static text (the line with the GET and the one with the ***CLOSE***), read the content of your index.html file and print it to your out stream.
EDIT: Here's a quick overview of the http data flow:
The client (e.g. a browser) connects to the server
The client sends it's request, something like
GET /theFileIWant.html HTTP/1.1\r\n
Host: localhost\r\n
\r\n
at this point, the client usually stops sending anything and waits for the server to respond. That is called the "request/response" model.
The server reads the request data and finds out what it has to do.
The output (in this case: a file's content) is sent to the client, preceded by HTTP response headers.
The connection can be kept open or closed, depending on the HTTP headers of both client's request and server's response.