Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用java发送简单的电子邮件_Java_Email_Smtp - Fatal编程技术网

使用java发送简单的电子邮件

使用java发送简单的电子邮件,java,email,smtp,Java,Email,Smtp,实际上,我想告诉你,我没有完成代码,因为它在第6行开始给我错误,这是p.setProperty(“mail.smtp.host”,host)。 它说,包p不存在,类型为非法开始。我不知道这有什么问题。编辑 针对OP的评论: 您缺少围绕正在执行的操作声明的方法。对于链接到的示例OP,操作在Main方法中: public class emailfromgmail { String from = "sender@gmail.com"; String to = "recipient@

实际上,我想告诉你,我没有完成代码,因为它在第6行开始给我错误,这是
p.setProperty(“mail.smtp.host”,host)
。 它说,
包p不存在,类型为非法开始。我不知道这有什么问题。

编辑

针对OP的评论:

您缺少围绕正在执行的操作声明的方法。对于链接到的示例OP,操作在
Main
方法中:

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)

不应该在课堂上。它需要进入方法或构造函数中。你应该这样做:

public class emailfromgmail {

  public static void main(String[] args){//This is the method declaration
然后将参数传递给该构造函数,如下所示:

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");

你需要在一个方法中编写你的电子邮件发送代码。先生,我不明白为什么我必须这样做,实际上我指的是这个网站,它没有使用方法或构造函数。在你看到的示例中,他使用的是一个方法。该方法是“Main”方法,由行“publicstaticvoidmain(String[]args){”打开
public void send(){
    Properties p = System.getProperties();
    p.setProperty("mail.smtp.host",host);
    //etc..

}