Action Mailer attachments.inline showing as normal attachment, not inline - ruby-on-rails

def simple_mail(to, subject, body)
attachments.inline['Logo.png'] = File.read( Rails.root.join("public", "Logo.png"))
mail(:to => to, :subject => subject, :body => body)
end
I receive an attachment to the message, but it is not an "inline" image. How can I attach inline, and how can I choose where it goes?
I'm seeing examples that have views for their mailer.. looks like I may need to set those up. If so, how do I link Action Mailer views to a message?

As you see in guides.rubyonrails, you can link a view to your mailer the same way you link a view to a controller's action. if your mailer is called my_mailer, and your mailer action is called simple_mail, then create a view in app/views/my_mailer/ and call it "simple_mail.html.erb". As well, you can create a "simple_mail.text.erb" to make sure that if the recipient can't receive HTML e-mails, they get the plaintext version (see action_mailer_basics.html below).
As for inline attachments, a different question was raised previously regarding views (see this link) and scaney answered with a couple links. Check out this link and search the text for "inline" and you should find the answer you're looking for!
http://guides.rubyonrails.org/action_mailer_basics.html
api.rubyonrails.org/classes/ActionMailer/Base.html

1) To Setup action-mailer views for the mails, you can do it as follows:
Create a view file in app/views/mailer_name/ with the same name as your mailer action (which in this case is "simple_mail" )
Alternatively if you want to use a different view altogether you can also do it as :
def simple_mail(to, subject, body)
attachments.inline['Logo.png']=File.read( Rails.root.join("public", "Logo.png"))
mail(:to => to, :subject => subject, :body => body) do |format|
format.html { render :partial => "/path/to/partial"}
end
end
In the above case, the content of the partial will be rendered as the body of the mail.
2) To attach a inline image you will also need to mention the attachment in the mailer action view file as follows:
<%= image_tag attachments['Logo.png'].url %>

Related

Rails grab template file as string variable in controller

