使用微软国际版的看:javamail微软邮箱imap协议使用oauth2.0认证–微软邮箱国际版
一、账号授权
imap协议使用oauth2.0身份认证,必须先对帐号进行授权,授权方式可以看我之前的文章:微软邮箱oath2协议下,使用imap协议时对账号授权,如果不进行授权,即使认证通过了,但是获取邮件相关文件夹时,会报错:A3 BAD User is authenticated but not connected.;
具体报错如下:
二、直接上代码
package test;
import com.alibaba.fastjson.JSON;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
public class TestImapAndOauth2By21V {
public static void main(String[] args) {
String mailAddress = "邮箱账号";
String tenant_id = "租户id";
String client_id = "应用id";
String client_secret = "密钥的值";//注意不是密钥的id
String scope = "https://partner.outlook.cn/.default";
String url = "https://login.partner.microsoftonline.cn/" + tenant_id + "/oauth2/v2.0/token";
org.apache.commons.httpclient.HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url);
postMethod.addRequestHeader("accept", "*/*");//固定参数
postMethod.addRequestHeader("connection", "Keep-Alive");//固定参数
postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=GBK");//固定参数
//必须设置下面这个Header
postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");//固定参数
//添加请求参数
postMethod.addParameter("grant_type", "client_credentials");//固定参数
postMethod.addParameter("client_id", client_id);
postMethod.addParameter("client_secret", client_secret);
postMethod.addParameter("scope", scope);
String token = "";
try {
int code = httpClient.executeMethod(postMethod);
String resBody = postMethod.getResponseBodyAsString();
if (code == 200) {
Map<String, String> map = JSON.parseObject(resBody, Map.class);
token = map.get("access_token");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
postMethod.releaseConnection();
}
try {
String protocol = "imap";
int port = 993;
String host = "partner.outlook.cn";
Properties properties = new Properties();
properties.setProperty("mail." + protocol + ".ssl.enable", "true");
properties.setProperty("mail." + protocol + ".auth.mechanisms", "XOAUTH2");
Session session = Session.getInstance(properties);
//session.setDebug(true);
Store store = session.getStore(protocol);
store.connect(host, port, mailAddress, token);
System.out.println("测试通过");
Folder inboxFolder = getInboxFolder(store);
Message[] messages = inboxFolder.getMessages();
System.out.println(messages.length);
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("不通过");
}
}
public static Folder getInboxFolder(Store store) throws Exception {
Folder folder = null;
if(store != null) {
folder = store.getDefaultFolder();
folder = folder.getFolder("INBOX");
if(!folder.isOpen()) {
folder.open(Folder.READ_ONLY);
}
}
return folder;
}
}
其实和国际版的比较,也就scope 、url 还有host 这三个参数不一样,其他的都一样