从托管在Google存储上的静态网站发送电子邮件,可以通过以下步骤实现:
// 导入Gmail API库
const { google } = require('googleapis');
// 配置Gmail API凭据
const credentials = require('path/to/credentials.json');
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);
// 授权访问Gmail API
const authUrl = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: ['https://www.googleapis.com/auth/gmail.send'],
});
console.log('请访问以下URL以授权访问Gmail API:', authUrl);
// 获取授权码并交换访问令牌
const authCode = '授权码';
oAuth2Client.getToken(authCode, (err, token) => {
if (err) return console.error('获取访问令牌时出错:', err);
oAuth2Client.setCredentials(token);
// 创建Gmail API客户端
const gmail = google.gmail({ version: 'v1', auth: oAuth2Client });
// 构建电子邮件消息
const email = {
to: '收件人邮箱',
subject: '邮件主题',
message: '邮件内容',
};
// 发送电子邮件
gmail.users.messages.send({
userId: 'me',
requestBody: {
raw: createRawMessage(email),
},
}, (err, res) => {
if (err) return console.error('发送电子邮件时出错:', err);
console.log('电子邮件已发送:', res.data);
});
});
// 创建原始电子邮件消息
function createRawMessage(email) {
const messageParts = [
`To: ${email.to}`,
'Content-Type: text/html; charset=utf-8',
'MIME-Version: 1.0',
`Subject: ${email.subject}`,
'',
email.message,
];
const rawMessage = messageParts.join('\n').trim();
const encodedMessage = Buffer.from(rawMessage).toString('base64');
return encodedMessage;
}
请注意,上述代码仅为示例,您需要根据自己的具体需求和开发环境进行适当的修改和调整。
推荐的腾讯云相关产品和产品介绍链接地址:
请注意,以上推荐的腾讯云产品仅供参考,您可以根据自己的需求选择适合的产品和服务。
领取专属 10元无门槛券
手把手带您无忧上云