Rails mailer and sendgrid with heroku - ruby-on-rails

I am working on adding email functionality to an app I am hosting on heroku.
Here are the relavant files:
app/mailers/user_actions_mailer.rb
def add_user_action(action_params)
#action_params = action_params
from = Email.new(email: 'marklocklear#blah.org')
subject = 'You have been notified'
to = Email.new(email: 'my_user#gmail.com')
content = Content.new(type: 'text/html', value: "test")
mail = Mail.new(from, subject, to, content)
sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
response = sg.client.mail._('send').post(request_body: mail.to_json)
end
This is working fine and I am able to send emails with it. However, my issue is with the 'content' variable above. I want the content to use rails standard mailer template in app/views/user_actions_mailer/add_user_action.html.erb.
I have this file/folder created, but I'm not sure how to point content to this location. I'm tryed not passing content to Mail.new fuction hoping this might trigger rails default mailer wiring, that doesn't seem to work.

I was not able to come up with a solution for this, using the sendgrid-ruby gem which my example above uses.
I ended up refactoring using THIS PAGE from sendgrids ruby-on-rails specific documentation.

Related

How do I get the JSON response from Dialogflow with Rails?

I understand the whole process of dialogflow and I have a working deployed bot with 2 different intents. How do I actually get the response from the bot when a user answers questions? (I set the bot on fulfillment to go to my domain). Using rails 5 app and it's deployed with Heroku.
Thanks!
If you have already set the GOOGLE_APPLICATION_CREDENTIALS path to the jso file, now you can test using a ruby script.
Create a ruby file -> ex: chatbot.rb
Write the code bellow in the file.
project_id = "Your Google Cloud project ID"
session_id = "mysession"
texts = ["hello"]
language_code = "en-US"
require "google/cloud/dialogflow"
session_client = Google::Cloud::Dialogflow::Sessions.new
session = session_client.class.session_path project_id, session_id
puts "Session path: #{session}"
texts.each do |text|
query_input = { text: { text: text, language_code: language_code } }
response = session_client.detect_intent session, query_input
query_result = response.query_result
puts "Query text: #{query_result.query_text}"
puts "Intent detected: #{query_result.intent.display_name}"
puts "Intent confidence: #{query_result.intent_detection_confidence}"
puts "Fulfillment text: #{query_result.fulfillment_text}\n"
end
Insert your project_id. You can find this information on your agent on Dialogflow. Click on the gear on the right side of the Agent's name in the left menu.
Run the ruby file in the terminal or in whatever you using to run ruby files. Then you see the bot replying to the "hello" message you have sent.
Obs: Do not forget to install the google-cloud gem:
Not Entirely familiar with Dilogflow, but if you want to receive a response when an action occurs on another app this usually mean you need to receive web-hooks from them
A WebHook is an HTTP callback: an HTTP POST that occurs when something happens; a simple event-notification via HTTP POST. A web application implementing WebHooks will POST a message to a URL when certain things happen.
I would recommend checking their fulfillment documentation for an example. Hope this helps you out.

Rails 5.0.1 - ActionMailer with MailGun, setting 'noname' for filename when directly attaching base64 string

