前言
大多开发项目中都会有着发送邮件的需求,例如定时发送邮件,验证邮件等等。
此文介绍发送邮件功能
前期准备
- mail.jar包
- 创建一个class文件
class文件内容(模板):
public class Mail {
public static void sendMail(String email,String subject, String emailMsg)
throws AddressException, MessagingException {
// 1.创建一个程序与邮件服务器会话对象 Session
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "SMTP");
props.setProperty("mail.host", "smtp.163.com");
//smtp.163.com此为网易的smtp服务器网址,不同邮箱不同(注意)
props.setProperty("mail.smtp.auth", "true");
// 指定验证为true
// 创建验证器
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("Ruian****", "199604****");
//Ruian****为发送邮件的邮箱名
//199604****为客户端授权码(注意)