Unable to send mail using gmail api node js

风格不统一 提交于 2020-12-13 02:59:29

问题


I have followed gmail api for sending email. I am getting error as:

"message": "400 - \"{\n \\"error\\": {\n \\"errors\\": [\n {\n \\"domain\\": \\"global\\",\n \\"reason\\": \\"invalidArgument\\",\n \\"message\\": \\"'raw' RFC822 payload message string or uploading message via /upload/* URL required\\"\n }\n ],\n \\"code\\": 400,\n \\"message\\": \\"'raw' RFC822 payload message string or uploading message via /upload/* URL required\\"\n }\n}\n\""

Here is the piece of code I have written for sending mail using gmail api with node.js. Help me out to resolve the issue.

router.post('/composeMail', async (req, res, next) => {
    function makeBody(to, from, subject, message) {
        let str = ["Content-Type: text/plain; charset=\"UTF-8\"\n",
            "Content-length: 5000\n",
            "Content-Transfer-Encoding: message/rfc822\n",
            "to: ", to,"\n",
            "from: ", from,"\n",
            "subject: ", subject,"\n\n",
            message
        ].join('');
        console.log("String: ", str);
        // let encodedMail = new Buffer(str).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');
        let encodedMail = btoa(str).replace(/\+/g, '-').replace(/\//g, '_');
        return encodedMail;
    }
    let raw = makeBody("dinesh.kumar@gmail.com", "dinesh.kumar@gmail.com", "Test mail", "Everything is fine");
    let obj = {};
    obj.raw = raw;
    let body = JSON.stringify(obj);
    let option = {
        url: "https://www.googleapis.com/gmail/v1/users/userId/messages/send",
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${req.query.access_token}`
        },
        qs: {
            userId: 'me'
        },
        body: body
    };

    await request(option).then(body => {
        return res.apiOk(body);
    }).catch(err => {
        return res.apiError(err);
    })
});

回答1:


  • You want to send an email using Gmail API by the request module.

If my understanding is correct, how about this modification? I think that there are several answers. So please think of this as one of them.

Modification points:

  • Please use https://www.googleapis.com/upload/gmail/v1/users/userId/messages/send as the endpoint.
  • Use the value as a string.
  • Add 'Content-Type': 'message/rfc822' to the headers.

Modified script:

Please modify makeBody() as follows.

function makeBody(to, from, subject, message) {
    let str = [
        "to: ", to, "\n",
        "from: ", from, "\n",
        "subject: ", subject, "\n\n",
        message,
    ].join('');
    return str;
}

Please modify option as follows.

let raw = makeBody("dinesh.kumar@gmail.com", "dinesh.kumar@gmail.com", "Test mail", "Everything is fine");
const userId = 'me'; // Please modify this for your situation.
let option = {
    url: "https://www.googleapis.com/upload/gmail/v1/users/" + userId + "/messages/send",
    method: 'POST',
    headers: {
        'Authorization': `Bearer ${req.query.access_token}`,
        'Content-Type': 'message/rfc822',
    },
    body: raw,
};

Note:

  • This modified script supposes that Gmail API is enabled at API console and the required scope for sending emails is included in the scopes of access token.

Reference:

  • Users.messages: send

In my environment, I could confirm that this modified script worked fine. But if this was not what you want, I'm sorry.



来源:https://stackoverflow.com/questions/53263239/unable-to-send-mail-using-gmail-api-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!