Tagging messages with ActionMailer and mailgun - mailgun

I'm using mailgun with ActionMailer like this:
config.action_mailer.delivery_method = :mailgun
config.action_mailer.mailgun_settings = {
api_key: 'key-b46eXXXXXXXXXXXX91c4',
domain: 'mg.eagle.com'
}
Mails go out like this:
mail(to: #contact, subject: 'Ask a Question', reply_to: #email, from: #email)
How can I add tags to my mails? There is an example in the mailgun documentation (https://documentation.mailgun.com/en/latest/user_manual.html#tagging) but that doesn't use ActionMailer but a POST on the API...

I found the solution to this, it's actually pretty simple:
Put the following line before the mail command:
headers['X-Mailgun-Tag'] = 'contact_us'
However this will only work if the Pull request is merged:
https://github.com/mailgun/mailgun-ruby/pull/133
Until then you can use this in the Gemfile:
gem 'mailgun-ruby', :github => 'mailgun/mailgun-ruby', :branch => 'sjohn/railgun-mailer-headers'

Related

Does AWS SES work with grails Mail plugin 1.0.7?

I would like to use the AWS SES mail service using SMTP. I know it works for some versions, but I haven't gotten it to work for my application yet. I get a 530 Authentication error.
My question is in three parts:
1. Does AWS smtp work using Grails 2.3.1 with the Mail 1.0.7 plugin using java 1.7?
If it does work, how does one configure it?
If it does work, how can I get more debug information to figure what is wrong?
I've tried every configuration example variant I've come across for this. My latest is below. (It's clear I don't really understand the Mail plugin and the Java mail class, I'm just trying to suss out a working configuration incantation.)
Here is what I have in my config.groovy file:
grails {
mail {
host = 'email-smtp.us-east-1.amazonaws.com'
port = '587'
username = SMTP AWS username, not IAMS username
password= SMTP AWS password, not IAMS password
props = [ 'mail.debug': true,
'mail.smtp.host' : 'email-smtp.us-east-1.amazonaws.com',
'mail.smtp.auth': 'true',
'mail.smtp.starttls.enable': 'true',
'mail.smtp.port': '587',
'mail.smtp.starttls.required': 'true',
'mail.smtp.user' : smtp username from above,
'mail.smtp.usernme' : smtp username from above,
'mail.smtp.password': smtp password from above,
'mail.smtp.socketFactory.port': '587',
'mail.smtp.socketFactory.class':
'javax.net.ssl.SSLSocketFactory',
'mail.smtp.EnableSSL.enable':'true',
'mail.smtp.socketFactory.fallback': 'false' ]
}
}
I have successfully made direct AWS SES emails using the aws-sdk:1.9.40 plugin, by the way.
I am using the mailService.sendmail code from the Mail plugin. This is unchanged (beyond the hardcoded html text), and works fine when the configuration went to our email server.
def resp = mailService.sendMail {
from replyToEmail
replyTo replyToEmail
to user.email
subject emailSubject
html "This is the mesage text Mar 20"
}
Any help at all would be most appreciated!!

how to include mail gun API in rails?

I want to use Mailgun in my Rails application.
When I include through Heroku addon it display error to add credit card number though I wanted the free version.
I looked up and found this code from Mailgun. Could someone tell me how to use it?
require 'mail'
Mail.defaults do
delivery_method :smtp, {
:port => 587,
:address => "smtp.mailgun.org",
:user_name => "",
:password => "",
}
end
mail = Mail.deliver do
to 'bar#example.com'
from 'foo#YOUR_DOMAIN_NAME'
subject 'Hello'
text_part do
body 'Testing some Mailgun awesomness'
end
end
I tried using this but it displays an error - mailgun SSL_read: sslv3 alert bad record mac
You need to sign up with Mailgun and get your SMTP username and password which you would use in the mail configuration.

ActionMailer not delivering confirmation emails in test environment - Rails 4

I'm using Rails (4.2.6), Ruby (2.2.4), Devise (4.1.1), Capybara (2.7.1), Capybara-email (2.5.0), Email_spec (2.1.0), Rspec (3.4.0), and Postgres (0.18.4)
After I upgraded the application from Rails 4.1.15 to 4.2.6, several authentification & registration tests fail. Before the upgrade all tests were properly passing. The code works as expected in the development environment (for example, confirmation emails are sent & viewable in the Rails server terminal). The problem of non-delivered emails only occurs in the test environment.
Here's the failing rspec ./spec/features/users/authentification_spec.rb:56:
#Sign up User
visit "/"
click_link "Sign up"
find(:css, "#user_email").set("tester9#example.com")
find(:css, "#user_password").set("password900")
find(:css, "#user_password_confirmation").set("password900")
expect {
click_button "Sign up"
}.to change{ ActionMailer::Base.deliveries.size}.by(1)
When a user completes the form and clicks the "Sign up" button, the page redirects to the "About" page and as expected, the following flash message appears: "A message with a confirmation link has been sent to your email address. Please follow the link to activate your account."
Using save_and_open_page, I confirmed the aforementioned behavior. However, the spec fails with the following error:
Failure/Error:
expect {
click_button "Sign up"
}.to change{ ActionMailer::Base.deliveries.size}.by(1)
expected result to have changed by 1, but was changed by 0
# ./spec/features/users/authentification_spec.rb:56:in `block (2 levels) in <top (required)>'
The error indicates that there are no message objects in the ActionMailer::Base.deliveries array. The results of Pry confirm that the ActionMailer::Base.deliveries array is indeed empty:
[1] pry(main)> mail = ActionMailer::Base.deliveries
=> []
Here's the test log when the spec is run:
Started POST "/users" for 127.0.0.1 at 2016-06-09 16:16:25 -0700
Processing by RegistrationsController#create as HTML
Parameters: {"utf8"=>"✓", "user"=>{"email"=>"tester9#example.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
[1m[35m (0.8ms)[0m SAVEPOINT active_record_1
[1m[36mUser Exists (3.3ms)[0m [1mSELECT 1 AS one FROM "users" WHERE "users"."email" = 'tester9#example.com' LIMIT 1[0m
[1m[35mUser Exists (1.9ms)[0m SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('tester9#example.com') LIMIT 1
[1m[36mSQL (2.1ms)[0m [1mINSERT INTO "users" ("email", "encrypted_password", "signup_as", "created_at", "updated_at", "confirmation_token", "confirmation_sent_at") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"[0m [["email", "tester9#example.com"], ["encrypted_password", "$2a $04$Vruf8j0A.DdOZLPe0qjVp.4PxzdR7sCdLF4FfyAr4dQSxcQAjpAwy"], ["created_at", "2016-06-09 23:16:25.095386"], ["updated_at", "2016-06-09 23:16:25.095386"], ["confirmation_token", "EmY8JyaVAxAfiq7oQ98z"], ["confirmation_sent_at", "2016-06-09 23:16:25.097581"]]
[1m[35m (0.4ms)[0m RELEASE SAVEPOINT active_record_1
Redirected to http://www.example.com/about
Completed 302 Found in 113ms (ActiveRecord: 9.6ms)
The log indicates that a confirmation email was sent, but the deliveries array is empty. Why is that happening? Is the record not being committed or persisted in the test database for some reason? I've read related posts about non-delivery of mail, but have not found a solution to my problem.
Relevant code from test.rb:
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
config.action_mailer.perform_deliveries = true
Relevant contents from rails_helper.rb:
require 'rspec/rails'
require 'devise'
require 'capybara/rails'
require 'database_cleaner'
require 'capybara/poltergeist'
require 'capybara/email/rspec'
require 'email_spec'
# Includes Devise test helpers (e.g., lets you use Devise's "sign_in" method in tests)
config.include Devise::TestHelpers, :type => :controller
config.include Warden::Test::Helpers
Relevant commented-out code from devise.rb:
# Configure the class responsible to send e-mails.
#config.mailer = 'Devise::Mailer'
Mail delivery works as expected in development & production. What is going wrong in the test environment? How can I fix it? Thanks!
Looking at devise - https://github.com/plataformatec/devise/blob/4-1-stable/lib/devise/models/confirmable.rb#L48 - it sends the confirmation email in an after_commit callback - If you're running with transactional testing enabled the after_commit callback will never be called (because the DB transaction is rolled back and never committed) so the email is never sent. Disable transaction based testing for that test and it will probably work.
Just to summarize the discussion between Tom Walpole and codeinspired above into a top-level answer for browsers who might not look into comments, their solution (assuming you use DatabaseCleaner) is to make the following modifications:
rails_helper.rb
# lots of boilerplate and
# other things at the top of this file, but you'll
# eventually see....
RSpec.configure do |config|
# ... other config stuff ...
# sometime after this key line, you want to add:
config.before(:each, truncation: true) do
DatabaseCleaner.strategy = :truncation
end
# ... other config stuff ...
end
For the test that is in question here, you want to modify it to look like the following (note the addition of "truncation: true" in the line starting with the word "it")
something_spec.rb
# ... other stuff ...
describe "some function" do
it "performs a function correctly", truncation: true do
# your test
# goes here
end
end

Salesforce.com Streaming API Error Summer 14 Release

I have problem in Salesforce.com Streaming API using CookieJar.
"CookieJar::InvalidCookieError: Domain is inappropriate based on request URI hostname"
It seem that Salesforce is setting the cookie domain as ".salesforce.com" which will not match the corresponding request domain according to RFC 2109.
Can any one help me?
Just add below to gemfile.
gem 'restforce', '~> 2.2', '>= 2.2.1'
gem 'faye', '0.8.9'
gem "cookiejar", :git => "https://github.com/MissionCapital/cookiejar.git"
Now create an initializer rest_for as below.
require 'faye'
Restforce.configure do |config|
config.username = ENV['SALESFORCE_USERNAME']
config.password = ENV['SALESFORCE_PASSWORD']
config.client_id = ENV['SALESFORCE_CLIENT_ID']
config.client_secret = ENV['SALESFORCE_CLIENT_SECRET']
config.host = ENV['SALESFORCE_HOST'] if ENV['SALESFORCE_HOST'].present?
config.instance_url = ENV['SALESFORCE_INSTANCE_URL'] if ENV['SALESFORCE_INSTANCE_URL'].present?
end
client = Restforce.new
credentials = client.authenticate!
Thread.abort_on_exception = true
Thread.new {
EM.run {
# Subscribe to the PushTopic.
client.subscribe 'YOUR_CHANNEL_NAME' do |message|
p message.inspect
end
}
}
Just remember to use proper host for development and production. In development use test.salesforce.com.
Hope this help someone who facing the same issue.

Implementing resource_owner_authenticator doesnt work

I'm writing an API aside with an web page. I want to have Oauth2 login so i can keep a session from the mobile device, i've already install the GEM doorkeeper and run the migration how it's explained on this site.
where i'm getting stuck is in the resource_owner_from_credentials parts, since i have an User model which has authenticate method given by the has_secure_password helper from rails. this is how my /config/initializers/doorkeeper.rb file looks like
Doorkeeper.configure do
# Change the ORM that doorkeeper will use.
# Currently supported options are :active_record, :mongoid2, :mongoid3, :mongo_mapper
orm :active_record
# This block will be called to check whether the resource owner is authenticated or not.
resource_owner_from_credentials do
User.find_by_email(params[:email]).authenticate(params[:password])
end
##lots of comments
end
and when go to
localhost:3000/oauth/authorize
i get this:
config/initializers/doorkeeper.rb:8:in `block (2 levels) in <top (required)>'
then i tried:
http://127.0.0.1:3000/oauth/authorize?email=puca#gmail.com&password=porche
and the same
what i'm i doing wrong? how should i configuresource_owner_authenticator block? how do i get the token?
As per this doorkeeper wiki page you need to send a POST request to /oauth/token API with the following params:
{
"grant_type" : "password",
"username" : "user#example.com",
"password" : "sekret"
}
When this request is processed, doorkeeper calls the resource_owner_from_credentials block and passes the params to it. So you have access to the param named username and not email.
To summarize, fix the API endpoint to /oauth/token , change params[:email] to params[:username] and everything should work.