I'm creating a custom ActionMailer which will also send Direct Messages on Twitter, and Text Message through Twilio. I need each to receive a parameter of the body of the message. I need to use the current template as a string variable.
For example:
# calling send_invite's mail method will load the send_invite template
def send_invite(to)
mail(to: to) # body parameter is automatically rendered from template
end
Now if I modify it to send through other services:
def send_invite(to, option)
if option == :email
mail(to: to) # body parameter is automatically rendered from template
elsif option == :twitter
twitter.create_direct_message(to, NEED_TEMPLATE_AS_STRING_HERE)
elsif option == :sms
twilio.sms(to, NEED_TEMPLATE_AS_STRING_HERE)
end
end
How might I grab the template for each of these service calls? Would there be something like:
message(to, render layout: false)
# or
message(to, IO.read template_path_helper("template") )
# or
message(to, template_helper.to_s)
How might I get the template as a string for my message body in these other methods? What's the Rails Way to do it? The templates are erb files and need to be able to render the appropriate variable as they would from a render.
I need to do it this way for translations of templates to be available.
I think you can create the template string from the controller, and send it to your mailer, like this:
#parsed_template = render_to_string(:partial => 'my_partial', :layout => false, :locals => {:my_object => my_value})
SomeMailer.send_invite(to, option, #parsed_template).deliver

How to modify actionmailer email html_part before sending

I have everything at the point where I'm about to send out the email but I need to modify all links to include Google Analytics attributes. The problem is that if I try and read/write the html_part.body of the email, the entire html string somehow becomes encoded and doesn't display the email properly (i.e. <html> becomes <html>). I have logged the html_part.body.raw_source in the logger and it shows as proper unencoded HTML, it's only when the email is actually sent does the encoding occur.
EBlast.rb (ActionMailer)
def main(m, args={})
# Parse content attachment references (they don't use helpers like the layout does)
# and modify HTML in other ways
m.prep_for_email self
#email = m # Needed for helper methods in view
mail_args = {
:to => #user.email,
:subject => m.subject,
:template_path => 'e_blast',
:template_name => 'no_template'
}
mail_args[:template_name] = 'main' if m.needs_template?
m.prep_for_sending mail(mail_args)
end
Email.rb
def prep_for_sending(mail_object)
if mail_object.html_part
# If I simply do a 'return mail_object', the email sends just fine...
# but the url trackers aren't applied.
# Replace the content with the entire generated html
self.content = mail_object.html_part.body.decoded
# Add Google analytics tracker info to links in content
apply_url_tracker :source => "Eblast Generator", :medium => :email
# Replace the html_part contents
mail_object.html_part.body = content
# At this point, mail_object.html_part.body contains the entire
# HTML string, unencoded. But when I send the email, it gets its
# entities converted and the email is screwed.
end
# Send off email
mail_object
end
Looks like I'm answering my own question again - I'm on a roll this week.
Apparently setting the body directly creates some odd attribute called 'body_raw' instead of replacing the raw_contents of the html_part. So basically I ended up having a duplicate part embedded in the mail object (I don't know why it does this). Creating a separate Mail::Part and assigning it to html_part just added another part instead of replacing html_part! WTF?!
New Edit: Scratch my last remark about String.replace. It looked like it was working but when I went to another computer and tested it, the same problem of duplication occurred.
Another Edit: Finally?
Before I executed the apply_url_tracker method I had reset the content of the email (for the purposes of changing all the links in the rendered view). I don't have any idea why that screws with the Mail object considering the message should already have been rendered but changing my methodology to the following has fixed the duplication of email parts and their subsequent 'reencoding'. I no longer change the content attribute, I only change the html_part:
def prep_for_sending(message)
if message.html_part
# Replace the html raw_source
message.html_part.body.raw_source.replace apply_url_tracker(message.html_part.body.decoded, :source => "Eblast Generator", :medium => :email)
end
message
end
Clarification:
Even though the call to mail() produces a Mail object with fully rendered HTML/Text parts (i.e., fully rendered views), changing the attribute that is USED by those views (in my case, the 'content' attribute) screws up the final send. Don't modify your model before sending, JUST MODIFY THE MAIL PART DIRECTLY.

emailing a page that already exists

I'm looking at this tutorial http://guides.rubyonrails.org/action_mailer_basics.html and I get why it would send the html page that is in the view. However how do I send a page that already exists before I created the mailer? I don't want to copy the html and the ruby code over because I don't want another copy of that code to have to maintain.
The page I want to email is an announcements page and there is already another view for the announcements page since it is accessible from other parts of the site.
You can pass :template_path and :template_name hash keys to the specific method in your mailer as in:
mail(:to => user.email,
:subject => "Subject",
:template_path => 'announcements',
:template_name => 'index')
In this case it will look for templates at app/views/announcements with name index.

Did I do this correctly - Call an action from controller with link_to

Please excuse the simplicity and length of this, but I have a little test app that has a users table, with name, email, and salary attributes. I created a mailer that will send out a report of this data to a specific user at my discretion, in other words, when I click a button. My button is created using link_to, and calls an action in my main users_controller, which then calls the mailer action. (I hope that just made sense). It looks like the following and is working just as I hoped; I'm just looking to know if this is the right way to do something like this:
In my users_controller (created by the scaffold generator):
def sendemail
#user = User.find(params[:id])
UserMailer.welcome_email(#user).deliver
redirect_to user_path(#user)
flash[:notice] = 'Email has been sent!'
end
In the user_mailer.rb file:
def welcome_email(user)
#user = user
#url = "http://example.com/login"
mail(:to => user.email,
:subject => "Welcome to My Awesome Site")
end
In the User's show.html.erb page, this is how the email gets sent:
<%= link_to "Send Email", sendemail_user_path(#user) %>
In my routes.rb file, so that everything executes properly (which it does):
resources :users do
member do
get 'sendemail'
end
So, having said all this, it works just like it should. I click on the user's show.html.erb page where I would have the data and charts that I want to eventually display, and at my discretion, I can kick out an email to that user with this data, or whatever I put in the mailer.html.erb file. When it is sent, it flashes the message I specified in the controller, and leaves me on that page, just as I specified; so it's working. I just want to know, is this the right and most ruby/railsy way to do things?
This code looks very similar to the Rails Guides Action Mailer example, so suffice it to say you are creating railsy code.
Also, if your application evolved into a much grander scale you would want to consider delivering emails via a background job to avoid email deliveries from blocking the current thread.
Otherwise the code looks great. Of course, you would most likely send an email after doing something successful in a controller, rather than have a dedicated action for emailing directly. For instance, you might have a welcome action that sends an email on a successful user record save.

How to access validation messages in partials?

So, each rails project i seem to run into this problem and would be really grateful if someone could enlighten me:
With a "normal" setup when the form sits on the view immediately associated with the url/controller it is pretty straightforward, a render => :action on fail will display the validation message.
Now what i have is a form in a partial sitting on a page whose url/controller is a show/:id and not the create action of the form, the validation kicks in but i cannot get the validation message to display because i can't trigger the correct render action...
CLosest i got is a render => #object but there is no css/layout, i can pass a message through a redirect with flash[] but it feels wrong, same with jquery/client error messages...
So how can i "cleanly" display validation messages of a form in a partial (under another controller/action than the parent page)?
(thanks in advance for your help)
edit: can't paste the actual thing now but i'll do my best to explain
i have a main page e.g. article/show/01, on this page is the content of the article (#article) and then at the bottom of the page is a partial _commentform with a form to post a comment. This form is bound to a Create action of a different controller (comments controller).
Now if the form were on its own "page"/url instead of a partial, say /comment/create, i would jus do:
if #comment.save
redirect_to #comment
else
render => :create
end
and the validation would display normally.
In my case the form is in a a partial on the article/show/01 url, what should be the equivalent to the code above so that on validation fail error messages are displayed on the parent url, like "render article/show/01" ?
I am sure it is easy but i cannot get it to work (i just can redirect on success but cannot display the errors with a render)
I don't think the best way to display validations errors is to render a partial.
IMHO, the best and clean way to display errors messages using the styles/css you or your webdesigner wants is by implementing your own error_messages method in a FormBuilder.
For example, here is the error_messages method I've implemented for my latest project.
Here is an example that will output the errors list in ul/li's with some custom styles...
Just customize this and put your form builder in app/helpers...
class StandardBuilder < ActionView::Helpers::FormBuilder
def error_messages
return unless object.respond_to?(:errors) && object.errors.any?
errors_list = ""
errors_list << #template.content_tag(:span, "There are errors!", :class => "title-error")
errors_list << object.errors.full_messages.map { |message| #template.content_tag(:li, message) }.join("\n")
#template.content_tag(:ul, errors_list.html_safe, :class => "error-recap round-border")
end
end
Then in my forms :
= form_for #post, :builder => StandardBuilder do |f|
= f.error_messages
...
No need to display/render another partial. And that's all :).
If you want to display anything (including error messages) in a partial you have two ways
1 - Define it in the controller action where the partial is called
2 - pass the message as a parameter to the partial
1 - Example
in your controller/action
if #comment.save
redirect_to #comment
else
#messages = "This is a message"
render => :create
end
in your partial
you can access the #message variable
2 - passing the variable to the partial
render :partial => “<partial name>”, :locals => { :param1 => “value”}
<partial name> – name of your partial (Ex /partials/footer)
:params1 – parameter name
“value” – value
hope this helps
thanks
sameera

Resources