Problem sending mail with message and attachements after upgrading to Rails 3 - ruby-on-rails

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

Related

mailgun rails - How to define mailgun_settings per ActionMailer

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

send an attachment in mail using mailer rails4

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.

ActionMailer working fine in terminal, not sending to gmail

I'm just about in the finishing stages of my website, however I am having trouble with the ActionMailer. It prints out the message just fine, I'm just eager to know how to wire it so it can send to gmail account. I'm primary confused how to route it and configure it properly. I have a contact page that has a model that takes parameters like the recipient, subject, message and the time it was sent: Mailer model: Note all this code is on a local machine
class UserEmail < ActionMailer::Base
default from: 'XXX#gmail.com'
def contact(sender, subject, message, sent_at = Time.now)
#sender = sender
#message = message
#sent_at = sent_at.strftime("%B %e, %Y at %H:%M")
mail(:subject => subject)
end
end
Here's the about controller which the contact methods lie in:
class AboutController < ApplicationController
# ...\controllers\home_controller.rb
#----------------------------------------------------
# show contact form
def contact
#title = "Contact"
#sender = ''
#subject = ''
#message = ''
end
def sendmail
#sender = params[:sender]
#subject = params[:subject]
#message = params[:message]
if validate(#sender, #subject, #message)
UserEmail.contact(#sender, #subject, #message).deliver
flash[:success] = "Your message sent sucessfully!"
redirect_to about_index_path
else
flash.now[:error] = "Your message did not send"
redirect_to about_index_path
end
end
private
def validate(sender, subject, message)
#email_regex = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
if sender.blank? || subject.blank? || message.blank?
#error = "Message not sent: Required information not filled"
return false
elsif subject.length >= 50
#error = "Message not sent: Subject must be smaller than 50 characters"
return false
elsif sender[#email_regex].nil?
#error = "Message not sent: Email not valid"
return false
else
return true
end
end
end
Now this is where I am lost.
Here's what my route like to the mailer. Is this routed appropriately?:
match '/contact_email', :to => 'about#sendmail'
When I configure the mailer, does the code rest in the application.rb or the development.rb? Here's what I have in my application.rb:
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:user_name => 'XXX#gmail.com',
:password => 'XXX',
:authentication => 'plain',
:enable_starttls_auto => true,
}
Thanks in advance!
Change
def contact(sender, subject, message, sent_at = Time.now)
#sender = sender
#message = message
#sent_at = sent_at.strftime("%B %e, %Y at %H:%M")
mail(:subject => subject)
end
to
def contact(sender, subject, message, recipient, sent_at = Time.now)
#sender = sender
#message = message
#sent_at = sent_at.strftime("%B %e, %Y at %H:%M")
#recipient = recipient
mail(:subject => subject, :to => #recipient)
end
And don't forget to set recipient in your calling function.
Have you put the following lines in development.rb
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true

Prevent ActionMailer to strip repeating spaces in plain message

I'm trying to have an table in text mail, so I write some helpers:
module MailerHelper
def field_width(text, width)
' ' * (width - text.length) + text
end
def cell(text, width)
output = '| ' + field_width(text, width-2) + " |\n"
output << '+-' + '-'*(width-2) + '-+'
end
end
Then in view I write it like this:
<%= cell 'Test', 10 %>
But that what I get (according to letter_opener) is:
| Test |
+----------+
As can you see, the spaces that are repeating before Test. My question is how to prevent ActionMailer (or anything else what is destroying my beautiful table) from doing that.
Mailer code:
def remind(client, invoices)
#client = client
#company = #client.company
#invoices = invoices.to_a
days_left = #invoices.first.pay_date - Date.today
message = #client.group.messages.find_by_period days_left.to_i
raise 'No messages for this invoices.' if message.nil?
#template = message.template || if days_left < 0
t 'message.before'
elsif days_left > 0
t 'message.after'
else
t 'message.today'
end
#text = liquid_parse #template
#html = markdown_parse #text
mail(:to => #client.email, :subject => t('message.title'))
end
private
def markdown_parse(text)
markdown = Redcarpet::Markdown.new Redcarpet::Render::HTML,
:autolink => true, :space_after_headers => true
markdown.render text
end
def liquid_parse(text)
renderer = Liquid::Template.parse text
renderer.render 'company' => #company, 'invoice' => #invoice, 'client' => #client
end
I've found bug. It was caused by Premailer what I use to inline CSS in HTML part.
class InlineCSSInterceptor
def self.delivering_email(message)
#message.text_part.body = Premailer.new(message.text_part.body.to_s, with_html_string: true).to_plain_text # this is line causing the problem.
message.html_part.body = Premailer.new(message.html_part.body.to_s, with_html_string: true).to_inline_css
end
end
Mailer.register_interceptor InlineCSSInterceptor

The email body is missing when I send mails with attachements using ActionMailer

The content in the view is not being displayed. Only the attachment is being sent. Help would be appreciated!
def send
#subject = "Status of PIS App"
#recipients = "ssg#gmail.com"
#from = APP_CONFIG[:email]
#sent_on = Time.now
##content_type = "text/html"
content_type = "multipart/alternative"
attachment :filename => "Report.html",:content_type => "text/html",
:body => File.read("/home/shreyas/repos/mysorepoc/app/models/new1.html")
end
When using attachments, you need to specify the text part separately:
def send
#subject = "Status of PIS App"
#recipients = "ssg#gmail.com"
#from = APP_CONFIG[:email]
#sent_on = Time.now
##content_type = "text/html"
content_type = "multipart/mixed"
part :content_type => "text/plain", :body => "contents of body"
attachment :filename => "Report.html",:content_type => "text/html", :body => File.read("/home/shreyas/repos/mysorepoc/app/models/new1.html")
end
And you probably want to send the mail as a multipart/mixed, not as multipart/alternative (unless the attachment really is an alternative representation of the text part).

Resources