palak sharma
palak sharma

Reputation: 231

Sending a simple email using java

public class emailfromgmail {
     String from = "[email protected]";
     String to = "[email protected]";
     String host="localhost";

     //get the session object

     Properties p = System.getProperties();
     p.setProperty("mail.smtp.host", host);
     Session session = Session.getDefaultInstance(p);
}

Actually I want to tell you that I didn't complete the code because it start giving me error at the 6th line which is p.setProperty("mail.smtp.host",host). It says package p does not exist <identifier> expected illegal start of type. I don't know what is wrong with this.

Upvotes: 0

Views: 247

Answers (1)

Alex
Alex

Reputation: 827

EDIT

In respone to OP's comment:

You are missing a method declared around the operations you are performing. For the example OP linked to, the operations were in the Main method:

public class emailfromgmail {

  public static void main(String[] args){//This is the method declaration

Make sure to then close the method after your operations with a } before the class closing }

Original answer:

The line:

p.setProperty("mail.smtp.host", host);

Shouldn't be in the class section. It needs to go either in a method or the constructor. What you should do is something like this:

public class emailfromgmail {

    String from, to, host;
    //etc.

    public emailfromgmail(String from, String to, String host){ //any other parameters as well
        this.from = from;
        this.to = to;
        this.host = host;
        //etc..

    }

Then pass the parameters to that constructor like:

emailfromgmail email = new emailfromgmail("[email protected]","[email protected]","localhost");

Then use a method to do the operations like setting up the properties and sending etc:

public void send(){
    Properties p = System.getProperties();
    p.setProperty("mail.smtp.host",host);
    //etc..

}

Upvotes: 1

Related Questions