packagecom.wzy.car.exhibition.controller.adver;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.ResponseBody;importjavax.activation.DataHandler;importjavax.activation.FileDataSource;import javax.mail.*;import javax.mail.internet.*;importjava.util.Calendar;importjava.util.Properties;/*** 发送邮件
*
*@author高飞
*@versionv1.0
*@since2018/6/13*/@Controller
@RequestMapping("/bm")public classbMController {
@RequestMapping(value= "/sendEmail",method =RequestMethod.POST)
@ResponseBodypublic String sendEmail(@RequestParam(value = "email") String email){//1.创建一个程序与邮件服务器会话对象 Session
Properties props = newProperties();
props.setProperty("mail.transport.protocol", "SMTP");//连接协议
props.setProperty("mail.smtp.host", "smtp.163.com");//连接协议
props.setProperty("mail.smtp.port", "25");//连接协议//指定验证为true
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.timeout","1000");//验证账号及密码,密码需要是第三方授权码
Authenticator auth = newAuthenticator() {publicPasswordAuthentication getPasswordAuthentication(){return new PasswordAuthentication("发送人邮箱", "授权码");
}
};
Session session=Session.getInstance(props, auth);//2.创建一个Message,它相当于是邮件内容
MimeMessage message = newMimeMessage(session);try{//防止成为垃圾邮件,披上outlook的马甲
message.addHeader("X-Mailer","Microsoft Outlook Express 6.00.2900.2869");//设置发送者
message.setFrom(new InternetAddress("发送人邮箱"));//设置发送方式与接收者
message.setRecipient(MimeMessage.RecipientType.TO, newInternetAddress(email));//设置主题
message.setSubject("标题");//创建消息主体
MimeBodyPart messageBodyPart = newMimeBodyPart();
messageBodyPart.setText("内容主体");//创建多重消息
Multipart multipart=newMimeMultipart();
multipart.addBodyPart(messageBodyPart);//设置邮件消息发送的时间
message.setSentDate(Calendar.getInstance().getTime());//设置内容
message.setContent(multipart, "text/html;charset=utf-8");//3.创建 Transport用于将邮件发送
Transport.send(message);return "200";
}catch(Exception e){
e.printStackTrace();return "400";
}
}
}