java中new一个对象的问题
顽皮猫喵 2017-08-23 03:10:55 如图,这是种啥操作?? 还可以这么玩??
public class TestMail {
public static void main(String[] args) {
new MailSender()
.title("测试发送邮件")
.content("文本!!")
.contentType(MailContentTypeEnum.TEXT.getValue())
.targets(new ArrayList<String>(){{
add("283206322@qq.com");
}
});
}
}
直接在一个new 后面. . . . 就可以了。。。。
public class MailSender {
//邮件实体
private static MailEntity mail = new MailEntity();
public MailSender title(String title){
mail.setTitle(title);
return this;
}
public MailSender content(String content){
mail.setContent(content);
return this;
}
public MailSender contentType(String contentType){
mail.setContentType(contentType);
return this;
}
public MailSender targets(List<String> targets){
mail.setList(targets);
return this;
}
public void send() throws Exception{
if(mail.getContentType()==null){
mail.setContentType(MailContentTypeEnum.HTML.getValue());
}
if(mail.getTitle() == null || mail.getTitle().trim().length()==0){
throw new Exception("无标题");
}
if(mail.getContent()==null||mail.getContentType().trim().length()==0){
throw new Exception("无内容");
}
if(mail.getList()==null || mail.getList().size()==0){
throw new Exception("无接收者");
}
final PropertiesUtil properties = new PropertiesUtil("mail");
final Properties props = new Properties();
//smtp发送邮件需要身份验证
props.put("mail.smtp.auth","true");
//smtp服务器
props.put("mail.stmp.host",properties.getValue("mail.stmp.service"));
//设置端口号
props.put("mail.smtp.port",properties.getValue("mail.smtp.port"));
//发送邮件
props.put("mail.user",properties.getValue("mail.from.address"));
//设置发送邮件的16位STMP口令
props.put("mail.password",properties.getValue("mail.from.stmp.pwd"));
//构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName,password);
}
};
Session mailSession = Session.getInstance(props,authenticator);
MimeMessage message = new MimeMessage(mailSession);
String nickName = MimeUtility.encodeText(properties.getValue("mail.from.nickname"));
InternetAddress form = new InternetAddress(nickName + "<" + props.getProperty("mail.user")+">");
message.setFrom(form);
message.setSubject(mail.getTitle());
//html发送
if(mail.getContentType().equals(MailContentTypeEnum.HTML.getValue())){
message.setContent(mail.getContent(),mail.getContentType());
}
//文本发送
else if(mail.getContentType().equals(MailContentTypeEnum.TEXT.getValue())){
message.setText(mail.getContent());
}
//发送地址
List<String> list = mail.getList();
for(int i=0;i<list.size();i++){
try{
//设置收件邮箱
InternetAddress t0 = new InternetAddress(list.get(i));
message.setRecipient(Message.RecipientType.TO,t0);
Transport.send(message);
}catch (Exception e){
continue;
}
}
}
}
这个类是这样的。 看不懂那个main方法里面的东西。。。