Skip to content

Instantly share code, notes, and snippets.

@johnholdun
Created May 11, 2019 03:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnholdun/726f404f7f63330756e4e7276a0668f5 to your computer and use it in GitHub Desktop.
Save johnholdun/726f404f7f63330756e4e7276a0668f5 to your computer and use it in GitHub Desktop.
Creates a Mailchimp campaign based on a URL. Useful if you tend to deliver your most recent blog post or whatever but aren't satisfied with the RSS campaign feature.
require 'rest-client'
require 'json'
require 'yaml'
require 'opengraph_parser'
require 'open-uri'
# Generate a new Mailchimp campaign from a page one your website. I used to use
# this with a purpose-built template in my static site generator that
# automatiacally set up my most recent post as an email, just the way I liked
# it. You'll probably need to make some changes to suit your needs but you're
# already off to a great start! Good luck!
# A URL on the web where your content already exists
ARTICLE_URL = 'https://example.com/email/'.freeze
MAILCHIMP_API_KEY = 'CHANGEME'.freeze
FROM_NAME = 'Your Name'.freeze
REPLY_TO = 'you@example.com'.freeze
# Oh yeah, this script also spits out text you can share on Twitter or whatever.
# For that it uses these two CSS selectors to fetch a permalink and a little
# description snippet from your webpage.
PERMALINK_SELECTOR = '.permalink'
SUMMARY_SELECTOR = '.preview-text'
MAILCHIMP_DATA_CENTER = MAILCHIMP_API_KEY.split('-').last.freeze
BASE_API_URL = "https://#{MAILCHIMP_DATA_CENTER}.api.mailchimp.com/3.0".freeze
# This script assumes you're using OpenGraph tags.
article = OpenGraph.new(ARTICLE_URL)
html = open(ARTICLE_URL).read.force_encoding('UTF-8').encode('UTF-8')
payload = {
type: 'regular',
recipients: { list_id: 'acad6b38c1' },
settings: {
subject_line: article.title,
title: article.title,
from_name: FROM_NAME,
reply_to: REPLY_TO,
to_name: '*|FNAME|*',
inline_css: true
}
}
response =
RestClient.post \
"#{BASE_API_URL}/campaigns",
payload.to_json,
'Authorization' => "apikey #{MAILCHIMP_API_KEY}"
body = JSON.parse(response, symbolize_names: true)
campaign_id = body[:id]
payload = { html: html }
response =
RestClient.put \
"#{BASE_API_URL}/campaigns/#{campaign_id}/content",
payload.to_json,
'Authorization' => "apikey #{MAILCHIMP_API_KEY}"
body = JSON.parse(response, symbolize_names: true)
puts body.to_yaml
puts '---'
document = Nokogiri::HTML(html)
permalink = document.css(PERMALINK_SELECTOR).first[:href]
puts "#{article.title} • #{document.css(SUMMARY_SELECTOR).inner_html.strip} #{permalink}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment