/**
* 邮件发送功能配置类,需要引用spring的mail功能,maven引入地址:
* <!-- java mail dependency -->
* <dependency>
* <groupId>javax.mail</groupId>
* <artifactId>mail</artifactId>
* <version>1.4.7</version>
* </dependency>
* <dependency>
* <groupId>org.springframework</groupId>
* <artifactId>spring-context-support</artifactId>
* <version>4.3.8.RELEASE</version>
* </dependency>
* @Author renchenglong
*/
public class MailConfig {
private MailConfig() {
}
//邮箱的地址
private static final String EMAIL_HOST= "smtp.******.com";
//邮箱账号
private static final String EMAIL_USERNAME= "**********";
//邮箱密码或者授权码
private static final String EMAIL_PASSWORD= "************";
//邮箱端口号
private static final int EMAIL_PORT= 465;
//开启ssl功能
private static final boolean ENABLE_SSL= true;
//java邮件发送实例,他被声明成私有的
private static JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
/** 为发送实例的属性赋值
* 腾讯邮箱需要打开ssl功能,因为它默认是关闭的
*/
static {
mailSender.setHost(EMAIL_HOST);
mailSender.setPort(EMAIL_PORT);
mailSender.setUsername(EMAIL_USERNAME);
mailSender.setPassword(EMAIL_PASSWORD);
if (ENABLE_SSL){
Properties properties = new Properties();
properties.setProperty("mail.smtp.ssl.enable","true");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.auth", "true");
Session session = Session.getInstance(properties);
mailSender.setSession(session);
}
}
/**
* 获取邮件发送实例
* @return JavaMailSenderImpl
*/
public static JavaMailSenderImpl getMailSender(){
return mailSender;
}
}
邮件发送类
public String sendMail(EmailVo emailVo) {
log.warn("sendMail: "+JSON.toJSONString(emailVo));
try {
if (StringUtil.isNotNull(emailVo.getToEmail()) ) {
if (StringUtil.isNull(emailVo.getSubject())) {
emailVo.setSubject(emailVo.getTitle());
}
if (StringUtil.isNull(emailVo.getTitle())) {
emailVo.setSubject(emailVo.getSubject());
}
//获取邮件发送对象
JavaMailSenderImpl mailSender = MailConfig.getMailSender();
//创建邮件实例
MimeMessage mimeMessage = mailSender.createMimeMessage();
//构造消息helper,第二个参数表明这个消息是multipart类型的
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "UTF-8");
//邮件来源
helper.setFrom(new InternetAddress(mailSender.getUsername()) );
//邮件发送给
helper.setTo(emailVo.getToEmail());
//邮件标题
helper.setSubject(emailVo.getSubject());
//邮件内容
helper.setText(emailVo.getContent(),true);
if(StringUtil.isNotNull(emailVo.getBcc()))
helper.setBcc(emailVo.getBcc());
if(StringUtil.isNotNull(emailVo.getCc()))
helper.setCc(emailVo.getCc());
if(StringUtil.isNotNull(emailVo.getReplyto()))
helper.setReplyTo(emailVo.getReplyto());
//发送邮件
mailSender.send(mimeMessage);
log.info("-------send mail success------");
return SEND_STATUS_SUCCESS;
}else{
log.error("-----fromEmail or toEmail is null-----");
return SEND_STATUS_FAILURE;
}
}catch (Exception e){
log.error(e);
return SEND_STATUS_FAILURE;
}
}