Rails: Amazon aws-ses, missing required header 'From' - ruby-on-rails

Email from Ruby code is sending without any issue. But when I try to send it from Rails console, it gives the Missing required header 'From' error even From is specified in the email (Notifier), see below:
def send_email(user)
recipients "#{user.email}"
from %("Name" "<name#domain.com>")
subject "Subject Line"
content_type "text/html"
end
Here is email sending code from rails console:
ActionMailer::Base.delivery_method = :amazon_ses
ActionMailer::Base.custom_amazon_ses_mailer = AWS::SES::Base.new(:secret_access_key => 'abc', :access_key_id => '123')
Notifier.deliver_send_email
Am I missing something?
GEMS used: rails (2.3.5), aws-ses (0.4.4), mail (2.3.0)

Here is how it was fixed:
def send_email(user)
recipients "#{user.email}"
from "'First Last' <name#domain.com>" # changing the FROM format fixed it.
subject "Subject Line"
content_type "text/html"
end

Related

Where to put ruby helpers Sendgrid V3 Send API

I am trying to integrate Sendgrid using their Github documentation.
In their examples they suggest that you create a Mail Helper class but give very little guidance on how to actually do this.
I have a scheduled Rake task running using Heroku Scheduler that I would like to send an email when the task is complete and was hoping to use Sendgrid for this.
Currently I have the following code in /lib/tasks/scheduler.rake
require 'sendgrid-ruby'
include SendGrid
desc "Testing Email Rake"
task :test_sendgrid => :environment do
puts 'Starting Sendgrid Email Test'
send_task_complete_email()
puts 'Sendgrid Email Test Complete'
end
def send_task_complete_email
from = Email.new(email: 'test#example.com')
to = Email.new(email: 'test#example.com')
subject = 'Sending with SendGrid is Fun'
content = Content.new(type: 'text/plain', value: 'and easy to do anywhere, even with Ruby')
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)
puts response.status_code
puts response.body
puts response.headers
end
I don't have the helper classes added anywhere as I am not sure which bits to add or where to put them. At the moment when I run this task I receive a 400 Bad request error back from Sendgrid and I believe it's because I don't have these helpers in place.
Any advice to fix this would be much appreciated as when I try to integrate without using the helpers and instead writing out the JSON I can successfully send the email but receive a TypeError: Mail is not a module when I try to deploy to Heroku.
UPDATE: ERROR RECEIVED USING ANSWER BELOW
400
{"errors":[{"message":"Invalid type. Expected: object, given: string.","field":"(root)","help":"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#-Request-Body-Parameters"}]}
{"server"=>["nginx"], "date"=>["Thu, 07 Jun 2018 09:02:42 GMT"], "content-type"=>["application/json"], "content-length"=>["191"], "connection"=>["close"], "access-control-allow-origin"=>["https://sendgrid.api-docs.io"], "access-control-allow-methods"=>["POST"], "access-control-allow-headers"=>["Authorization, Content-Type, On-behalf-of, x-sg-elas-acl"], "access-control-max-age"=>["600"], "x-no-cors-reason"=>["https://sendgrid.com/docs/Classroom/Basics/API/cors.html"]}
You need to use Action Mailer:
First create a mailer class to add your mail details (i.e. UserMailer):
$ bin/rails generate mailer UserMailer
it will create the following files:
create app/mailers/user_mailer.rb
create app/mailers/application_mailer.rb
invoke erb
create app/views/user_mailer
create app/views/layouts/mailer.text.erb
create app/views/layouts/mailer.html.erb
invoke test_unit
create test/mailers/user_mailer_test.rb
create test/mailers/previews/user_mailer_preview.rb
Now edit the file app/mailers/user_mailer.rb:
require 'sendgrid-ruby'
include SendGrid
class UserMailer < ApplicationMailer
def send_task_complete_email
from = Email.new(email: 'test#example.com')
to = Email.new(email: 'test#example.com')
subject = 'Sending with SendGrid is Fun'
content = Content.new(type: 'text/plain', value: 'and easy to do anywhere, even with Ruby')
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)
puts response.status_code
puts response.body
puts response.headers
end
end
Then you can simply send emails using this code:
UserMailer.send_task_complete_email.deliver_now
Or from rake task:
desc "Testing Email Rake"
task :test_sendgrid => :environment do
puts 'Starting Sendgrid Email Test'
UserMailer.send_task_complete_email.deliver_now
puts 'Sendgrid Email Test Complete'
end
Update:
Because there is Mail module in Rails, you need to specify the correct SendGrid Mail module by changing:
mail = Mail.new(from, subject, to, content)
to
mail = SendGrid::Mail.new(from, subject, to, content)

NoMethodError Ruby 1.9.3

