有详细描述。
入参Email 收件人邮箱
subject 邮件主题
text 邮件内容
public boolean sendEmail(String Email,String subject,String text){
MailHost mailHost = mailMapper.selectMailHost();
//获取发件人邮箱
String addressFrom = mailHost.getAddressFrom();
//获取服务器地址
String host = mailHost.getHost();
//获取密码
String passWord = mailHost.getAuthCode();
//获取邮箱传输协议
String protocol = mailHost.getProtocol();
try {
//1,设置连接服务器参数配置
Properties props = new Properties();
props.setProperty("mail.transport.protocol",protocol);
props.setProperty("mail.smtp.host",host);
if (mailHost.getAuthFlag().equals("1")){
props.setProperty("mail.smtp.auth","true");
}else if(mailHost.getAuthFlag().equals("0")){
props.setProperty("mail.smtp.auth","false");
}
//2,配置创建会话对象,用于和邮件服务器交互
Session session = Session.getInstance(props);
session.setDebug(true);
//3,发送邮件信息
MimeMessage message = new MimeMessage(session);
message.setFrom(addressFrom);
//设置收件人邮箱
message.addRecipient(Message.RecipientType.TO, new InternetAddress(Email));
//设置主题
message.setSubject(subject);
message.setSentDate(new Date());
//设置文本
message.setText(text);
//4,根据Session 获取邮件传输对象
Transport transport = session.getTransport();
//5,使用邮箱账号 密码 连接邮件服务器
String user = addressFrom.split("@")[0];
transport.connect(user,passWord);
Address[] allRecipients = message.getAllRecipients();
transport.sendMessage(message,allRecipients);
transport.close();
}catch (Exception e){
log.error("发送邮件失败");
e.printStackTrace();
return false;
}
return true;
}