如何使用SoapUI读取收件箱Gmail邮件

时间:2017-04-07 01:26:49

标签: soapui

作为测试的一部分,我们必须验证电子邮件中的文本。

现在我们正在使用SoapUI进行API自动化测试。

我们如何阅读Gmail收件箱中的电子邮件?

先谢谢。

1 个答案:

答案 0 :(得分:0)

我已经用Java实现了这段代码,希望这对你有用。请添加所有必要的罐子。

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;

import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.Gmail;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

import com.google.api.services.gmail.model.ListMessagesResponse;
import com.google.api.services.gmail.model.Message;
import java.util.ArrayList;

import org.apache.commons.codec.binary.Base64;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

public class GmailReader extends EmailReader implements EmailReaderOperations {

    private static final String userId = "orionmam2017@gmail.com";
    private static Gmail service;

    /** Application name. */
    private static final String APPLICATION_NAME =
            "Gmail API Java Quickstart";

    /** Directory to store user credentials for this application. */
    private static final java.io.File DATA_STORE_DIR = new java.io.File(
            System.getProperty("user.home"), ".credentials/gmail-java-quickstart");

    /** Global instance of the {@link FileDataStoreFactory}. */
    private static FileDataStoreFactory DATA_STORE_FACTORY;

    /** Global instance of the JSON factory. */
    private static final JsonFactory JSON_FACTORY =
            JacksonFactory.getDefaultInstance();

    /** Global instance of the HTTP transport. */
    private static HttpTransport HTTP_TRANSPORT;

    /** Global instance of the scopes required by this quickstart.
     *
     * If modifying these scopes, delete your previously saved credentials
     * at ~/.credentials/gmail-java-quickstart
     */
    private static final List<String> SCOPES =
            Arrays.asList(GmailScopes.GMAIL_READONLY);

    static {
        try {
            HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
            DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
        } catch (Throwable t) {
            t.printStackTrace();
            System.exit(1);
        }
    }

    /**
     * Constructor
     * @return Nothing
     * @throws IOException
     */
    public GmailReader() throws IOException {
        // Build a new authorized API client service.
        service = getGmailService();
    }

    /**
     * fetchActivationLink
     *
     * Fetches the email from Gmail account after waiting for defaultWaitInMilliseconds milliseconds
     */
    @Override
    public String fetchActivationLink() throws Exception {
        return this.fetchActivationLinkWithWait(defaultWaitInMilliseconds);
    }

    /**
     * fetchActivationLinkWithWait
     *
     * Fetches the email from Gmail account after waiting for <waitInMilliseconds> milliseconds
     */
    @Override
    public String fetchActivationLinkWithWait(int waitInMilliseconds) throws Exception {

        Thread.sleep(waitInMilliseconds);

        List<Message> activationEmails =
                listMessagesMatchingQuery(service, userId, "from:no-reply@stryker.com"); // string constant

        Message latestEmail = activationEmails.get(0);
        System.out.println(latestEmail.getId());

        Message detailedMessage = getMessage(service, userId, latestEmail.getId());
        System.out.println(detailedMessage.getId());

        // Read the body and parse into HTML format
        String htmlMail = new String(Base64.decodeBase64(detailedMessage.getPayload().getBody().getData()));

        Document doc = Jsoup.parse(htmlMail);
        Elements linkTag = doc.select("a[href]");
        activationURL = linkTag.attr("href");

        return activationURL;
    }

    public String fetchLinkAtIndex(int index) throws Exception {
        return this.fetchLinkAtIndexWithWait(index, defaultWaitInMilliseconds);
    }



    /**
     * Creates an authorized Credential object.
     * @return an authorized Credential object.
     * @throws IOException
     */
    private static Credential authorize() throws IOException {
        // Load client secrets.
        InputStream in =
                GmailReader.class.getResourceAsStream("resources/client_secret.json");
        GoogleClientSecrets clientSecrets =
                GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow =
                new GoogleAuthorizationCodeFlow.Builder(
                        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
                        .setDataStoreFactory(DATA_STORE_FACTORY)
                        .setAccessType("offline")
                        .build();
        Credential credential = new AuthorizationCodeInstalledApp(
                flow, new LocalServerReceiver()).authorize("user");
        System.out.println(
                "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
        return credential;
    }

    /**
     * Build and return an authorized Gmail client service.
     * @return an authorized Gmail client service
     * @throws IOException
     */
    private static Gmail getGmailService() throws IOException {
        Credential credential = authorize();
        return new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName(APPLICATION_NAME)
                .build();
    }

    /**
     * List all Messages of the user's mailbox matching the query.
     *
     * @param service Authorized Gmail API instance.
     * @param userId User's email address. The special value "me"
     * can be used to indicate the authenticated user.
     * @param query String used to filter the Messages listed.
     * @throws IOException
     */
    private static List<Message> listMessagesMatchingQuery(Gmail service, String userId,
                                                          String query) throws IOException {
        ListMessagesResponse response = service.users().messages().list("me").setQ(query).setMaxResults(5L).execute();

        List<Message> messages = new ArrayList<Message>();
        while (response.getMessages() != null) {
            messages.addAll(response.getMessages());
            if (response.getNextPageToken() != null) {
                String pageToken = response.getNextPageToken();
                response = service.users().messages().list(userId).setQ(query)
                        .setPageToken(pageToken).execute();
            } else {
                break;
            }
        }

//        For Debug purpose
//        for (Message message : messages) {
//            System.out.println(message.toPrettyString());
//        }

        return messages;
    }


    /**
     * Get Message with given ID.
     *
     * @param service Authorized Gmail API instance.
     * @param userId User's email address. The special value "me"
     * can be used to indicate the authenticated user.
     * @param messageId ID of Message to retrieve.
     * @return Message Retrieved Message.
     * @throws IOException
     */
    public static Message getMessage(Gmail service, String userId, String messageId)
            throws IOException {
        Message message = service.users().messages().get(userId, messageId).setFormat("FULL").execute();

        System.out.println("Message snippet: " + message.getSnippet());

        return message;
    }
}