繁体   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