I have read the entire official guide here and about 5 questions on SO that describe this problem for Rails 3 and Rails 4.
This question is for Rails 5, but he is using an actual file, not an encoded string.
This is my mailer code (and yes I have both views setup). The email comes through perfectly fine, with the attached PDF.
def pdf_quote(proposal)
#proposal = proposal
email_with_name = %("#{#proposal.first_name} #{#proposal.last_name}" <#{#proposal.email}>)
filename = "QD-#{#proposal.qd_number}_#{#proposal.last_name}.pdf"
attachments[filename] = {
mime_type: 'application/pdf',
encoding: 'Base64',
content: #proposal.pdf_base64
}
mail(
to: email_with_name,
from: 'Floorbook UK <email address>',
subject: 'Your Personal Flooring Quote is attached',
sent_on: Time.now
)
end
In gmail the attachment is called 'noname' and in Postbox it is called 'pb_mime_attachment.pdf'
How can I get ActionMailer to use the filename I provide?
Note that I am using MailGun (mailgun-ruby gem 1.1.4) to send the email, so it could be the gem at fault here.
It turned out to be a bug with 3rd party mailgun-ruby gem.
I raised a bug with them, here are the details:
https://github.com/mailgun/mailgun-ruby/issues/82
It is fixed (I tested it) in version 1.1.5.

Rails: access git email config

We have a mail interceptor in our local environment, so that email aren't sent to the actual mail addresses, but a copy is sent to the developpers (devs#project.com).
It is cool, except that all the developpers receive the mails of the whole team, which can be annoying, disturbing.
I'd like to filter with each one using his own email address. I thought of using the git email address, which is set by all of us.
Can my Rails code have an access to this mail address?
Otherwise, I'll create a .gitignored file that each of us should set, but that's more setup then.
Found the solution here: Is it possible to call Git or other command line tools from inside a Thor script?
mail = %x(git config user.email)
So the whole interceptor would be:
class DevelopmentMailInterceptor
def self.delivering_email(message)
git_email = %x(git config user.email)
filter_email = !git_email.empty? git_email : 'devs#project.com'
if Rails.env.development? && !message.to.include?(filter_email)
message.subject = "[Local Filter] To: #{message.to} - #{message.subject}"
message.to = filter_email
end
return message
end
end

Rails not sending (ical) attachments in emails

I'm trying to send an email with an ical attachment, I'm running rails v.3.2.13 and using the icalendar gem (to generate the ical string) see. (In development mode in case that might be a problem).
The relevant mailer code looks like this:
def mailme
ical = Icalendar::Calendar.new
...
attachments["meetings.ics"] = { mime_type: "text/calendar", content: ical.to_ical }
mail(from: email, to: recipient, ...)
end
there is also template file with the same name (mailme.html.erb)
The problem is the mail (html) is send without the attachment.
As usual any help would be much appreciated.
Thank you.
I've gotten them working with something like below:
mail.attachments['meeting.ics'] = { mime_type: 'application/ics',
content: ical.to_ical }
mail(from: email, to: recipient, ...)
So it's possible you need to call it on #attachments on the mail object instead of calling it on the current context. I'm not sure if your mime type needs to be application/ics, but that's worked fine for me in my systems.
In case someone else stumbles upon this.
If you are using delayed_job check out https://github.com/collectiveidea/delayed_job/wiki/Common-problems#wiki-Sending_emails_with_attachments
To fix this, remember to add this line to your mailer:
content_type "multipart/mixed"

Using Google's Audit API to monitor google apps email

I need to get some admin users using google apps gmail the ability to monitor their employees email. Have you used Google's Audit API to do this.
I wish there there was a way for the admins to just click a view my users email but that doesn't be the case.
If it matters the application is a rails app. The email is completely done on googles mail through google apps. Anyone that has done this any advice would be helpful.
Update! 500 points for this one!
I'm using ruby on rails hosting an app on heroku. The email is completely hosted with google apps standard, not business so we will have to upgrade, and the DNS is with zerigo which you already know if you use heroku.
Well, I hadn't planned on extending the gdata-ruby-util gem :), but here's some code that could be used for the Google Audit API based on Google's documentation. I only wrote a create_monitor_on method, but the rest are pretty easy to get.
Let me know if it works or needs any rewrites and I'll update it here:
class Audit < GData::Client::Base
attr_accessor :store_at
def initialize(options = {})
options[:clientlogin_service] ||= 'apps'
options[:authsub_scope] ||= 'https://apps-apis.google.com/a/feeds/compliance/audit/'
super(options)
end
def create_monitor_on(email_address)
user_name, domain_name = email_address.split('#')
entry = <<-EOF
<atom:entry xmlns:atom='http://www.w3.org/2005/Atom' xmlns:apps='http://schemas.google.com/apps/2006'>
<apps:property name='destUserName' value='#{#store_at}'/>
<apps:property name='beginDate' value=''/>
<apps:property name='endDate' value='2019-06-30 23:20'/>
<apps:property name='incomingEmailMonitorLevel' value='FULL_MESSAGE'/>
<apps:property name='outgoingEmailMonitorLevel' value='FULL_MESSAGE'/>
<apps:property name='draftMonitorLevel' value='FULL_MESSAGE'/>
<apps:property name='chatMonitorLevel' value='FULL_MESSAGE'/>
</atom:entry>
EOF
return true if post('https://apps-apis.google.com/a/feeds/compliance/audit/mail/monitor/'+domain_name+'/'+user_name, entry).status_code == 201
false
end
end
Then use it elsewhere like this:
auditor = Audit.new
auditor.store_at = 'this-username'
auditor.clientlogin(username, password)
render :success if auditor.create_monitor_on('email-address#my-domain.com')
My suggestion is to create one core email address that all the email monitors are sent to, so your admins' inboxes aren't slammed with everyone else's mail. Then in your Rails app, use Net::IMAP to download the messages you want from that master email account. i.e., you can create a link that says "View Joe's Email" and the method does something like this:
require 'net/imap'
imap = Net::IMAP.new('imap.gmail.com', 993, true)
imap.login('this-username#my-domain.com', password)
imap.select('INBOX')
messages = []
imap.search(["TO", "joe#email.com").each do |msg_id|
msg = imap.fetch(msg_id, "(UID RFC822.SIZE ENVELOPE BODY[TEXT])")[0]
body = msg.attr["BODY[TEXT]"]
env = imap.fetch(msg_id, "ENVELOPE")[0].attr["ENVELOPE"]
messages << {:subject => env.subject, :from => env.from[0].name, :body => body }
end
imap.logout
imap.disconnect
Then you can put those messages in your view -- or send them all in one bulk email, or whatever you want to do.

Resources