繁体   English   中英

无法使用 Gmail API 获取 Gmail 只读邮件。 这里使用的语言是 html 和 javascript

[英]Not able to get Gmail Read-Only mails using Gmail API. The languages used here are html and javascript

我编写了三个文件,它们是:home-flatfull.jsp、settings-social-prefs.html 和 google-js-api-wrapper.js 文件。

在 home-flatfull.jsp 文件中,我写如下:

head.js('jscore/lib/base64.js', 'jscore/lib/google-js-api.js', 'jscore/lib/google-js-api-wrapper.js', function () {
        var config = {
            apiKey: 'AIzaSyCa52K8J68kr5b4S7Afu1FQzeleCfvzOFs',
            clientId: '492662354647-877atvgj1a0pu82nrutsm50rcmg0lufh.apps.googleusercontent.com',
            discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"],
            scopes: 'https://www.googleapis.com/auth/gmail.readonly',
            listener: function(response){
              console.log(' Check google ');
              console.log(response);
            }
        };

        googleJSAPI = GoogleJSAPI.getInstance(config);

      });

在 settings-social-prefs.html 文件中,我定义如下:

<a onclick="googleJSAPI.signIn()" class="btn btn-sm btn-default">
                            {{agile_lng_translate 'prefs-email' 'enable'}}
                        </a>

在 google-js-api-wrapper.js 文件中,我定义如下:

class GoogleJSAPI {

    emailRegx = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    instance;
    isActive = false;

    constructor(config) {
        console.log(' google code loaded ');
        gapi.load('client:auth2', () => {
            gapi.client.init({
                apiKey: config.apiKey,
                clientId: config.clientId,
                discoveryDocs: config.discoveryDocs,
                scope: config.scopes
            }).then(() => {
                this.isActive = true;
                console.log(' config loaded ');
                gapi.auth2.getAuthInstance().isSignedIn.listen(config.listener);
            }, (error) => {
                this.isActive = false;
                console.log(JSON.stringify(error, null, 2));
            });
        });
    }

    static getInstance(config) {
        if (!this.instance) {
            this.instance = new GoogleJSAPI(config);
        }
        return this.instance;
    }

    isActive() {
        return this.isActive;
    }

    isUserLoggedIn() {
        return gapi.auth2.getAuthInstance().isSignedIn.get();
    }

    signIn = () => {
        gapi.auth2.getAuthInstance().signIn();
    }

    signOut() {
        gapi.auth2.getAuthInstance().signOut();
    }

    getSorted(a, b) {
        return new Date(b.date).getTime() - new Date(a.date).getTime();
    }

    getMailList(queryObject) {
        return new Promise((resolve, reject) => {
            gapi.client.gmail.users.messages.list(queryObject).then(function (response) {
                resolve(response.result);
            });
        });
    }

    getMailContentById(id) {
        return new Promise((resolve, reject) => {
            gapi.client.gmail.users.messages.get({
                'userId': 'me', 'id': id
            }).then((response) => {
                let message = {};

                let headers = response.result.payload.headers;
                headers.forEach((header) => {
                    if (header.name === "From") {
                        message['from'] = header.value;
                    } else if (header.name === "Subject") {
                        message['subject'] = header.value;
                    } else if (header.name === "To") {
                        message['to'] = theader.value;
                    } else if (header.name === "Date") {
                        message['date'] = header.value;
                    } else if (header.name === "Cc") {
                        message['cc'] = header.value;
                    }
                });

                try {
                    if (response.result.payload) {
                        let body = "";
                        if (response.result.payload.body.size > 0) {
                            body = response.result.payload.body.data;
                        } else {
                            let bodyParts = response.result.payload.parts;
                            bodyParts.forEach((part, index) => {
                                if (part.type = "text/html") {
                                    //console.log(index);
                                    body = part.body.data;
                                    return;
                                }
                            });
                        }

                        message['message'] = Base64.decode(body);
                        // console.log(message['body']);
                    }
                } catch (e) {
                    //console.log(index);
                    //console.log(response.result);
                    //console.log(e);
                }
                resolve(message);
            });
        });
    }

    getInboxMailsWithContent(nextPageToken, fromEmail) {

        var qData = '';

        var queryObject = {
            'userId': 'me',
            'labelIds': ['INBOX']
        };

        if (nextPageToken) {
            queryObject['pageToken'] = nextPageToken;
        }

        if (fromEmail) {
            qData += 'from:' + fromEmail;
        }

        queryObject['q'] = qData;

        return new Promise((resolve, reject) => {
            gapi.client.gmail.users.messages.list(queryObject).then((response) => {

                let resultObject = {
                    nextPageToken: response.result.nextPageToken
                };

                let messages = new Array();
                let rawMessages = response.result.messages;

                rawMessages.forEach((rawMessage, index) => {
                    gapi.client.gmail.users.messages.get({
                        'userId': 'me', 'id': rawMessage.id
                    }).then((response) => {
                        let message = {
                            id: rawMessage.id
                        };

                        let headers = response.result.payload.headers;
                        headers.forEach((header) => {
                            if (header.name === "From") {
                                message['from'] = header.value;
                            } else if (header.name === "Subject") {
                                message['subject'] = header.value;
                            } else if (header.name === "To") {
                                message['to'] = header.value;
                            } else if (header.name === "Date") {
                                message['date'] = header.value;
                            } else if (header.name === "Cc") {
                                message['cc'] = header.value;
                            }
                        });

                        try {
                            if (response.result.payload) {
                                let body = "";
                                if (response.result.payload.body.size > 0) {
                                    body = response.result.payload.body.data;
                                } else {
                                    let bodyParts = response.result.payload.parts;
                                    bodyParts.forEach((part, index) => {
                                        if (part.type = "text/html") {
     f                                       //console.log(index);
                                            body = part.body.data;
                                            return;
                                        }
                                    });
                                }

                                message['message'] = Base64.decode(body);
                                // console.log(message['body']);
                            }
                        } catch (e) {
                            //console.log(index);
                            //console.log(response.result);
                            //console.log(e);
                        }
                        messages[index] = message;
                    });
                });

                // resultObject.messages = messages.sort(this.getSorted);
                resultObject.messages = messages;
                resolve(resultObject);

            });

        });
    }
}

function getInboxMailsWithContent(nextPageToken, fromEmail, callback) {
    googleJSAPI.getInboxMailsWithContent(nextPageToken, fromEmail).then((response) => {
        setTimeout(() => {
            if (callback && typeof (callback) == "function") {
                callback(response);
            }
        }, 3000);
    });
}

When I clicked on enable button in settings-social-prefs.html file, I am just getting the gmail login page and gmail password page once I have provided gmail username and password, I got the consent screen which asks to allow access to user's email然后我在没有收到 Gmail 只读邮件的情况下出现空白屏幕。当我点击启用按钮时,你能帮我获取 Gmail 只读邮件吗?

您可以关闭两因素身份验证(如果打开),还可以在谷歌我的帐户设置中“允许低安全性应用程序连接”

Ps:应避免在公共场合显示API :-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM