JavaMail 实现邮件推送功能(网易邮箱)

1.首先需要去网易注册一个邮箱,登陆后如图点击POP3/SMTP/IMAP

在这里插入图片描述

2.开启POP3,填写对应的信息,复制获得的授权码

在这里插入图片描述

3.自己创建好Maven工程,导入JavaMail的依赖

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.5.0-b01</version>
</dependency>

4.注释在代码中,可根据自己的授权码进行修改

package com.itboyst.facedemo.util;

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

public class SendMailByWY {
    
    

    public static void sendEmail(String to, String content) throws MessagingException {
    
    
        //1.创建连接对象
        Properties properties = new Properties();
        //1.2 设置发送邮件的服务器
        properties.put("mail.smtp.host","smtp.163.com");
        //1.3 需要经过授权,用户名和密码的校验(必须)
        properties.put("mail.smtp.auth",true);
        //1.4 默认以25端口发送
        properties.setProperty("mail.smtp.socketFactory.class" , "javax.net.ssl.SSLSocketFactory");
        properties.setProperty("mail.smtp.socketFactory.fallback" , "false");
        properties.setProperty("mail.smtp.port" , "465");
        properties.setProperty("mail.smtp.socketFactory.port" , "465");
        //1.5 认证信息
        Session session = Session.getInstance(properties, new Authenticator() {
    
    
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
    
    
                return new PasswordAuthentication("你自己的网易邮箱@163.com" , "授权码");
            }
        });
        //2.创建邮件对象
        Message message = new MimeMessage(session);
        //2.1设置发件人
        message.setFrom(new InternetAddress("你自己的网易邮箱@163.com"));
        //2.2设置收件人
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
        //2.3设置抄送者(PS:没有这一条网易会认为这是一条垃圾短信,而发不出去)
        message.setRecipient(Message.RecipientType.CC,new InternetAddress("你自己的网易邮箱@163.com"));
        //2.4设置邮件的主题
        message.setSubject("主题");
        //2.5设置邮件的内容
        message.setContent(""+content+"","text/html;charset=utf-8");
        //3.发送邮件
        Transport.send(message);
    }
	
	//直接在main方法下测试
    public static void main(String[] args) throws MessagingException {
    
    
        sendEmail("[email protected]", "邮件内容");
    }

}

5.效果如下图

在这里插入图片描述

6.思考

利用邮件推送功能,我们可以直接封装成一个工具类,改造成登陆注册页面时候的验证码功能和用户邮件提示功能,以及其他的一些功能

猜你喜欢

转载自blog.csdn.net/weixin_43967679/article/details/107879747