public Boolean sendMail(String mailAddr, String mailTitle, String mailBody) throws MailSendException {
MailUser mailUser = mailUserDao.queryPresent();
if(mailUser == null)
{
throw new MailSendException(ErrorCode.MAIL_USER_NOT_EXISTS);
}
Properties property = new Properties();
// 开启debug调试
property.setProperty("mail.debug", "true");
// 发送服务器需要身份验证
property.setProperty("mail.smtp.auth", "true");
// 设置邮件服务器主机名
property.setProperty("mail.host",mailUser.getMailHost());
// 发送邮件协议名称
property.setProperty("mail.transport.protocol", "smtp");
Session session = Session.getInstance(property);
MimeMessage msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(mailUser.getMailUser()));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailAddr));
msg.setSubject(mailTitle);
msg.setText(mailBody);
} catch (MessagingException ex) {
Logger.getLogger(MailServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
throw new MailSendException(ErrorCode.MAIL_SEND_FAILED);
}
Transport transport = null;
//todo : 为什么每个操作都提示要加try catch
try {
transport = session.getTransport();
} catch (NoSuchProviderException ex) {
Logger.getLogger(MailServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
throw new MailSendException(ErrorCode.MAIL_SEND_FAILED);
}
//截取邮箱账号
String user = mailUser.getMailUser().substring(0,mailUser.getMailUser().indexOf("@"));
try {
transport.connect(user, mailUser.getMailPsw());
} catch (MessagingException ex) {
Logger.getLogger(MailServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
throw new MailSendException(ErrorCode.MAIL_SEND_FAILED);
}
try {
transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
transport.close();
} catch (MessagingException ex) {
Logger.getLogger(MailServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
throw new MailSendException(ErrorCode.MAIL_SEND_FAILED);
}
return true;
}
注意:
1、如果需要SSL协议发送邮件,需要把
property.setProperty("mail.transport.protocol", "smtp");
里面的smtp换成smtps,发送的时候端口号会自动从25切换成465
2、qq邮箱的host是smtp.exmail.qq.com