Rails and Mailgun send CSV doesn't work - ruby-on-rails

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.

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)

Delayed Job - Mail is not sending for spreadsheet data

In rails 4.2.4, I am using gem 'delayed_job_active_record' & gem 'daemons' for sending an emails.
Also I am importing a data from .csv and .xls file to my database. After saving an object I am trying to send an email using delay, but right now mail is sending only for data which is imported from .csv file. Mail is not sending for the data which is imported from .xls file.
I am using gem 'roo' for extracting xls file data.
In delayed_jobs table for spreadsheet data, handler field contains like below,
raw_attributes:
name: User1
email: &5 !ruby/string:Spreadsheet::Link
str: user1#gmail.com
url: mailto:user1#gmail.com
fragment:
In the same delayed_jobs table for csv data, handler field contains like below,
raw_attributes:
name: "User2\tuser2#gmail.com\t111111333"
id: 7
email:
mobile_number:
I am extracting xls file data like below,
def extract_asset_data_from_xls(asset)
require 'spreadsheet'
filename = "#{Rails.root}/#{asset.document.path}"
if File.exist?(filename)
file = File.open(filename)
if file
worksheet = Spreadsheet.open(file).worksheet(0)
1.upto worksheet.last_row_index do |index|
row = worksheet.row(index)
user = User.new
user.name = row[0]
user.email = row[1]
user.save
end
end
else
puts "#{filename} doesn't exists".red
return
end
end
How can I send an email to spreadsheet's data using delay?

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

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

Rails 2 - sending pdf via emailer

I'm using ruby 1.8.7, rails 2.3.4, rubygems 1.3.6, windows 7 home basic.
Objective: to convert a html page into pdf and send it via email. (like an online receipt)
Here's what i used: prawn (for pdf) emailer (for email)
question: how to do i send an email to a real email address? All i got from the tutorial is sending an "email" that can be seen in command prompt. that's all. another question is how to generate pdf's on the fly, meaning there should be no file generated and attach it to an email? It's really hard and I have been working on this for weeks now. thanks.
The precise answer to your question depends on precisely how you're generating your pdfs, but here's an example that should work:
1) In your controller file (as part of an action)
pdf_doc = Prawn::Document.new()
pdf.text "Hello, world" # etc, etc
data_string = pdf_doc.render
user = 'me#example.com'
Emailer.deliver_email_with_attachment(user,data_string)
2) In your mailer file (e.g. app/models/emailer.rb)
class Emailer < ActionMailer::Base
def email_with_attachment(user, data)
# setup your email as normal using #from, #subject, etc
#from = user
# now attach the pdf
attachment :content_type => "application/pdf", :body => data
end
end
for more information on attachments in ActionMailer see The rails docs
EDIT: You should also make sure you've edited your config file(s) to make sure your rails app can send emails. As you're using windows you'll need to configure sending by SMTP:
config/environments/development.rb
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => "my.smtp-server.com",
:port => 25,
:domain => 'iwantgreatcare.org',
:user_name => 'username',
:password => 'password',
:authentication => 'plain',
}
For more information on configuring smtp setting see the Rails ActionMailer guide

How do I email a PDF generated using PDFKit and on Heroku in Rails?

I am using PDFKit on Heroku (and also locally for dev) and am having difficulty emailing the generating PDF from my cron task.
This is the code in my cron job:
kit = PDFKit.new(html_file)
file = kit.to_pdf
OutboundMailer.deliver_pdf_email(file)
#kit.render_file("pdf_from_cron.pdf")
This is the code in my Mailer:
def pdf_email(pdf)
subject "This is your batch of letters"
recipients "helloworld#gmail.com"
from "Batch Email <hello#batch.com>"
sent_on Date.today
body "This is the body of pdf"
attachment "application/pdf" do |a|
a.filename = "batch-letters.pdf"
a.body = pdf
end
end
I setup PDFKit on Heroku once and followed: http://blog.mattgornick.com/using-pdfkit-on-heroku. You may need to include the binary.

Resources