Reputation: 139
I created a code which generate xls file, then i pass it to the Mailer to send it as an attachment. But , I keep getting the same errors again and again :
TypeError: no implicit conversion of Spreadsheet::Workbook into String
Or
NoMethodError: undefined method `length' for #<Spreadsheet::Workbook:0x007fe937e4fe80>
My code is :
def xls_mailer (data)
attachments['HelloWorld.xlsx'] = data
mail(subject: "Hi", to: @gmail.email)
end
***data - is the xls file which I;m passing to this Method.
Thank you guys ahead,
Upvotes: 1
Views: 4035
Reputation: 6072
Action Mailer expects you to pass it a File
-like object as an attachment, but your code's passing it the spreadsheet data directly. Fortunately, Ruby has a class called StringIO
that we can use to convert our spreadsheet into something that acts like a File
:
def xls_mailer (spreadsheet)
spreadsheet_file = StringIO.new
spreadsheet.write(spreadsheet_file)
attachments['HelloWorld.xls'] = spreadsheet_file
mail(subject: "Hi", to: @gmail.email)
end
Upvotes: 1
Reputation: 69
The below chunk of code works like a charm. I have tried this, used in a working application.
def send_excel_report(file_name, emails, subject, email_content, file_path, bcc_emails = [])
attachments["#{file_name}.xls"] = File.read(file_path)
mail(to: emails, subject: subject, from: "[email protected]", bcc: bcc_emails) do |format|
format.html { render :partial => "users/mail_body"}
end
end
FYI: I have used spreadsheet gem to create the excel
Upvotes: 1
Reputation: 139
Okay Guys, I found out the answer. The code should be like this :
spreadsheet_file = StringIO.new
data.write(spreadsheet_file)
attachments['HelloWorld.xls'] = spreadsheet_file.read
Upvotes: 3