How to Upload Subscribers to Mailchimp Using CSV File (RubyShorts)

How to Upload Subscribers to Mailchimp Using CSV File (RubyShorts) - Webdesign Antwerpen

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.

Want to stay updated?

Follow my RSS feed and get notified about new articles

Subscribe via RSS

Comments

M ↓   Markdown Help?
M
Meta Bravo
0 points
7 years ago

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 &lt;main&gt;' 3: from teste.rb:6:ineachwithindex'
2: from teste.rb:6:in each' 1: from teste.rb:8:inblock 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.each
withindex 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 },
:EMAIL
TYPE => '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)

permalink
M
Meta Bravo
0 points
7 years ago

just figured out:

mail = row[:email]
first = row[:first_name]

shoud be:

mail = row[0]
first = row[1]

arrays....... integers..... omg.....

permalink
S
Simon Somlai
0 points
7 years ago

Awesome!

permalink