
JavaMail,顾名思义,提供给开发者处理电子邮件相关的编程接口。它是Sun发布的用来处理email的API。它可以方便地执行一些常用的邮件传输。我们可以基于JavaMail开发出类似于Microsoft Outlook的应用程序。
2.JavaMail的协议这里使用网易云邮箱 进入后开通SMPT服务
点击开启SMTP服务 扫码发送短信开通 填写你所使用的设备 记住授权码 后面要使用 这很重要
4.2引入JavaMail在pom.xml中添加如下依赖
javax.mail
mail
1.4.4
为了让Spring与JavaMail集成 还需要在pom.xml中引入如下依赖
org.springframework spring-context-suppport${spring.version}
如果是web项目 引入如下jar包
5.传统的邮件开发 6.邮件发送工具类抽取package com.czxy.utils;
import javax.mail.Address;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import java.util.Properties;
public class MailUtil {
public static void sendMsg(String to ,String subject ,String content) throws Exception{
// 创建属性文件
Properties props = new Properties();
// 设置主机地址 smtp.qq.com smtp.sina.com 使用的本地易邮服务器
props.setProperty("mail.smtp.host", "smtp.163.com");
// 认证,提供用户名和密码进行校验
props.setProperty("mail.smtp.auth", "true");
//2.产生一个用于邮件发送的Session对象,连接服务器主机
Session session = Session.getInstance(props);
//3.产生一个邮件的消息对象
MimeMessage message = new MimeMessage(session);
//4.设置消息的发送者
Address fromAddr = new InternetAddress("发件人的邮箱账号");
message.setFrom(fromAddr);
//5.设置消息的接收者
Address toAddr = new InternetAddress(to);
//TO 直接发送 CC抄送 BCC密送
message.setRecipient(RecipientType.TO, toAddr);
//6.设置主题
message.setSubject(subject);
//7.设置正文
message.setText(content);
//8.准备发送,得到火箭
Transport transport = session.getTransport("smtp");
//9.设置火箭的发射目标
transport.connect("smtp.163.com", "发送人的邮箱账号", "前面保存的授权码");
//10.发送
transport.sendMessage(message, message.getAllRecipients());
//11.关闭
transport.close();
}
}