java发送邮件,及邮件验证码
最近在做市新闻网站的项目,有一个功能是用户忘记密码,通过邮件验证码等其他信息修改密码。不过现在的身份验证个人觉着手机验证码更加方便灵活,不过公司要求用邮箱那就用邮箱吧。
1、想要完成邮件发送功能,需要导入一个jar包--commons-email-1.4.jar。
<!-- 邮件 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.5</version>
</dependency>
2、要想实现邮件发送功能,必须准备一个可以正常使用的邮箱,同时这个邮箱要开启POP3/SMTP服务。我使用的是QQ邮箱,开启POP3/SMTP服务的方法如下:
(1)登录QQ邮箱,点击顶部--设置--账户--POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务(图片中我的pop3服务已经开启了)。
(2)如果你的服务是关闭状态,则点击后面的开启,会弹出一个对话框。要求使用绑定的手机号发送一条短信,发送成功后,点击“我已发送”。
(3)点击后页面弹出另一个对话框,在对话框中会有一个16位的授权码,记录下来,以后会用。
3、导入jar,完成邮箱的服务开启后,需要编写邮件发送的方法,我使用的是springboot项目。
public class SendMailUtil {
private static final String from = "发件人邮箱";
private static final String fromName = "邮件的标题";
private static final String charSet = "utf-8";
private static final String username = "发件人邮箱";
private static final String password = "开启发件邮箱pop3服务时的授权码";
private static final String subject = "邮件的主题";
private static Map<String, String> hostMap = new HashMap<String, String>();
static {
// 126
hostMap.put("smtp.126", "smtp.126.com");
// qq
hostMap.put("smtp.qq", "smtp.qq.com");
// 163
hostMap.put("smtp.163", "smtp.163.com");
// sina
hostMap.put("smtp.sina", "smtp.sina.com");
// tom
hostMap.put("smtp.tom", "smtp.tom.com");
// 263
hostMap.put("smtp.263", "smtp.263.net");
// yahoo
hostMap.put("smtp.yahoo", "smtp.mail.yahoo.com");
// hotmail
hostMap.put("smtp.hotmail", "smtp.live.com");
// gmail
hostMap.put("smtp.gmail", "smtp.gmail.com");
hostMap.put("smtp.port.gmail", "465");
// sygongzhi.com
hostMap.put("smtp.sygongzhi", "smtp.mxhichina.com");
}
private static boolean validate = true;// 是否需要身份验证
public static Properties getProperties() throws Exception {
Properties p = new Properties();
p.put("mail.smtp.host", getHost(from));
p.put("mail.smtp.port", getSmtpPort(from));
p.put("mail.smtp.auth", validate ? "true" : "false");
return p;
}
public static String getHost(String email) throws Exception {
Pattern pattern = Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
Matcher matcher = pattern.matcher(email);
String key = "unSupportEmail";
if (matcher.find()) {
key = "smtp." + matcher.group(1);
}
if (hostMap.containsKey(key)) {
return hostMap.get(key);
} else {
throw new Exception("unSupportEmail");
}
}
public static int getSmtpPort(String email) throws Exception {
Pattern pattern = Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
Matcher matcher = pattern.matcher(email);
String key = "unSupportEmail";
if (matcher.find()) {
key = "smtp.port." + matcher.group(1);
}
if (hostMap.containsKey(key)) {
return Integer.parseInt(hostMap.get(key));
} else {
return 25;
}
}
/**
* 发送普通邮件
*
* @param toMailAddr
* 收信人地址
* @param subject
* email主题
* @param message
* 发送email信息
*/
public static void sendCommonMail(String toMailAddr, String subject, String message) {
HtmlEmail hemail = new HtmlEmail();
try {
hemail.setHostName(getHost(from));
hemail.setSmtpPort(getSmtpPort(from));
hemail.setCharset(charSet);
hemail.addTo(toMailAddr);
hemail.setFrom(from, fromName);
hemail.setAuthentication(username, password);
hemail.setSubject(subject);
hemail.setMsg(message);
hemail.send();
System.out.println("email send true!");
} catch (Exception e) {
e.printStackTrace();
System.out.println("email send error!");
}
}
// @SuppressWarnings("unchecked")
public static String getAppPath(Class<?> cls) {
// 检查用户传入的参数是否为空
if (cls == null)
throw new IllegalArgumentException("参数不能为空!");
ClassLoader loader = cls.getClassLoader();
// 获得类的全名,包括包名
String clsName = cls.getName() + ".class";
// 获得传入参数所在的包
Package pack = cls.getPackage();
String path = "";
// 如果不是匿名包,将包名转化为路径
if (pack != null) {
String packName = pack.getName();
// 此处简单判定是否是Java基础类库,防止用户传入JDK内置的类库
if (packName.startsWith("java.") || packName.startsWith("javax."))
throw new IllegalArgumentException("不要传送系统类!");
// 在类的名称中,去掉包名的部分,获得类的文件名
clsName = clsName.substring(packName.length() + 1);
// 判定包名是否是简单包名,如果是,则直接将包名转换为路径,
if (packName.indexOf(".") < 0)
path = packName + "/";
else {// 否则按照包名的组成部分,将包名转换为路径
int start = 0, end = 0;
end = packName.indexOf(".");
while (end != -1) {
path = path + packName.substring(start, end) + "/";
start = end + 1;
end = packName.indexOf(".", start);
}
path = path + packName.substring(start) + "/";
}
}
// 调用ClassLoader的getResource方法,传入包含路径信息的类文件名
java.net.URL url = loader.getResource(path + clsName);
// 从URL对象中获取路径信息
String realPath = url.getPath();
// 去掉路径信息中的协议名"file:"
int pos = realPath.indexOf("file:");
if (pos > -1)
realPath = realPath.substring(pos + 5);
// 去掉路径信息最后包含类文件信息的部分,得到类所在的路径
pos = realPath.indexOf(path + clsName);
realPath = realPath.substring(0, pos - 1);
// 如果类文件被打包到JAR等文件中时,去掉对应的JAR等打包文件名
if (realPath.endsWith("!"))
realPath = realPath.substring(0, realPath.lastIndexOf("/"));
/*------------------------------------------------------------
ClassLoader的getResource方法使用了utf-8对路径信息进行了编码,当路径
中存在中文和空格时,他会对这些字符进行转换,这样,得到的往往不是我们想要
的真实路径,在此,调用了URLDecoder的decode方法进行解码,以便得到原始的
中文及空格路径
-------------------------------------------------------------*/
try {
realPath = java.net.URLDecoder.decode(realPath, "utf-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println("realPath----->" + realPath);
return realPath;
}
}
4、写一个controller,调用上面的方法。
@Controller
@RequestMapping(value = "/email")
public class testSendEmail {
@RequestMapping(value = "/sendEmail")
@ResponseBody
public void sendEmail(){
SendMailUtil.sendCommonMail("要发送的目标邮箱","邮件主题","邮件内容");
}
}