邮件发送工具类及邮箱有效性校验

邮件对象

import lombok.Data;

import java.util.Date;

/**
 * 邮件对象
 *
 * @author huxiang
 */
@Data
public class Email {
    /**
     * 邮件标题
     */
    private String subject;

    /**
     * 邮件内容
     */
    private String content;

    /**
     * 收件人,多个收件人用逗号分割
     */
    private String recipients;

    /**
     * 发送时间,null表示立即发送
     */
    private Date sendTime;

    /**
     * 邮件发送认证方式,默认使用密码,false时使用授权码认证
     */
    private boolean usePassword = true;
}

发送邮件工具类

import com.paratera.console.notice.model.message.Email;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

/**
 * 发送邮件工具类
 *
 * @author huxiang
 */
@Component
@Slf4j
public class EmailUtil {

    @Value("${console.email.sendaddress}")
    private String sendAddress;

    @Value("${console.email.password}")
    private String password;

    @Value("${console.email.smtpserver}")
    private String smtpServer;

    public void send(Email email) throws MessagingException {
        if (email.isUsePassword()) {
            sendByPassword(email);
            return;
        }
        sendByAuthCode(email);
    }

    /**
     * 发送邮件(授权码)
     *
     * @param email 邮件内容
     */
    private void sendByAuthCode(Email email) throws MessagingException {
        Properties props = System.getProperties();
        // 打开认证
        props.setProperty("mail.smtp.auth", "true");
        //设置传输协议
        props.setProperty("mail.transport.protocol", "smtp");
        //设置发件人的SMTP服务器地址
        props.setProperty("mail.smtp.host", smtpServer);
        //获取默认session对象
        Session session = Session.getInstance(props);
        session.setDebug(true);
        //创建邮件对象
        MimeMessage message = new MimeMessage(session);
        message = getContent(message, email);

        try {
            Transport transport = session.getTransport();
            // 发件人邮箱账号、授权码
            transport.connect(sendAddress, password);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            log.info("邮件发送成功:" + email);
        } catch (Exception e) {
            log.info("邮件发送失败:" + email + ",异常原因:" + e);
        }
    }

    /**
     * 发送邮件(密码)
     *
     * @param email
     */
    private void sendByPassword(Email email) throws MessagingException {
        Properties properties = System.getProperties();
        //设置邮件服务器
        properties.setProperty("mail.smtp.host", smtpServer);
        //打开认证
        properties.setProperty("mail.smtp.auth", "true");
        //设置端口
        properties.setProperty("mail.smtp.port", "25");
        //获取默认session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                // 发件人邮箱账号、密码
                return new PasswordAuthentication(sendAddress, password);
            }
        });
        //创建邮件对象
        MimeMessage message = new MimeMessage(session);
        message = getContent(message, email);
        try {
            Transport.send(message);
            log.info("邮件发送成功:" + email);
        } catch (Exception e) {
            log.info("邮件发送失败:" + email + ",异常原因:" + e);
        }
    }

    /**
     * 校验发送的邮件内容
     */
    private MimeMessage getContent(MimeMessage message, Email email) throws MessagingException {
        if (StringUtils.isEmpty(email.getSubject())) {
            throw new MessagingException("邮件标题不能为空");
        }
        if (StringUtils.isEmpty(email.getContent())) {
            throw new MessagingException("邮件内容不能为空");
        }
        Date sendTime = email.getSendTime() == null ? new Date() : email.getSendTime();
        message.setSentDate(sendTime);
        message.setSubject(email.getSubject(), "UTF-8");
        message.setContent(email.getContent(), "text/html;charset=UTF-8");
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email.getRecipients()));
        message.setFrom(new InternetAddress(sendAddress));
        return message;
    }
}

邮箱有效性校验接口

 public void sendEmailCode(String email) throws MessagingException {
        Email mail = new Email();
        mail.setSubject("邮箱验证码,有效时间五分钟,重试无效!");
        mail.setRecipients(email);
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        mail.setContent(code);
        emailUtil.send(mail);
        redisTemplate.opsForValue().set(EMAIL_UUID + email, code, 5, TimeUnit.MINUTES);
    }

    public boolean validateEmailCode(String email, String code) {
        if (StringUtils.equals(redisTemplate.opsForValue().get(EMAIL_UUID + email), code)) {
            redisTemplate.delete(EMAIL_UUID + email);
            return true;
        }
        return false;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值