public BaseResult sendEmail(String to,String Content) {
try {
/*** 1、创建Session ***/
Properties props = new Properties();
/*
// 开启调试模式
props.setProperty("mail.debug", "true");*/
// 发送主机需要身份验证
props.setProperty("mail.smtp.auth", "true");
// 设置主机名称
props.setProperty("mail.host", "smtp.exmail.qq.com");
// 设置主机端口
props.setProperty("mail.port", "25");
// 发送协议名称
props.setProperty("mail.transport.protocol", "smtp");
Session session = Session.getInstance(props);
/*** 2、创建邮件对象 ***/
Message msg = new MimeMessage(session);
// 设置发件人
String nick = "";//发件人昵称
msg.setFrom(new InternetAddress(globalProperties.emailAccount,nick));
// 设置标题
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
msg.setSubject(formatter.format(new Date())+"GMP统计通知");
// 设置内容
msg.setContent(Content, "text/html;charset=UTF-8");
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));//设置收件人
//String cc = "Otis.Chen@ficent.com,teddy.tang@ficent.com";
//msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
/*** 3、发送邮件 ***/
if (props.get("mail.smtp.auth").equals("true")) {
Transport transport = session.getTransport();
transport.connect(globalProperties.emailAccount, globalProperties.emailPassword);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
} else {
Transport.send(msg);
}
System.out.println("邮件发送成功");
} catch (Exception e){
e.printStackTrace();
return new BaseResult(Config.Result_Error, e.toString());
}
return new BaseResult(Config.Result_Ok,"");
}
emailAccount 发送者账号 emailPassword 发送者密码 to 收件人账号 Content 发送信息
gradle依赖
compile group: 'commons-email', name: 'commons-email', version: '1.1'//邮件发送