1. 起初,要在网易注册一个邮箱,登录后如图所示点击 POP3/SMTP/IMAP 。
2. 启动 POP3 ,填好相应的信息,并复制获取到的授权码。
3. 自行创建 Maven 工程,并导入以下依赖:
<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 设置抄送者(注意:若无此条,网易会将其视为垃圾短信而无法发送) 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(“other@qq.com”, “邮件内容”); }}
5. 效果展示如下图。
6. 思考
借助邮件推送的功能,我们能够将其直接封装为一个工具类,改造为登录注册页面时的验证码功能、用户邮件提示功能以及其他一些相关功能。
2 本站部分内容来源于网络,仅供学习与参考,如有侵权,请联系网站管理员删除
3 本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
4 精准获客感谢您的访问!希望本站内容对您有所帮助!
暂无评论内容