I have included given code
def send_help_enterprise
p '-----------------'
p params
Mailer.help_enterprise_issue(params[:app], params[:version], params[:name], params[:description][:text])
respond_to do |format|
format.js {
render :layout => false
}
end
end
and fetch parameters
{"utf8"=>"✓", "app"=>"test", "version"=>"1.1", "name"=>"faltuz", "description"=>{"text"=>"dcdfwedfed"}, "remotipart_submitted"=>"true", "authenticity_token"=>"rAykheNgAcEZF/M36i+hkpMzs+X1QZA+56hFoXAdQfXyDkGQU7K441nDylKKvj4cuxs/bfJgg7SEM0k9Kr+IGQ==", "X-Requested-With"=>"IFrame", "X-Http-Accept"=>"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript, */*; q=0.01", "file"=>#<ActionDispatch::Http::UploadedFile:0xb483c5d4 #tempfile=#<Tempfile:/tmp/RackMultipart20150916-3796-okttg1.jpeg>, #original_filename="images1.jpeg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"file\"; filename=\"images1.jpeg\"\r\nContent-Type: image/jpeg\r\n">, "controller"=>"enterprises", "action"=>"send_help_enterprise"}
and in my mailer I have included given code
def help_enterprise_issue(app,version,name,description)
#app = app
#version = version
#name = name
#description = description
#email = 'test#gmail.com'
mail :to => #email,
:subject => I18n.t('mailer.info.help_enterprise_issue')
end
Please guide how I can attach file in this mail I want to attach given file which I am fetching in params[:file]. Please help me out in solving this. Thanks in advance
use attachment attribute
attachments['file-name.pdf'] = File.read('file-name.pdf').
def welcome(user)
attachments['file-name.pdf'] = File.read('path/to/file-name.pdf')
mail(:to => user, :subject => "Welcome!")
end
refer this (2.3) :
http://guides.rubyonrails.org/action_mailer_basics.html
Modify your code to this:
def send_help_enterprise
p '-----------------'
p params
Mailer.help_enterprise_issue(params[:app], params[:version], params[:name], params[:description][:text], params[:file])
respond_to do |format|
format.js {
render :layout => false
}
end
end
in your mailer
def help_enterprise_issue(app,version,name,description,file)
#app = app
#version = version
#name = name
#description = description
#email = 'test#gmail.com'
attachments['attachment.extension'] = file
mail :to => #email,
:subject => I18n.t('mailer.info.help_enterprise_issue')
end
Thisshould work
Based on http://guides.rubyonrails.org/action_mailer_basics.html, you have to add attachments['file-name.jpg'] = File.read('file-name.jpg'). So, you can put in this method.
def help_enterprise_issue(app,version,name,description)
attachments['file-name.jpg'] = File.read('file-name.jpg')
#app = app
#version = version
#name = name
#description = description
#email = 'test#gmail.com'
mail :to => #email,
:subject => I18n.t('mailer.info.help_enterprise_issue')
end
I hope it can help you.
Related
I'm using Rails 4.2, sidekiq, rubyzip, axlsx and axlsx-rails
What I need to do:
I need to export file in a mail, but as a link and not as attachment.
I want an email send with a url to the download for it
Problem:
I don't know how to do it with this gem, in the git documentation there's nothing about it and every url I use don't work. I need to know how to create a download link for it and not as attachment to the mail
Code:
controller:
def export
export_args = {account_id: current_account.id}
ExportReportJob.perform_later(export_args)
redirect_to action: :index
end
job:
def perform(export_args)
begin
export_failed = false
account = Admin::Account.find_by(id: export_args[:account_id])
account.connect_to_target_db
#accounts = Admin::Account.active_accounts
file_name = "#{Time.now.strftime("%d_%m_%Y_at_%I_%M%p")}_export.xlsx"
dir_path = "#{Rails.root}/public/exports"
FileUtils.mkdir_p(dir_path) unless File.directory?(dir_path)
file_location = "#{absolute_path}/#{file_name}"
Admin::Mailer.export(account.pi, #accounts, file_location).deliver
rescue => e
export_failed = true
Airbrake.notify(e, environment_name: Rails.env, error_message: "export account failed #{e.message}")
ensure
ActiveRecord::Base.clear_active_connections!
end
end
template:
wb = xlsx_package.workbook
wb.add_worksheet(name: "Accounts") do |sheet|
sheet.add_row ["Account id", "Account name", "Organization"]
accounts.each do |account|
sheet.add_row [account.id, accoount.name, account.organization_id]
end
end
xlsx_package.to_stream.read
mailer:
def export(member, accounts, file_location)
#member = member
#title = "Export"
#header = subject = "Your Export is Ready"
#link = file_location
xlsx = render_to_string(layout: false, handlers: [:xlsx], template: "export.xlsx.axlsx", locals: {accounts: accounts})
# attachment = Base64.encode64(xlsx)
# attachments["export_#{DateTime.now.strftime("%d_%m_%Y_%HH%MM")}.xlsx"] = {mime_type: Mime::XLSX, content: attachment, encoding: 'base64'}
# ^ this is not what I want, I want to get the url for it and insert to #link
mail(:to => member.email, :subject => subject) do |format|
format.html
end
end
mail template:
= render partial: 'header'
= h_tag 'The export you requested has been completed'
= button 'Download the file', #link, { download: true }
= p_tag '(the file download will expire after <b>2</b> days)'
= render partial: 'footer'
I am using mailgun-ruby to send emails in my rails app.
I have activated a number of domains on my Mailgun account and for each ActionMailer I wish to choose a specific domain to send emails from.
The gem's documentation only explains a global way of setting mailgun_settings:
config.action_mailer.delivery_method = :mailgun
config.action_mailer.mailgun_settings = {
api_key: 'api-myapikey',
domain: 'mydomain.com'
}
Any suggestion how this can be done per ActionMailer?
I came up with a self crafted design for this:
class ApplicationMailer < ActionMailer::Base
before_action do
#layout = 'mailer'
#from = 'default#domain.com'
#to = 'default_to#domain.com'
#subject = 'Default Subject'
#domain = 'default.domain.com'
#params = {}
end
after_action do
ac = ActionController::Base.new()
mg = Mailgun::Client.new 'key-xxxxxxxxx'
message_params = {
from: #from,
to: #to,
subject: #subject,
text: ac.render_to_string("#{self.class.to_s.underscore}/#{action_name}.text", layout: #layout, locals: #params),
html: ac.render_to_string("#{self.class.to_s.underscore}/#{action_name}.html", layout: #layout, locals: #params)
}
mg.send_message #domain, message_params
end
end
class UserMailer < ApplicationMailer
before_action do
#from = 'Domain <updates#domain.com>'
#domain = 'updates.domain.com'
end
def test
#to = "yourself#gmail.com"
#subject = "Test"
#params = {}
end
end
Customize user_mailer/test.txt.erb and user_mailer/test.html.erb and send the email:
UserMailer.test
So, I have followed the standard answers for applying will paginate WITH AJAX on my rails website, but it doesn't seem to be working. If I click to go to the next set of partials, the page doesn't change. I see the request being made, but the contents of the page are the same.
//Here is my code below:
//Views
#container.baseGrip
= render :partial => 'student_search_pages/search_options'
#teachersList.full
%span.noreselt.full 該当する先生はいません
- #initial_users.each do |user|
.profcard_wrapper.six
= render :partial => "user_profile_cards/user_profile_card", :locals => {:user => user, :favorite_view => true}
= render :partial => 'users/edit/sche_candidate'
= js_will_paginate #initial_users, :previous_label => "< b", :next_label => "n >", :class => "pagination full", :outer_window => 2, :params => params[:page]
Here is my controller:
class StudentSearchPagesController < AuthenticatedController
before_action :check_user_is_student!
include StudentSearchPagesHelper
include WillPaginateHelper
def show
#user = current_user
#student = current_user.student
#initial_users = StudentSearchPagesHelper.initial_teacher_search(#student).paginate(:page => params[:page], :per_page => 1)
#favorites = current_user.user_favorites
#referer = request.referer
end
end
And finally, here is my helper:
module WillPaginateHelper
class WillPaginateJSLinkRenderer < WillPaginate::ActionView::LinkRenderer
def prepare(collection, options, template)
options[:params] ||= {}
options[:params]['_'] = nil
super(collection, options, template)
end
protected
def link(text, target, attributes = {})
if target.is_a? Fixnum
attributes[:rel] = rel_value(target)
target = url(target)
end
#template.link_to(target, attributes.merge(remote: true)) do
text.to_s.html_safe
end
end
end
def js_will_paginate(collection, options = {})
will_paginate(collection, options.merge(:renderer => WillPaginateHelper::WillPaginateJSLinkRenderer))
end
end
Also, here is the request that shows up when I click next:
Started GET "/student/search?page=2" for ::1 at 2018-04-04 10:09:13 -0400
Processing by StudentSearchPagesController#show as JS
Parameters: {"page"=>"2"}
...
Rendered users/edit/_time.haml (284.7ms)
Rendered user_profile_cards/_teacher_card.haml (456.3ms)
Rendered user_profile_cards/_user_profile_card.haml (542.3ms)
Subject Load (1.0ms) SELECT `subjects`.* FROM `subjects` ORDER BY `subjects`.`id` ASC LIMIT 1000
Rendered users/edit/_sche_candidate.haml (8.0ms)
Matching Load (0.7ms) SELECT `matchings`.* FROM `matchings` WHERE `matchings`.`student_id` = 2
Rendered student_search_pages/show.haml (1223.8ms)
This helper I use and works perfectly:
module WillPaginateHelper
class WillPaginateAjaxLinkRenderer < WillPaginate::ActionView::LinkRenderer
def prepare(collection, options, template)
options[:params] ||= {}
options[:params]["_"] = nil
super(collection, options, template)
end
protected
def link(text, target, attributes = {})
if target.is_a? Fixnum
attributes[:rel] = rel_value(target)
target = url(target)
end
target = target.sub('/data', "") if Rails.env == "production"
ajax_call = "$.ajax({url: '#{target}', dataType: 'script'});return false;"
#template.link_to(text.to_s.html_safe,"#", onclick: ajax_call)
end
end
def ajax_will_paginate(collection, options = {})
will_paginate(collection, options.merge(:renderer => WillPaginateHelper::WillPaginateAjaxLinkRenderer))
end
end
I have a Payment mailer class that creates email:
class PaymentMailer < ActionMailer::Base
include LocaleWrapper
helper :application
def payment_notification(payment)
host = payment.try(:host)
#payment = payment
#user = payment.user
using_locale((#user && #user.locale) || I18n.locale) {
attachments["#{set_default_domain_name_from(host)}_receipt_#{Time.now.strftime("%Y_%m_%d")}.pdf"] = WickedPdf.new.pdf_from_string(
render_to_string(pdf: "#{set_default_domain_name_from(host)}_receipt_#{Time.now.strftime("%Y_%m_%d")}.pdf", template: filtre_mail_template_by_host(host), layout: "pdf.html"))
headers['Precedence'] = 'bulk'
mail(:to => #user.email, :subject => I18n.t("mailer_subjects.payment_completed"), :from => "no-reply##{set_default_domain_name_from(host)}") do |format|
format.text(:content_transfer_encoding => "base64")
format.html
end
}
end
I have observer method that saves email in the database:
def delivered_email(email)
Rails.logger.info email.inspect
html_body = (email.multipart? ? email.html_part : email).body.to_s
text_body = (email.multipart? ? email.text_part : email).body.to_s
outgoing_mail = OutgoingMail.new({
:to => email.to.join(', '),
:from => email.from.join(', '),
:subject => email.subject.to_s,
:sent_at => email.date,
:html_body => html_body,
:text_body => text_body,
:multipart => email.multipart?,
})
outgoing_mail.save
save_attachments(email, outgoing_mail)
end
Problem is with multipart email's plain text version, which returns ASCII 8bit string and mysql throws Mysql2::Error: Incorrect string value error.
(rdb:1) text_body
"N\x16\xA7\x93*.~\x8A\xF2\xA2\xEA\xDC\xA2{k\x89\xBB\xAD\x8A\x89\xD2y\xEA]}\xABmi\xC8fz{_\xA2\xBAZ\xCAg\xA7\xB5\xD7\xADj)l"
(rdb:1) text_body.encoding
#<Encoding:ASCII-8BIT>
I have tried using #force_encoding method, but there is no success:
(rdb:1) text_body.force_encoding("UTF-8")
"N\u0016\xA7\x93*.~\x8A\xF2\xA2\xEAܢ{k\x89\xBB\xAD\x8A\x89\xD2y\xEA]}\xABmi\xC8fz{_\xA2\xBAZ\xCAg\xA7\xB5\u05EDj)l"
Why am i getting ASCII 8bit string instead of UTF-8?
I used to have this code for sending mails:
class MailTimerMailer < ActionMailer::Base
def mail_schedule(from, to, cc, bcc, subject, message, files=[], sent_at = Time.now)
#subject = subject
#recipients = to
#from = from
#cc = cc
#bcc = bcc
#sent_on = sent_at
#body["message"] = message
#headers = {}
# attache files
files.each do |file|
attachment file.mimetype do |a|
a.body = file.binarydata
a.filename = file.filename
end
end
end
end
It no longer works. I do not have a view for my mails, as the complete message comes from outside my method. I have tried to modify my code to Rails 3 like this:
class ScheduleMailer < ActionMailer::Base
def mail_schedule(from, to, cc, bcc, subject, message, files=[], sent_at = Time.now)
#subject = subject
#recipients = to
#from = from
#cc = cc
#bcc = bcc
#sent_on = sent_at
#body["message"] = message
#headers = {}
# attache files
files.each do |file|
attachments[file.filename] = File.read("public/data/" << file.id.to_s() << "." << file.extension)
end
end
end
This code sends a mail with the attachements, but there are no actual message in the mail. It also gives me a deprecation warning "Giving a hash to body is deprecated, please use instance variables instead". I have tried with "body :message => message" but no luck.
How can I get this working again?
Thank you
This is how:
class MyMailer < ActionMailer::Base
def mail_schedule(from, to, cc, bcc, subject, message, files=[], sent_at = Time.now)
# attache files
files.each do |file|
attachments[file.filename] = File.read("public/data/" << file.id.to_s() << "." << file.extension)
end
mail(:from => from, :to => to, :cc => cc, :bcc => bcc, :subject => subject) do |format|
format.text { render :text => message }
end
end
end