Knowledge Base/SMTP Integration/Sending via SMTP in different languages

Using Mandrill's SMTP integration with Web Frameworks

Kaitlin
posted this on July 19, 2012 12:22 AM

If you're using Ruby on Rails or NodeJS, you can configure sending through your Mandrill account via SMTP.

Port 25 is used in these examples, but you can connect to Mandrill on other ports if needed, so use whichever works for your particular configuration.

Ruby on Rails

Rails comes ready to send email out of the box, you just need to decide what environments will be sending email via Mandrill: “production” is a no-brainer, but “development” may only use Mandrill on occasion to make sure something works, and “test” should probably never use it (test suites shouldn’t rely on external services, etc.)

Which file you edit is determined by your environment choices:

  • production: config/environments/production.rb
  • test: config/environments/test.rb
  • development: config/environments/development.rb
  • all: config/application.rb (not recommended)

Code

# production.rb, test.rb, development.rb or application.rb

YourApp::Application.configure do
  config.action_mailer.smtp_settings = {
    :address   => "smtp.mandrillapp.com",
    :port      => 25, # ports 587 and 2525 are also supported with STARTTLS
    :enable_starttls_auto => true, # detects and uses STARTTLS
    :user_name => "MANDRILL_USERNAME",
    :password  => "MANDRILL_PASSWORD", # SMTP password is any valid API key
    :authentication => 'login', # Mandrill supports 'plain' or 'login'
    :domain => 'yourdomain.com', # your domain to identify your server when connecting
  }

  # …
end

# app/mailers/your_mailer.rb

class YourMailer < ActionMailer::Base
  def email_name
    mail :subject => "Mandrill rides the Rails!",
         :to      => "recipient@example.com",
         :from    => "you@yourdomain.com"
  end
end

# In a controller: YourMailer.email_name.deliver

NodeJS

For Node we’ll be using the node_mailer library, installed via npm. To install npm:

$ curl http://npmjs.org/install.sh | sh

To install node_mailer:

$ npm install mailer

Code

// mailer.js

var mailer   = require("mailer")
  , username = "MANDRILL_USERNAME"
  , password = "MANDRILL_PASSWORD";

mailer.send(
  { host:           "smtp.mandrillapp.com"
  , port:           25
  , to:             "customer@anydomain.com"
  , from:           "you@yourdomain.com"
  , subject:        "Mandrill knows Javascript!"
  , body:           "Hello from NodeJS!"
  , authentication: "login"
  , username:       username
  , password:       password
  }, function(err, result){
    if(err){
      console.log(err);
    }
  }
);

Now run like this:

$ node mailer.js
 
Topic is closed for comments