简体   繁体   中英

Sending a simple email using java

public class emailfromgmail {
     String from = "sender@gmail.com";
     String to = "recipient@gmail.com";
     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.

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("palaksharma786@gmail.com","vineetsharma123786@gmail.com","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..

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM