服务中有邮箱验证相关的需求,本实例通过本机127.0.0.1 25发送邮件。
1.加入依赖
<dependency>
<groupId>javamail</groupId>
<artifactId>javamail</artifactId>
<version>1.3.2</version>
</dependency>
2.java代码
package *.*.mail;
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.Properties;
/**
* Created by user on 16/3/1.
*/
public class MailUtil {
public static void sendMail(String validateCode,String mail){
try {
Properties prop = new Properties();
prop.setProperty("mail.host", "127.0.0.1");
//prop.put("mail.smtp.localhost", "localhost");
prop.put("mail.transport.protocol", "smtp");
//使用JavaMail发送邮件的5个步骤
//1、创建session
Session session = Session.getInstance(prop);
//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
session.setDebug(true);
//2、通过session得到transport对象
Transport ts = session.getTransport();
//3、使用邮箱的用户名和密码连上邮件服务器,发送邮件时,发件人需要提交邮箱的用户名和密码给smtp服务器,用户名和密码都通过验证之后才能够正常发送邮件给收件人。使用25端口不需要认证,直接连接即可。
ts.connect();
//4、创建邮件
Message message = createSimpleMail(session,validateCode,mail);
//5、发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}catch (Exception e){
e.printStackTrace();
}
}
public static MimeMessage createSimpleMail(Session session,String validateCode,String mail)
throws Exception {
//创建邮件对象
MimeMessage message = new MimeMessage(session);
//指明邮件的发件人
message.setFrom(new InternetAddress("test@test.com"));
//指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
message.setRecipient(Message.RecipientType.TO, new InternetAddress(mail));
//邮件的标题
message.setSubject("验证码");
//邮件的文本内容
message.setContent(validateCode, "text/html;charset=UTF-8");
//返回创建好的邮件对象
return message;
}
}