我正在创建一个googlesheet插件来发送邮件。而对于发送邮件,我使用的是sendgrid。 我找不到任何使用Google Appscript发送邮件的文档或示例代码。这是我正在使用的代码,但它并不好。
50%
有没有人有任何想法或代码使用googl appscript发送带有sendgrid的电子邮件?
答案 0 :(得分:5)
尝试以下代码。它对我有用
var SENDGRID_KEY ='Your API KEY';
var headers = {
"Authorization" : "Bearer "+SENDGRID_KEY,
"Content-Type": "application/json"
}
var body =
{
"personalizations": [
{
"to": [
{
"email": "email id of the sender"
}
],
"subject": "Hello, World!"
}
],
"from": {
"email": "From email id"
},
"content": [
{
"type": "text",
"value": "Hello, World!"
}
]
}
var options = {
'method':'post',
'headers':headers,
'payload':JSON.stringify(body)
}
var response = UrlFetchApp.fetch("https://api.sendgrid.com/v3/mail/send",options);
Logger.log(response);
还要确保您在SendGrid中创建的API密钥具有发送电子邮件所需的所有凭据
答案 1 :(得分:0)
对于以后使用交易电子邮件模板遇到此问题的任何人:
这是发送功能(类似于Nikil Mathew的回答,但具有动态数据的交易电子邮件模板):
export const sendBySendGrid = (toEmail, templateId, dynamicTemplateData) => {
const headers = {
Authorization: `Bearer ${process.env.SENDGRID_API_KEY}`,
'Content-Type': 'application/json',
}
const body = {
from: {
email: process.env.SENDGRID_FROM_EMAIL,
name: process.env.SENDGRID_FROM_NAME,
},
personalizations: [
{
to: [
{
email: toEmail,
},
],
dynamic_template_data: dynamicTemplateData,
},
],
template_id: templateId,
}
const options = {
method: 'POST',
headers,
payload: JSON.stringify(body),
}
const response = UrlFetchApp.fetch('https://api.sendgrid.com/v3/mail/send', options)
Logger.log(response)
}
您可以使用SendGrid凭据更新process.env.SENDGRID_API_KEY
,process.env.SENDGRID_FROM_EMAIL
,process.env.SENDGRID_FROM_NAME
答案 2 :(得分:0)
这是我现在在Google Apps脚本中为我工作的内容,包括使用动态模板并为我的SendGrid模板中的“把手”插入动态数据:
var SENDGRID_KEY ='API_KEY';
var headers = {
"Authorization" : "Bearer "+SENDGRID_KEY,
"Content-Type": "application/json"
}
function sendEmail_1() {
var body = {
"personalizations": [
{
"to": [
{
"email": "test@test.com",
"name": "Test Name"
}
],
"bcc": [
{
"email": "test@test.com"
}
],
"dynamic_template_data":
{
"firstName": "Marco Polo"
}
}
],
"from":
{
"email": "test@test.com",
"name": "Test Name"
},
"reply_to": {
"email": "test@test.com"
},
"template_id":"TEMPLATE_ID"
}
var options = {
'method':'post',
'headers':headers,
'payload':JSON.stringify(body)
}
var response = UrlFetchApp.fetch("https://api.sendgrid.com/v3/mail/send",options);
}