How to use the Ghost API to schedule an email-only newsletter
Documentation? Sorta. Here's what works.
This ate an hour of my life, so maybe I can save you some time. For whatever reason, sending a post to the Ghost Admin API for emailing in the future is not a one-step process. Nope! You've got to first create it as a draft, then edit it. Here's the process:
async function pushPostToGhost(HTML) {
const api = new GhostAdminAPI({
url: process.env.GHOST_API_URL,
version: "v5.0",
key: process.env.GHOST_ADMIN_API_KEY
});
// Change to when you actually want the email sent...
let schedule_time = moment().add(1, 'minutes').format('YYYY-MM-DDTHH:mm:ssZ');
let post = {
title: `Spiffy title`,
html: `
${HTML}
`,
status: 'draft',
tags: ['#some-tag'],
email_only: true
}
let response = await api.posts.add(post, {source: 'html'});
let edit = await api.posts.edit({
id: response.id,
updated_at: response.updated_at,
email_only: true,
status: 'scheduled',
published_at: schedule_time
}, {newsletter: 'default-newsletter', email_segment: 'all'
});
return edit;
}
Huge kudos to the folks over on the Ghost Forum for discussion that got me there.