Javascript Gmail API代码,用于在没有用户身份验证的情

时间:2016-12-15 02:45:14

标签: javascript gmail-api

我开发了一个网站,用户填写表单并使用Gmail API发送,但不想要授权按钮,我无法编写服务器端代码。我怎么能这样做?

我的代码:

<form id="form1">
//Form inputs
<button type="button" class="mybutton" onclick="sendEmail()" id="btn_cerrar">SIGN UP</button>

<button id="authorize-button" style="display:none" class="btn btn-primary" onclick="handleAuthClick()">Authorize</button>

<script>    
var clientId = '...apps.googleusercontent.com';
var apiKey = '...xg';
var scopes =
'https://www.googleapis.com/auth/gmail.readonly ' +
'https://www.googleapis.com/auth/gmail.send';

    function handleClientLoad() {
        gapi.client.setApiKey(apiKey);
        window.setTimeout(checkAuth, 1);
    }

    function checkAuth() {
        gapi.auth.authorize({
            client_id: clientId,
            scope: scopes,
            immediate: true
        }, handleAuthResult);
    }

    function handleAuthClick() {
        gapi.auth.authorize({
            client_id: clientId,
            scope: scopes,
            immediate: false
        }, handleAuthResult);
        return false;
    }

    function handleAuthResult(authResult) {
        if (authResult && !authResult.error) {
            loadGmailApi();
        } else {
           document.getElementById('authorize-button').style.display="block";
        }
    }

    function loadGmailApi() {
        gapi.client.load('gmail', 'v1', console.log("loading api"));
    }

    function sendEmail() {
          document.getElementById('btn_cerrar').style.display="none";

        var d = new Date();
        var month = d.getMonth()+1;
        var day = d.getDate();
        var hou = d.getHours();
        var min = d.getMinutes();
        var sec = d.getSeconds();
        var output = d.getFullYear() + '-' +
            (month<10 ? '0' : '') + month + '-' +
            (day<10 ? '0' : '') + day + 'T' +
            (hou<10 ? '0' : '') + hou + ':' +
            (min<10 ? '0' : '') + min + ':' +
            (sec<10 ? '0' : '') + sec;  

        var adf='... form data'          
        sendMessage(
          {
              'To': 'xxx@gmail.com',
              'Subject': 'iLeads'
          },
          adf,
          console.log('sent')

        );
        return false;
    }

    function sendMessage(headers_obj, message, callback) {
        var email = '';

        for (var header in headers_obj)
            email += header += ": " + headers_obj[header] + "\r\n";

        email += "\r\n" + message;

        var sendRequest = gapi.client.gmail.users.messages.send({
            'userId': 'yrausquinilead@gmail.com',
            'resource': {
                'raw': window.btoa(email).replace(/\+/g, '-').replace(/\//g, '_')
            }
        });

        return sendRequest.execute(callback);
    }
</script>

0 个答案:

没有答案