簡體   English   中英

使用Java發送簡單的電子郵件

[英]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);
}

實際上,我想告訴您,我沒有完成代碼,因為它在第六行p.setProperty("mail.smtp.host",host)處開始給我錯誤。 它說package p does not exist <identifier> expected illegal start of type 我不知道這有什么問題。

編輯

回應OP的評論:

您缺少在執行的操作周圍聲明的方法。 對於鏈接到的示例OP,操作位於Main方法中:

public class emailfromgmail {

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

確保在操作結束后使用}關閉該方法,然后再關閉該類}

原始答案:

該行:

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

不應在課程部分中。 它需要進入方法或構造函數中。 您應該做的是這樣的:

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..

    }

然后將參數傳遞給該構造函數,例如:

emailfromgmail email = new emailfromgmail("palaksharma786@gmail.com","vineetsharma123786@gmail.com","localhost");

然后使用一種方法來執行諸如設置屬性和發送等操作:

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM