Debugging Rails ActionMailer from Console

Sometimes you want to find the best ActionMailer configuration or debug connection issues.

One ncie way to do it is by instantiating directly `ActionMailer::Base`. You create an instance,
set its `delivery_method` to `:smtp`, then call `.mail(...)` on it to build a `Mail::Message`
object. That message object carries its own separate delivery method instance, and that is
where you inject your SMTP credentials before calling `.deliver!`.

Below is a working example using SendGrid over SMTP. Open a Rails console (`rails c`) and
run this step by step — or all at once:

```ruby
mailer = ActionMailer::Base.new
mailer.delivery_method = :smtp

m = mailer.mail(
  from: 'sourceacc@example.com',
  to:   'destacc@example.com',
  subject: 'test email_configurations',
  body: "Hello, email configurations!"
)

m.delivery_method.settings = m.delivery_method.settings.merge({
  address:        'smtp.sendgrid.net',
  port:            587,
  user_name:      'apikey',
  password:       'your_sendgrid_api_key',
  authentication: :plain,
  enable_starttls: true,
  ca_path:        "/etc/ssl/certs/",
  # openssl_verify_mode: 'none',
  openssl_verify_mode: OpenSSL::SSL::VERIFY_PEER
})

m.deliver!
```

A few things worth noting. First, `mailer.delivery_method = :smtp` must be set **before**
calling `.mail(...)` — otherwise the message object inherits the default delivery method
(usually `:test` in development) and your settings merge goes to the wrong place. Second,
`m.delivery_method.settings` is state on that `Mail::Message` instance, so using `.merge`
rather than direct assignment keeps any existing defaults intact.

For `openssl_verify_mode`, keeping it as `OpenSSL::SSL::VERIFY_PEER` is the correct
production choice — it validates the server certificate against the CA bundle at `/etc/ssl/certs/`.
The commented-out `'none'` option is only a quick escape hatch when debugging certificate issues
locally; never use it in production.

This approach is handy for smoke-testing a new SMTP configuration or a fresh SendGrid API key
without touching any application code.

Comments

Popular Posts