A custom ActionMailer delivery method that sends emails via Microsoft Graph API using OAuth 2.0 client credentials flow.
- 🚀 Send emails through Microsoft Graph API (v1.0)
- 🔐 OAuth 2.0 authentication with client credentials flow
- 📎 Support for attachments
- 📧 Support for HTML and plain text emails
- 📬 Support for CC, BCC, and Reply-To recipients
- 🔍 Comprehensive error handling and logging
- ⚙️ Configurable SSL verification
Add this line to your application's Gemfile:
gem 'ms-graph-mailer', git: 'https://github.com/zauberware/ms-graph-mailer'Then execute:
bundle install- Register an application in Azure Active Directory
- Grant the application
Mail.SendAPI permission (Application permission, not delegated) - Generate a client secret
- Note down:
- Tenant ID
- Client ID (Application ID)
- Client Secret
Create an initializer file config/initializers/ms_graph_mailer.rb:
MsGraphMailer.configure do |config|
config.tenant_id = ENV['AZURE_MAIL_APP_TENANT_ID']
config.client_id = ENV['AZURE_MAIL_APP_CLIENT_ID']
config.client_secret = ENV['AZURE_MAIL_APP_CLIENT_SECRET']
config.logger = Rails.logger
endConfigure ActionMailer to use the Microsoft Graph delivery method:
# config/environments/production.rb
config.action_mailer.delivery_method = :microsoft_graph
config.action_mailer.microsoft_graph_settings = {
ssl_verify: true # Set to false to disable SSL verification (not recommended for production)
}Set the following environment variables:
AZURE_MAIL_APP_TENANT_ID=your-tenant-id
AZURE_MAIL_APP_CLIENT_ID=your-client-id
AZURE_MAIL_APP_CLIENT_SECRET=your-client-secretOnce configured, the gem works automatically with ActionMailer. Just send emails as you normally would:
require 'ms/graph/mailer'
class UserMailer < ApplicationMailer
def welcome_email(user)
mail(
to: user.email,
subject: 'Welcome to Our App',
from: '[email protected]'
)
end
end
# Send the email
UserMailer.welcome_email(user).deliver_now- The
fromemail address must be a valid mailbox in your Microsoft 365 tenant - The Azure AD application must have the necessary permissions to send emails on behalf of the sender
- Emails are sent using the
/users/{sender}/sendMailendpoint
The gem raises specific exceptions for different error scenarios:
MsGraphMailer::ConfigurationError- Invalid or missing configurationMsGraphMailer::AuthenticationError- OAuth authentication failuresMsGraphMailer::DeliveryError- Email delivery failures
After checking out the repo, run:
bundle installRun tests:
bundle exec rspecRun RuboCop:
bundle exec rubocopBug reports and pull requests are welcome on GitHub at https://github.com/zauberware/ms-graph-mailer.
The gem is available as open source under the terms of the MIT License.
Developed by Zauberware Technologies GmbH