I am trying to write a program using java that will send an email. I am using JDK 1.6.0_43
I am getting java.net.UnknownHostException: mailhost error. My code is as follows -
import java.io.*;
import java.net.*;
public class SendMail {
public static void main(String[] args) {
try {
if (args.length >= 1)
System.getProperties().put("mail.host", args[0]);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("From: ");
String from = in.readLine();
System.out.print("To: ");
String to = in.readLine();
System.out.print("Subject: ");
String subject = in.readLine();
URL u = new URL("mailto:" + to);
URLConnection c = u.openConnection();
c.setDoInput(false);
c.setDoOutput(true);
System.out.println("Connecting...");
System.out.flush();
c.connect();
PrintWriter out = new PrintWriter(new OutputStreamWriter(c.getOutputStream()));
out.println("From: \"" + from + "\" <" + System.getProperty("user.name") + "#" + InetAddress.getLocalHost().getHostName() + ">");
out.println("To: " + to);
out.println("Subject: " + subject);
out.println();
System.out.println("Enter the message. " + "End with a '.' on a line by itself.");
String line;
for(;;) {
line = in.readLine();
if ((line == null) || line.equals("."))
break;
out.println(line);
}
out.close();
System.out.println("Message sent.");
System.out.flush();
}
catch (Exception e) {
System.err.println(e);
System.err.println("Usage: java SendMail [<mailhost>]");
}
}
}
How to solve this?
The error message says it all: Usage: java SendMail [<mailhost>]
You need to know the name (or IP address) of your mail server. So try executing it like this:
java SendMail smtp.example.com
Related
i am using the following in one of my application.
public static void concatenation(List<String> commands) throws IOException {
if (commands.get(1).equals(">")) {
String path = history.getFilePath();
File file = new File(path + "\\" + commands.get(2));
if (file.exists() && file.isFile()) {
try (FileWriter writer = new FileWriter(file)) {
Scanner scanner = new Scanner(System.in);
String line;
System.out.println("Write to file. Press Ctrl+C to stop.");
while (true) {
try {
line = scanner.nextLine();
writer.write(line + System.lineSeparator());
writer.flush();
} catch (Exception e) {
System.out.println("Interrupted. Stopping...");
break;
}
}
scanner.close();
} catch (IOException e) {
System.out.println("Error writing to file: " + e.getMessage());
}
}
} else {
System.out.println("bash : " + commands.get(1) + " : unrecognized operator");
}
}
i want to exit out of the while loop when ctrl + c is pressed. And it is a console application. How to achieve this?
I have the following data. What I'm trying to do is to separate every reading into different outputs, but it does not work. It only show 'null'. What i expected to work are:
Output:
C.txt
1 1000 1000
2 2000 2000
Output: B.txt
1 2 90.000 2
2 3 180.000 2
Output: D.txt
1 2 100.1 0.038
2 3 200.1 0.038
Data in Input.txt:
C;1;1000;1000
C;2;2000;2000
B;1;2;90.00;2
B;2;3;180.00;2
D;1;2;100.1;0.038
D;2;3;200.1;0.038
import java.io.*;
import java.util.StringTokenizer;
public class ReadFile {
public static void main(String[] args) {
BufferedReader input = null; //read
PrintWriter outC = null; //write output
PrintWriter outB = null;
PrintWriter outD = null;
try {
input = new BufferedReader(new FileReader("C:\\Users\\PC\\Desktop\\FYP\\Input.txt"));
outC = new PrintWriter(new BufferedWriter(new FileWriter("C:\\Users\\PC\\Desktop\\FYP_Test\\C.txt")));
outB = new PrintWriter(new BufferedWriter(new FileWriter("C:\\Users\\PC\\Desktop\\FYP_Test\\B.txt")));
outD = new PrintWriter(new BufferedWriter(new FileWriter("C:\\Users\\PC\\Desktop\\FYP_Test\\D.txt")));
String inputData = null;
int C = 0;
int B = 0;
int D = 0;
while ((inputData = input.readLine()) != null) {
StringTokenizer tokenizer = new StringTokenizer(inputData, ";");
String id = tokenizer.nextToken();
String StnFrom = tokenizer.nextToken();
String NorthingTo = tokenizer.nextToken();
String EastingDistBrg = tokenizer.nextToken();
String StdError = tokenizer.nextToken();
if (id.equalsIgnoreCase("C")) {
C++;
outC.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg);
} else if (id.equalsIgnoreCase("B")) {
B++;
outB.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg + " " + StdError);
} else if (id.equalsIgnoreCase("D")) {
D++;
outB.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg + " " + StdError);
}
}
input.close();
outC.close();
outB.close();
outD.close();
} catch (FileNotFoundException fe) {
System.out.println(fe.getMessage());
} catch (IOException iox) {
System.out.println(iox.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
tokenizer.nextToken() will throw NoSuchElementException when there are no more tokens in the tokenizer's string.
Your sample input, if provided, will throw "NoSuchElementException" because Data in "Input.txt" for "C" is wrong. In your program, you are calling "nextToken" five times, whereas data for "C" contains only 4 values(C;1;1000;1000).
Below, is improved "Input" data.
C;1;1000;1000;1
C;2;2000;2000;1
B;1;2;90.00;2
B;2;3;180.00;2
D;1;2;100.1;0.038
D;2;3;200.1;0.038
Also, you need to improve your while loop to read empty line. Currently, it will throw Error.
Consider below while loop:
while ((inputData = input.readLine()) != null) {
if(inputData.length() != 0) {
StringTokenizer tokenizer = new StringTokenizer(inputData, ";");
String id = tokenizer.nextToken();
String StnFrom = tokenizer.nextToken();
String NorthingTo = tokenizer.nextToken();
String EastingDistBrg = tokenizer.nextToken();
String StdError = tokenizer.nextToken();
if (id.equalsIgnoreCase("C")) {
C++;
outC.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg);
} else if (id.equalsIgnoreCase("B")) {
B++;
outB.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg + " " + StdError);
} else if (id.equalsIgnoreCase("D")) {
D++;
outD.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg + " " + StdError);
}
}
}
I created the mobile app on client side for Android successfully.
Then Server side, that is windows server code also created. I can able to type all the letters numbers and all.
My problem is using shift key and "#" key. I need "#" into my project. When I press the "#" crashes the connection and says...
Invalid key code
at sun.awt.windows.WRobotPeer.keyPress(Native Method)
at java.awt.Robot.keyPress(Unknown Source)
at pcHotkey.keyboardServer$Capitalizer.run
Now, how should I type "#" with my app. Then I press shift key it was passing correctly and it was not stopping the pressed state.
My code goes here,
1st class:
aMap.put("Shift", KeyEvent.VK_SHIFT);
aMap.put("At", KeyEvent.VK_AT);
try{
robo = new Robot();
}
catch(Exception e)
{}
ServerSocket listener = new ServerSocket(9898);
try {
while (true) {
new Capitalizer(listener.accept(), clientNumber++).start();
}
} finally {
listener.close();
}
2nd class :
public Capitalizer(Socket socket, int clientNumber) {
this.socket = socket;
this.clientNumber = clientNumber;
log("New connection with client# " + clientNumber + " at " + socket);
}
public void run() {
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
// Send a welcome message to the client.
out.println("Hello, you are client #" + clientNumber + ".");
out.println("Enter a line with only a period to quit\n");
while (true) {
String input = in.readLine();
System.out.println(input);
if(input.equals("Caps")){
Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent.VK_CAPS_LOCK, true);
;
}
else if(input.equals("At"))
{
log("Log Value : "+ input);
//Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent.VK_SHIFT, true);
robo.keyPress(aMap.get("At"));
//Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent.VK_SHIFT, true);
}
else
robo.keyPress(aMap.get(input));
}
} catch (IOException e) {
log("Error handling client# " + clientNumber + ": " + e);
} finally {
try {
socket.close();
} catch (IOException e) {
log("Couldn't close a socket, what's going on?");
}
log("Connection with client# " + clientNumber + " closed");
}
I did by passing the keycode of "SHIFT" and "2". Problem got fixed now.
Like the title says, I can get it to write the first thing to the file I want it to, but after that it doesn't write any more. I run it through the debugger, and see that it's not even reading the next line (I know this because it's not filling the array.) I tried manually advancing the pointer (I don't know if that's actually a thing you can do) at the end of the loop with "line = in.readline;", but It just throws a "nosuchelement" exception. Here's my try block"
try
{
in = new BufferedReader(new FileReader("lab7input.txt"));
outNormal = new PrintWriter(new File("normal.txt"));
outVegetarian = new PrintWriter(new File("vegetarian.txt"));
outPescetarian = new PrintWriter(new File("pescetarian.txt"));
outInvalid = new PrintWriter(new File("invalid.txt"));
String line = in.readLine();
StringTokenizer st = new StringTokenizer(line);
while (line != null)
{
Scanner sc = new Scanner(line);
while(sc.hasNext())
{
if(st.countTokens() == 3)
{
attendee3[0] = sc.next();
attendee3[1] = sc.next();
attendee3[2] = sc.next();
if(Integer.parseInt(attendee3[2]) == 0)
{
outNormal.println(attendee3[0] + " " + attendee3[1]);
outNormal.close();
}
else if(Integer.parseInt(attendee3[2]) == 1)
{
outVegetarian.println(attendee3[0] + " " + attendee3[1]);
outVegetarian.close();
}
else if(Integer.parseInt(attendee3[2]) == 2)
{
outPescetarian.println(attendee3[0] + " " + attendee3[1]);
outPescetarian.close();
}
else
{
outInvalid.println(attendee3[0] + " " + attendee3[1]);
outInvalid.close();
}
}
if(st.countTokens() == 4)
{
attendee4[0] = sc.next();
attendee4[1] = sc.next();
attendee4[2] = sc.next();
if(Integer.parseInt(attendee4[3]) == 0)
{
outNormal.println(attendee4[0] + " " + attendee4[1] + " " + attendee4[2]);
outNormal.close();
}
else if(Integer.parseInt(attendee4[3]) == 1)
{
outVegetarian.println(attendee4[0] + " " + attendee4[1] + " " + attendee4[2]);
outVegetarian.close();
}
else if(Integer.parseInt(attendee4[3]) == 2)
{
outPescetarian.println(attendee4[0] + " " + attendee4[1] + " " + attendee4[2]);
outPescetarian.close();
}
else
{
outInvalid.println(attendee4[0] + " " + attendee4[1] + " " + attendee4[2]);
outInvalid.close();
}
}
//line = in.readLine();
}
}
}
a simpler and cleaner way would be
String line = in.readLine();
while (line != null)
{
String arr [] = line.split ();
if(arr.length == 3)
{
attendee3[0] = arr[0];
attendee3[1] = arr[1];
attendee3[2] = arr[2];
}
// other count code
line = in.readLine();
}
You have to put line = in.readLine() one block below and not in a while block of a scanner.
Not only that, i've had the experience that Scanner can only read in UTF-8 codeded .txt files. so always make sure that they are UTF-8 coded.
If they are not just simply open the file and save it with that coding.
I wanted to set a timeout when a client read. the routine supposed to throw an InterruptedIOException but instead it throws NoSuchElementException on System.out.println("echo: " + _in.nextLine()); what am I doing wrong ?
this is my methode
public void startUserInput()
{
try {
_out = new PrintWriter(_echoSocket.getOutputStream(), true);
_in = new Scanner(new InputStreamReader(_echoSocket.getInputStream()));
Scanner stdIn = new Scanner(new InputStreamReader(System.in));
System.out.print("Input: ");
while (stdIn.hasNextLine()) {
_out.println(stdIn.nextLine());
System.out.println("echo: " + _in.nextLine());
System.out.print("Input: ");
}
stdIn.close();
}catch (InterruptedIOException exception){
System.err.println("The server is not responding " + _serverHostname);
}
catch (IOException e) {
System.out.println("error" + e.getLocalizedMessage());
}}
and this is my connection
public boolean establishConnection()
{
System.out.println ("Connecting to the host " +
this.getServerHostname() + " au port " + this.getServerPort());
try {
_echoSocket = new Socket();
_echoSocket = new Socket(this.getServerHostname(), this.getServerPort());
_echoSocket.setSoTimeout(10000);
System.out.println(_echoSocket.getOutputStream());
return _echoSocket.isConnected();
} catch (UnknownHostException e) {
System.err.println("Unknown host: " + this.getServerHostname());
return false;
} catch (IOException e) {
System.err.println("Error while connecting to the server : " +
this.getServerHostname() + ":" + this.getServerPort());
return false;
}
}
Thanks
The reason is that when you invoked _in.nextLine() there is no line to be read in from the from the Scanner object _in.
What you did in the while loop was to check for stdIn.hasNextLine() but you did not check if _in has a nextLine() that can be read.
For details on the exception, you can check out:
http://download.oracle.com/javase/1,5.0/docs/api/java/util/Scanner.html#nextLine()
hope it helps :) Cheers!