通过outlook.office365.comJMeter使用密钥向www.example.com发送邮件

wfveoks0  于 2023-01-20  发布在  其他
关注(0)|答案(1)|浏览(342)

我有一个client_id和连接outlook.office365.com服务器的密钥。我必须通过JMeter向服务器发送邮件。
我没有看到任何选项提供上述密钥在我的SMTP采样器。我该怎么做呢?

ql3eal8s

ql3eal8s1#

我不认为您可以使用SMTP采样器来完成此操作,从JMeter 5.5开始,它只允许用户名/密码身份验证
如果您的邮箱不允许使用用户名和密码进行SMTP连接,那么唯一的选择就是使用JSR223采样器和Groovy language
比如:

import com.fasterxml.jackson.databind.JavaType
import com.fasterxml.jackson.databind.ObjectMapper
import org.apache.commons.io.IOUtils
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClients
import org.apache.http.message.BasicHeader

import javax.mail.Session
import javax.mail.Store

public String getAuthToken(String tanantId, String clientId, String client_secret) throws ClientProtocolException, IOException {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost loginPost = new HttpPost("https://login.microsoftonline.com/" + tanantId + "/oauth2/v2.0/token");
    String scopes = "https://outlook.office365.com/.default";
    String encodedBody = "client_id=" + clientId + "&scope=" + scopes + "&client_secret=" + client_secret
    +"&grant_type=client_credentials";
    loginPost.setEntity(new StringEntity(encodedBody, ContentType.APPLICATION_FORM_URLENCODED));
    loginPost.addHeader(new BasicHeader("cache-control", "no-cache"));
    CloseableHttpResponse loginResponse = client.execute(loginPost);
    InputStream inputStream = loginResponse.getEntity().getContent();
    byte[] buffer = new byte[4096];
    byte[] response = IOUtils.readFully(inputStream, buffer);
    ObjectMapper objectMapper = new ObjectMapper();
    JavaType type = objectMapper.constructType(
            objectMapper.getTypeFactory().constructParametricType(Map.class, String.class, String.class));
    Map<String, String> parsed = new ObjectMapper().readValue(response, type);
    return parsed.get("access_token");
}

Properties props = new Properties();

props.put("mail.store.protocol", "imap");
props.put("mail.imap.host", "outlook.office365.com");
props.put("mail.imap.port", "993");
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imap.starttls.enable", "true");
props.put("mail.imap.auth", "true");
props.put("mail.imap.auth.mechanisms", "XOAUTH2");
props.put("mail.imap.user", mailAddress);
props.put("mail.debug", "true");
props.put("mail.debug.auth", "true");

String token = getAuthToken(tanantId, clientId, client_secret);
Session session = Session.getInstance(props);
session.setDebug(true);
Store store = session.getStore("imap");
store.connect("outlook.office365.com", mailAddress, token);
//do what you need here

您需要在JMeter类路径中包含jackson-databind库及其依赖项
更多信息:How to access outlook.office365.com IMAP form Java with OAUTH2

相关问题