作为与庞大用户群沟通工作的一部分,我每天需要发送超过 75,000 封电子邮件。我正在联系的用户的电子邮件存储在 CSV 文件中。我一直在使用 Postman Runner 通过 SendGrid(电子邮件 API)发送这些请求,但是由于容量如此之大,我的计算机要么变慢,要么 Postman 在批处理完成之前完全崩溃。即使它没有崩溃,通过 Runner 发送这么多 POST 请求也需要 3 个小时以上。
我想将包含电子邮件的 CSV 上传到 Cloud Storage 存储桶中,然后使用 Cloud Functions 访问该文件,为每封电子邮件发送一个 POST 请求。这样,所有的处理都可以由 GCP 处理,而不是由我的个人机器处理。但是,我似乎无法让 Cloud Function 逐行读取 CSV 数据。我尝试使用 Cloud Storage NodeJS 客户端库中的 createReadStream() 以及 csv-parser,但无法使此解决方案正常工作。以下是我尝试过的:
const sendGridMail = require('@sendgrid/mail');
const { Storage } = require('@google-cloud/storage');
const fs = require('fs');
const csv = require('csv-parser');
exports.sendMailFromCSV = (file, context) => {
console.log(` Event: ${context.eventId}`);
console.log(` Event Type: ${context.eventType}`);
console.log(` Bucket: ${file.bucket}`);
console.log(` File: ${file.name}`);
console.log(` Metageneration: ${file.metageneration}`);
console.log(` Created: ${file.timeCreated}`);
console.log(` Updated: ${file.updated}`);
const storage = new Storage();
const bucket = storage.bucket(file.bucket);
const remoteFile = bucket.file(file.name);
console.log(remoteFile);
let emails = [];
fs.createReadStream(remoteFile)
.pipe(csv())
.on('data', function (row) {
console.log(`Email read: ${row.email}`);
emails.push(row.email);
//send email using the SendGrid helper library
const msg = {
to: [{
"email": row.email;
}],
from: "fakeemail@gmail.com",
template_id: "fakeTemplate",
};
sendGridMail.send(msg).then(() =>
context.status(200).send(file.body))
.catch(function (err) {
console.log(err);
context.status(400).send(file.body);
});
})
.on('end', function () {
console.table(emails);
});
};
Cloud Function 当前由上传到 Cloud Storage 存储分区触发。
有没有办法在不将文件加载到内存的情况下解决这个问题?Cloud Functions 是向下移动的正确路径,还是使用 App Engine 或其他工具会更好?愿意尝试任何将此流程移至云端的 GCP 解决方案