java实现发送邮件

java发送邮件 需要先申请邮箱的授权码,对应配置文件中的password。

 

 

1.引入jar

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.7</version>
</dependency>

2.实现代码:

创建Mail封装类

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Mail implements Serializable {

    private static final long serialVersionUID = -1L;

    @ApiModelProperty("发件人")
    private String sendFrom;

    @ApiModelProperty("收件人,多个以逗号隔开")
    private String sendTo;

    @ApiModelProperty("抄送人,多个以逗号隔开")
    private String sendCopy;

    @ApiModelProperty("主题")
    private String subject;

    @ApiModelProperty("邮件内容")
    private String content;
}

创建发送邮件工具类:

public class SendEmailUtil {
    public static Session createSession(String host, String userName, String passWord) {
        Properties prop = new Properties();
        prop.setProperty("mail.host", host);
        prop.setProperty("mail.smtp.auth", "true");
        prop.setProperty("mail.smtp.ssl.enable", "true");
  // 创建验证器
        Authenticator auth = new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, passWord);
            }
        };
        // 获取session对象
        return Session.getInstance(prop, auth);
    }

    /**
     * 发送指定的邮件
     *
     * @param mail
     */
    public static void send(Session session, Mail mail) throws Exception {

        MimeMessage msg = new MimeMessage(session);
        // 设置发件人
        msg.setFrom(new InternetAddress(mail.getSendFrom()));
        // 设置收件人
        msg.addRecipients(Message.RecipientType.TO, mail.getSendTo());
        //设置抄送
        if (!ObjectUtils.isEmpty(mail.getSendCopy())) {
            msg.addRecipients(Message.RecipientType.CC, mail.getSendCopy());
        }
        //设置主题
        msg.setSubject(mail.getSubject());
        //创建部件集对象
        MimeMultipart parts = new MimeMultipart();
        //创建一个部件
        MimeBodyPart part = new MimeBodyPart();
        //设置邮件文本内容
        part.setContent(mail.getContent(), "text/html;charset=utf-8");
        //把部件添加到部件集中
        parts.addBodyPart(part);
        //给邮件设置内容
        msg.setContent(parts);
        //发邮件
        Transport.send(msg);
    }
}

添加配置文件:

#发送邮件配置
mail.host=smtphz.qiye.163.com
mail.username=***@163.com
mail.password=uA*******

service中调用:

@Value("${mail.host}")
private String host;
@Value("${mail.username}")
private String userName;
@Value("${mail.password}")
private String passWord;


//给用户发送邮件
 String subject = "后台管理平台账号已生成,请查收!";
 String content = String.format("账号:%s  密码:%s", userinfo.getUsername(), pwd);
 Mail mail = Mail.builder().sendFrom(userName).
              sendTo(userinfo.getUsername())
              .subject(subject)
              .content(content).build();
 try {
     SendEmailUtil.send(SendEmailUtil.createSession(host, userName, passWord), mail);
 } catch (Exception e) {
     e.printStackTrace();
 }

 

posted @ 2023-02-23 17:57  山阴路的秋天  阅读(743)  评论(0编辑  收藏  举报