I am using Ruby 1.9.3 and getting the following error on the following line while trying to use the SendGrid API.
ERROR [on this line below "mailer.mail(mail_defaults)"]:
NoMethodError (undefined method `to_h' for #<Hash:0x00000005da0958>):
CODE:
assuming some users
recipients = []
recipient = SendGrid::Recipient.new('jn#geo.com')
recipient.add_substitution('name', 'Billy Bob')
recipient.add_substitution('number', 1234)
recipient.add_substitution('time', '10:30pm')
recipients << recipient
# then initialize a template
template = SendGrid::Template.new('blahblah7bef2-d25b00')
# create the client
# see client above
# set some defaults
mail_defaults = {
:from => 'no-reply#geo.com',
:html => '<h1>I like email tests</h1>',
:text => 'I like email tests',
:subject =>'Test Email is great',
}
mailer = SendGrid::TemplateMailer.new(client, template, recipients)
# then mail the whole thing at once
mailer.mail(mail_defaults)
I thought it might be my mail_defaults array so I tried this (see below) and received the same error on the same line.
mail_defaults = {
from: 'no-reply#geo.com',
html: '<h1>I like email tests</h1>',
text: 'I like email tests',
subject: 'Test Email is great',
}
Do I have an error in my code or is their an error in SendGrids mailer.mail method?
This problem is with mail.mailer. This uses the to_h method internally, which was implemented in Ruby 2.1. Effectively, the sendgrid sdk requires ruby 2.1 now. I had the same issue with Ruby 1.9.3 and solved it by upgrading to 2.1.
This is what I used to upgrade to Ruby 2.1 on CentOS 6 (not my gist):
https://gist.github.com/mustafaturan/8290150
Hope this helps.

Rails and Mailgun send CSV doesn't work

i'm want to generate CSV data and send it via mail to some email-address. For the generation of the CSV i'm using FasterCSV with the following code:
csv_data = FasterCSV.generate(:col_sep => ";") do |csv|
csv << ["timestamp", "staff_firstname", "staff_lastname", "message"]
log.each do |log_entry|
csv << [log_entry.timestamp, log_entry.staff_firstname, log_entry.staff_lastname, log_entry.message]
end
end
The csv_data i want to send via a ActionMailer method and therefore i'm using the following code:
def log_csv_export(log_csv, email)
mail.attachments["log.csv"] = log_csv
mail(:to => email, :subject => 'Export Log' )
end
To call the ActionMailer method i'm using:
AccountMailer.log_csv_export(csv_data, email).deliver
If I test it, the mail was send to the transmitted email address, but without an attachment. The csv-data is shown as plain text in the email, but not as attachment to save.
This problem only occurs if i send the mail via heroku mailgun. If i'm testing it with
ActionMailer::Base.delivery_method = :sendmail in the config, then it works.
Did someone knows what the issue is or what i need to change that it works?
Thank you.

ActionMailer 3 error - undefined method `encode!' for "Welcome":String

I'm getting this error while sending mail to the registered user in rails 3:
undefined method 'encode!' for "Welcome":String
I have the following code
#content = content
mail(:to => content[:email], :subject => "test")
If there is a subject then above error message displaying, if I remove the subject content
#content = content
mail(:to => content[:email], :subject => "") no error message sending with out subject
I'm using:
Rails version 3.0.1
action mailer 3.0.1
mail gem checks for Encoded global constant. If its defined by any gem or your code then it calls encode! on the mail object. Here is this call from UnstructuredField mail gem class:
def encode(value)
value.encode!(charset) if defined?(Encoding) && charset
(value.not_ascii_only? ? [value].pack("M").gsub("=\n", '') : value).gsub("\r", "=0D").gsub("\n", "=0A")
end
For me it was mail subject, a String, so I monkey patched String:
class String
def encode!(value)
#Do any encoding or simply return it
value
end
end
Try using ruby version 1.9
I got this error while using devise with rails 3.0.3 and ruby 1.8.7.
I migrated to ruby 1.9 and it worked like a charm.

sendmail_setting for hostingrails

Good afternoon,
I'm facing a problem about the way to send email through my application hosted on hostingrails.
In my config/initializers I added a file "setup_mailer" containing this
ActionMailer::Base.delivery_method = :sendmail
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.default_charset = "utf-8"
# Production
if Rails.env.production?
ActionMailer::Base.sendmail_settings = {
:location => '/usr/sbin/sendmail',
:arguments => '-i -t -f support#xxxxx.xxx'
}
end
and my mailer is as below
class Notification < ActionMailer::Base
def subscription_confirmation(user)
setup_email(user)
mail(:to => #recipients, :subject => "blabla")
end
protected
def setup_email(user)
#recipients = user.email
#from = "support#xxxxx.xx"
headers "Reply-to" => "support#xxxxx.xx"
#sent_on = Time.now
#content_type = "text/html"
end
end
It seems to work very fine on my local machine. But in production, emails are not sent properly and I receive this message in my support inbox.
A message that you sent using the -t command line option contained no
addresses that were not also on the command line, and were therefore
suppressed. This left no recipient addresses, and so no delivery could
be attempted.
If you have any idea, the support seems cannot help me, hope some of you'll have ideas or config files from hostingrails to share.
Thank you,
albandiguer
I had exactly the same problem - resolved it by removing the -t from the sendmail_settings.
I haven't looked much further to investigate other implications, but at least it works. But from the man page:
-t Extract recipients from message headers. These are added to any
recipients specified on the command line.
With Postfix versions prior to 2.1, this option requires that no
recipient addresses are specified on the command line.
So maybe just a difference in Postfix versions?
Try calling to_s on user.email or specifying user email as "#{user.email}"

Resources