How to Upload Subscribers to Mailchimp Using CSV File (RubyShorts)
How To Upload Subscribers To Mailchimp Using CSV File (Ruby)
Ever wanted to bulk upload users to your mailchimp account but were hindered because of the omnivore alert? Well with some magical ruby code and an API-key you won't have any problems :)
First up, enter this in the command line;
gem install mailchimp-api
require 'mailchimp'
require 'csv'
subscribers = []
contents = CSV.parse(File.read('path/to/file.csv', headers: true, header_converters: :symbol))
contents.each_with_index do |row, i|
# next if i == 0
mail = row[:email]
first = row[:first_name]
if first.nil?
subscriber = { 'EMAIL' => { 'email' => mail } }
p "added #{mail} without name"
else
p "added #{mail} with #{first}"
subscriber = { 'EMAIL' => { 'email' => mail },
:EMAIL_TYPE => 'html',
:merge_vars => { 'FNAME' => first.capitalize } }
end
subscribers << subscriber
end
mailchimp = Mailchimp::API.new('xxxxxxxxxxxx-YOUR-API-KEY-xxxxxxxxxxxxxx')
mailchimp.lists.batch_subscribe('YOUR-LIST-ID', subscribers, false, true, false)
And voila! All people imported! You might have to tweak a thing or two so the code matches the correct CSV collumns. This example was for a CSV file that contained a email and a first name.
Comments
on line 2, I think you missed a closing single quote for require 'csv'.
aside from that, I tried using this code and I get this:
ruby teste.rb
Traceback (most recent call last):
4: from teste.rb:6:in
<main>' 3: from teste.rb:6:in
eachwithindex'2: from teste.rb:6:in
each' 1: from teste.rb:8:in
block in <main>'teste.rb:8:in `[]': no implicit conversion of Symbol into Integer (TypeError)
what could I be doing wrong?
Heres is what I am using:
require 'mailchimp'
require 'csv'
subscribers = []
contents = CSV.parse(File.read('/tmp/teste3.csv', headers: true, headerconverters: :symbol, converters: :all))
contents.eachwithindex do |row, i|
# next if i == 0
nome = row[:nome]
mail = row[:email]
if nome.nil?
subscriber = { 'EMAIL' => { 'email' => mail } }
p "added #{mail} without name"
else
p "added #{mail} with #{nome}"
subscriber = { 'EMAIL' => { 'email' => mail },
:EMAILTYPE => 'html',
:merge_vars => { 'NOME' => nome.capitalize } }
end
subscribers << subscriber
end
mailchimp = Mailchimp::API.new('xxxxxxxxxx-xxxxxx')
mailchimp.lists.batch_subscribe('xxxxxxxxxxxx', subscribers, false, true, false)
just figured out:
mail = row[:email]
first = row[:first_name]
shoud be:
mail = row[0]
first = row[1]
arrays....... integers..... omg.....
Awesome!