[英]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)
. 实际上,我想告诉您,我没有完成代码,因为它在第六行
p.setProperty("mail.smtp.host",host)
处开始给我错误。 It says package p does not exist <identifier> expected illegal start of type
. 它说
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: 回应OP的评论:
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: 对于链接到的示例OP,操作位于
Main
方法中:
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..
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.