We built an app that needed to send email campaigns to groups of users that signed up at trade shows and recruiting events. We chose to use MailChimp to do the actual emailing and email click/statistics tracking.
In order to send emails to a dynamic set of users, we found that we needed to add each user to the same, predefined MailChimp list, and then segment that list at send time to send the campaign to a filtered set of email addresses.
Here is some sample Ruby code on how we were able to accomplish this:
Using MailChimp API to send email campaigns to a dynamic set of email addresses
A rake task grabs all EmailCampaigns needing to be sent and calls this member function on each.
- Segment the full predefined MailChimp list to get a segment_id.
- Grab the recipient email addresses from the database. Note, you cannot send to email addresses that are not already on the predefined MailChimp list. We chose to run a separate rake task to continually add new email addresses to that list via the API.
- Add the recipient email addresses from the app database to the segmented list on MailChimp.
- Create a new campaign on MailChimp with the segmented email campaign_id. For our project we used a predefined email template branded by the client so we also needed the content_section id so that we could inject the email body into the correct location in the template (must be prefaced with ‘html_’, see campaign_create).
- Tell MailChimp to send the campaign and save the campaign id for retrieving statistical information later.
Note, this is probably something MailChimp wants you to use their new service Mandrill for.