我们在开发过程中,很有可能需要使用java调用邮箱的接口,来发送给指定邮箱邮件。本篇文章主要讲解通过java编写使用qq邮箱发送邮件的例子。
首先,我们要去设置一下qq邮箱的授权码,参考:https://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256
然后我们需要引入关于mail的maven依赖:
<dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency>
接着我们编写邮件发送工具类,MailUtils.java:
package com.allen.utils;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.sun.mail.util.MailSSLSocketFactory;
/**
* 邮件发送工具类
* */
public class MailUtils {
private static final String MY_EMAIL = "************@qq.com"; //这里填的qq邮箱,也就是发件人
private static final String MY_CODE = "*************"; //这里填入刚刚我们配置的qq邮箱授权码
public static void sendMail(String to, String vcode) throws Exception {
//设置发送邮件的主机 smtp.qq.com
String host = "smtp.qq.com";
//1.创建连接对象,连接到邮箱服务器
Properties props = System.getProperties();
//Properties 用来设置服务器地址,主机名 。。 可以省略
//设置邮件服务器
props.setProperty("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
//SSL加密
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
//props:用来设置服务器地址,主机名;Authenticator:认证信息
Session session = Session.getDefaultInstance(props, new Authenticator() {
@Override
//通过密码认证信息
protected PasswordAuthentication getPasswordAuthentication() {
//new PasswordAuthentication(用户名, password);
//这个用户名密码就可以登录到邮箱服务器了,用它给别人发送邮件
return new PasswordAuthentication(MY_EMAIL, MY_CODE);
}
});
try {
Message message = new MimeMessage(session);
//2.1设置发件人:
message.setFrom(new InternetAddress(MY_EMAIL));
//2.2设置收件人 这个TO就是收件人
message.setRecipient(RecipientType.TO, new InternetAddress(to));
//2.3邮件的主题
message.setSubject("java测试发送邮件");
//2.4设置邮件的正文 第一个参数是邮件的正文内容 第二个参数是:是文本还是html的连接
message.setContent(vcode, "text/html;charset=UTF-8");
//3.发送一封激活邮件
Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}测试:
@Test
public void mailTest(){
try {
MailUtils.sendMail("liqinglin0314@aliyun.com", "哈哈哈,这是一条测试信息~~~");
} catch (Exception e) {
e.printStackTrace();
}
}