如何使用节点js中的gmail api发送带附件的电子邮件?

时间:2018-02-27 21:36:00

标签: node.js gmail-api

大家好我是node.js的新手,我试图使用gmail API创建一个邮箱一切正常,除了在电子邮件中上传附件我发现java Python C#的例子我可以&# 39;找到关于它的节点的任何文档 非常感谢任何提示

    function makeBody(to, from, subject, message) {
    var str = ["Content-Type: multipart/mixed; charset=\"UTF-8\"\n",
        "MIME-Version: 1.0\n",
        "Content-Transfer-Encoding: 7bit\n",
        "to: ", to, "\n",
        "from: ", from, "\n",
        "subject: ", subject, "\n\n",
        message,
        file
    ].join('');
    var encodedMail = new Buffer(str).toString("base64").replace(/\+/g, '-').replace(/\//g, '_');
    return encodedMail;
}

function sendMessage(auth) {
        var raw = makeBody(tap, 'me', response.subject,response.content,response.files);
        gmail.users.messages.send({
            auth: auth,
            userId: 'me',
            resource: {
                raw: raw
            }
        }, function(err, response) {
            if (err) {
                console.log('Error  ' + err);
                return;}
if(response){
                    res.sendFile(__dirname+'/boite.html')
            }
        });
    }

3 个答案:

答案 0 :(得分:3)

这可能要花点时间,反正我会花点时间,以防以后有人想要替代方法。

Moxched方法的主要问题在于,可能他需要仔细研究MIME规范(这对我来说是很痛苦的),以便更好地理解发送附件所需的一些内容。

从我的立场出发,要能够使用gmail API发送附件和许多其他内容,您必须根据MIME规范构建所有请求,为此,您需要了解MIME的工作原理,包括边界。

Joris方法有效,但最终没有使用nodeJS库发送电子邮件。他之所以无法通过gmail API使用gmail-api-create-message-body包中的答案,是因为出于某种原因,此lib在其MIME消息的顶部生成了以下内容:

'Content-Type: multipart/related; boundary="foo_bar_baz"',
`In-Reply-To: fakeemail@gmail.com`,
`References: `,
`From: fakeemail2@gmail.com`,
`Subject: SUBJECT`,
`MIME-Version: 1.0`,
'',
`--foo_bar_baz`,
`Content-Type: application/json; charset="UTF-8"`,
'',
`{`,
`}`,
'',
`--foo_bar_baz`,
`Content-Type: message/rfc822`,
'',
...

由于某些原因,gmailAPI不喜欢这个...

我的建议是更好地理解MIME规范,这是一种非常简单的方法,那就是使用一些旧的反向工程,为此,我建议查看gmail-api-create-message-bodymail-composer的回复来自nodemailer。

使用nodemailer/lib/mail-composer,您将能够轻松地根据MIME规范生成必要的MIME消息,其中包括附件支持和所有其他内容。生成的MIME邮件与Gmail API兼容。我留下一个基于NodeJS文档示例的工作示例,该示例发送带有2个附件的电子邮件。

希望这会有所帮助!

const fs = require('fs');
const path = require('path');
const readline = require('readline');
const {google} = require('googleapis');

const MailComposer = require('nodemailer/lib/mail-composer');

// If modifying these scopes, delete token.json.
const SCOPES = [
  'https://mail.google.com',
  'https://www.googleapis.com/auth/gmail.readonly'
];
const TOKEN_PATH = 'token.json';

// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Gmail API.
  //authorize(JSON.parse(content), listLabels);

  authorize(JSON.parse(content), sendEmail);

});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
    client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getNewToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getNewToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error retrieving access token', err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

function sendEmail(auth) {

  // ----------nodemailer test----------------------------------------------------

  let mail = new MailComposer(
    {
      to: "FAKE_EMAIL@gmail.com",
      text: "I hope this works",
      html: " <strong> I hope this works </strong>",
      subject: "Test email gmail-nodemailer-composer",
      textEncoding: "base64",
      attachments: [
        {   // encoded string as an attachment
          filename: 'text1.txt',
          content: 'aGVsbG8gd29ybGQh',
          encoding: 'base64'
        },
        {   // encoded string as an attachment
          filename: 'text2.txt',
          content: 'aGVsbG8gd29ybGQh',
          encoding: 'base64'
        },
      ]
    });

  mail.compile().build( (error, msg) => {
    if (error) return console.log('Error compiling email ' + error);

    const encodedMessage = Buffer.from(msg)
      .toString('base64')
      .replace(/\+/g, '-')
      .replace(/\//g, '_')
      .replace(/=+$/, '');

    const gmail = google.gmail({version: 'v1', auth});
    gmail.users.messages.send({
      userId: 'me',
      resource: {
        raw: encodedMessage,
      }
    }, (err, result) => {
      if (err) return console.log('NODEMAILER - The API returned an error: ' + err);

      console.log("NODEMAILER - Sending email reply from server:", result.data);
    });

  })

  // ----------nodemailer test----------------------------------------------------


}

答案 1 :(得分:0)

Creating messages with attachments中有关于此的说明:

使用附件创建消息就像创建任何其他消息一样,但将文件作为多部分MIME消息上载的过程取决于编程语言。

对于NodeJS样本参考,请检查此SO Post

答案 2 :(得分:0)

坚持同样的问题,我设法通过左右抓住东西来构建解决方案。

您需要使用的是npm包gmail-api-create-message-body

npm package page

  const body = createBody({
    headers:{
      To:(msg.to.name) + " <" + msg.to.email + ">",
      From:(msg.from.name) + " <" + msg.from.email + ">",
      Subject:msg.subject
    },
    textHtml:msg.body.html,
    textPlain:msg.body.text,
    attachments:msg.files
  })

files是以下格式的数组。这只是一个例子:

    files: [{
      type: "image/jpeg",
      name: "id1.jpg",
      data:base64ImageData
    }, {
      type: "image/jpeg",
      name: "id2.jpg",
      data: base64ImageData
    }]

接下来我需要混合2个api。我想通过Google API执行所有操作,但这不起作用,我不想浪费时间了解原因(以及他们的文档+节点示例是灾难)

为了进行通话,我们需要身份验证令牌。这可以使用npm包google-auth-library

找到
await oauth2Client.getAccessToken()

我认为,如何将OAuth2与Google的详细信息超出了这个答案的范围。

接下来我们需要实际发送邮件。我无法使用官方Gmail API(继续获取Error: Recipient address required),因此我使用了request-promise的示例中显示gmail-api-create-message-body

await rp({
  method: 'POST',
  uri: 'https://www.googleapis.com/upload/gmail/v1/users/me/messages/send',
  headers: {
    Authorization: `Bearer ${oauth2Client.credentials.access_token}`,
    'Content-Type': 'multipart/related; boundary="foo_bar_baz"'
  },
  body: body
});

这种方法非常完美。