使用Javax.mail 发送邮件
详细说明都在代码中:
引入依赖
<!--sun定义的一套接收、发送电子邮件的API-->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
编写代码
package com.joyful.auth.service;
import org.springframework.stereotype.Service;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;
@Service
public class MailServiceImpl implements MailService {
/**
*
* @param mailTo:发送给谁
* @param activeCode:发送的激活码
* @throws Exception
*
* javax.mail API使用步骤
* 1、使用Properties封装连接信息
* 2、传入Session对象
* 3、创建邮件实体对象Message
* 4、使用Transport对象发送邮件
*/
public void sendEmail(String mailTo, String activeCode) throws Exception {
//收件人地址
String recipientAddress = mailTo;
//发件人账户名
String senderAccount = "[email protected]";
//发件人账户密码
String senderPassword = "***************";
//1、连接邮件服务器的参数配置
Properties props = new Properties();
//设置用户的认证方式
props.setProperty("mail.smtp.auth", "true");
//设置传输协议
props.setProperty("mail.transport.protocol", "smtp");
//设置发件人的SMTP服务器地址
props.setProperty("mail.smtp.host", "smtp.163.com");
//2、创建定义整个应用程序所需的环境信息的 Session 对象
Session session = Session.getInstance(props);
//设置调试信息在控制台打印出来
session.setDebug(true);
//3、创建邮件的实例对象
Message msg = createMimeMessage(session,recipientAddress,activeCode);
//4、根据session对象获取邮件传输对象Transport
Transport transport = session.getTransport();
//设置发件人的账户名和密码
transport.connect(senderAccount, senderPassword);
//如果只想发送给指定的人,可以如下写法
transport.sendMessage(msg, new Address[]{new InternetAddress(recipientAddress)});
//5、关闭邮件连接
transport.close();
}
/**
* 邮件格式
* @param session
* @param recipientAddress
* @return
* @throws Exception
*/
public static MimeMessage createMimeMessage(Session session, String recipientAddress, String md5)
throws Exception{
//1.创建一封邮件
MimeMessage message=new MimeMessage(session);
//发件人地址
String senderAddress = "[email protected]";
message.setFrom(new InternetAddress(senderAddress));
//4.Subject 邮件主题
message.setSubject("[I旅行]用户激活","UTF-8");
//5.邮件正文
message.setContent("账号 :"+recipientAddress+", 激活码是 :"+md5,"text/html;charset=UTF-8");
//6..设置发件时间
message.setSentDate(newDate());
//7.保存设置
message.saveChanges();
returnmessage;
}
}