Created
March 8, 2013 21:59
-
-
Save larsar/5120239 to your computer and use it in GitHub Desktop.
Adds email,name from a csv file to a new Sendgrid recipient list. Only emails that are not already on an existing recipient list are added to the new one.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'CSV' | |
require 'rest_client' | |
require 'json' | |
USERNAME="" | |
PASSWORD="" | |
URL_POSTFIX = "&api_user=#{USERNAME}&api_key=#{PASSWORD}" | |
SOURCE_LIST="" | |
NEW_LIST="" | |
CSV_FILE="" | |
def fetch_existing_list | |
get_list_url = "https://sendgrid.com/api/newsletter/lists/email/get.json?list=#{SOURCE_LIST}" | |
response = RestClient.get(get_list_url+URL_POSTFIX) | |
JSON.parse(response) | |
end | |
def parse_csv | |
result = [] | |
CSV.foreach(CSV_FILE, encoding: "ISO-8859-1") do |row| | |
result << {'email' => row[0], 'name' => row[1]} | |
end | |
result | |
end | |
def mail_addresses_from_subscribers(subscribers) | |
emails = [] | |
subscribers.each do |sub| | |
emails << sub['email'] | |
end | |
emails | |
end | |
def add_to_mailinglist(subscriber) | |
add_subscriber_url = "https://sendgrid.com/api/newsletter/lists/email/add.json?list=#{NEW_LIST}&" | |
data = "data="+subscriber.to_json | |
url = add_subscriber_url+"&"+URI.encode(data)+URL_POSTFIX | |
response = RestClient.get(url) | |
puts "Adding subscriber: #{subscriber[:email]}: #{response.to_s}" | |
puts "Result of adding sendgrid subscribers: #{response.to_s}" | |
end | |
def add_if_missing(emails, subscribers) | |
subscribers.each do |sub| | |
unless emails.include?(sub['email']) | |
add_to_mailinglist(sub) | |
end | |
end | |
end | |
existing_subscribers = fetch_existing_list | |
imported_subscribers = parse_csv | |
existing_emails = mail_addresses_from_subscribers(existing_subscribers) | |
add_if_missing(existing_emails, imported_subscribers) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment