Last active
December 22, 2015 03:49
-
-
Save kiub/6412964 to your computer and use it in GitHub Desktop.
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
# Sample code for sending MailChimp Email Campaigns from a Rails App using Gibbon API wrapper v0.3.5 | |
# All recipients must already be on the associated MailChimp list (list_id), for this app we add those via another | |
# API call every few minutes. | |
# | |
# Member function of EmailCampaign.rb model | |
# See http://labs.saidigital.co/using-mailchimp-api-to-send-email-campaigns-to-a-dynamic-set-of-email-addresses-425/ | |
# for explanation. | |
def send_campaign(api_key, gb, list_id, template_id, from_name, from_email) | |
self.reset_unique_id | |
segment_id = gb.list_static_segment_add(:id => list_id, :name => self.safe_name) | |
logger.info "Segment ID: #{segment_id}" | |
recipients = self.get_recipients | |
segmented_emails = recipients.collect{ |e| e.email }.uniq | |
logger.info "####### SENDING TO: #######" | |
logger.info segmented_emails | |
logger.info "###########################" | |
if segmented_emails.blank? | |
logger.debug "No email addresses found." | |
self.mailchimp_campaign_id = 'NO RECIPIENTS' | |
self.save(:validate => false) | |
else | |
emails_added = gb.list_static_segment_members_add( :id => list_id, :seg_id => segment_id, :batch => segmented_emails ) | |
logger.info "Email Added: #{emails_added}" | |
content_section = AppSetting.where(:name => 'MailChimp Main Content Section').first.value | |
conditions = [:field => :static_segment, :value => segment_id, p => 'eq'] | |
campaign_id = gb.campaign_create( | |
:type => 'regular', | |
ptions => { | |
:list_id => list_id, | |
:subject => self.subject, | |
:from_email => from_email, | |
:from_name => from_name, | |
:title => self.safe_name, | |
:template_id => template_id | |
}, | |
:content => { ('html_' + content_section).to_sym => self.get_body,:text => self.body }, | |
:segment_opts => { :match => 'all', :conditions => conditions } | |
) | |
puts "\n" | |
puts "Campaign ID: #{campaign_id}" | |
puts "\n" | |
sent = gb.campaign_send_now( :cid => campaign_id ) | |
self.mailchimp_campaign_id = campaign_id | |
self.prospect_forms << recipients | |
self.save(:validate => false) | |
end | |
rescue | |
logger.info "Crashed on scheduling email_campaign ID: #{self.id}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment