I am successfully generating and sending an email with the following code.
class UserMailer < ActionMailer::Base
default :from => '[email protected]',
:date => Time.now
def new_user(user)
mail_subject = ['WELCOME TO ACME, INC', 'USER ACTIVATION']
@user = user
mail.attachments['File One.pdf'] = File.read(File.join(ATTACHMENT_DIR, 'shared', 'file_one.pdf'))
mail.attachments['File Two.pdf'] = File.read(File.join(ATTACHMENT_DIR, 'shared', 'file_two.pdf'))
mail.attachments['File Three.pdf'] = File.read(File.join(ATTACHMENT_DIR, 'shared', 'file_three.pdf'))
mail.attachments['File Four.pdf'] = File.read(File.join(ATTACHMENT_DIR, 'shared', 'file_four'))
mail( :to => user.address.email,
:subject => mail_subject.join(' ~ ').upcase )
end
end
However, the email contains three text documents which are identical to the content of the email body. The view I'm using for the mailer is named new_user.text.erb.
I suspect that for each pdf document I'm attaching, a plain text document is generated as well, the first being the actual email document body and the remaining three are attached along with the pdf documents.
How may I attach these pdf documents without also attaching these (repeating) text documents? Has anyone else run into this?
Try to use attachments['..'] instead of mail.attachments['..], it works here this way, and no duplicates are observed.
I'm on Rails 3.0.7, mail 2.2.19:
The only other difference that I see, is that I've a hash with mime_type and content. But I think that it worked the other way as well, it just was assigning a mime-type which was not adequate.
attachments['event.ics'] = {:mime_type=>'text/calendar', :content => ics}
mail({
:to => email,
:subject => subject,
}) do |format|
format.text { render :inline => mail_template }
...
end
I'm on Rails version 5.2.4.5. Hope it will help:
My reference comes from here 2.3.1 Adding Attachments and Attachments.
If you want to attach multiple files.
Just call this Method repeatedly. And it will send the mail with two file.
attachments["YourFile.csv"] = {mime_type: 'text/csv', content: csv_data}
attachments["YourFile2.csv"] = {mime_type: 'text/csv', content: csv_data}
This is my example that generate CSV and PDF and mail them in same time for your reference:
headers = ['Name', 'Age', 'Party', 'Vote']
csv_data = CSV.generate(headers: true) do |csv|
csv << headers
@candidates.each do |people|
csv << [people.name, people.age, people.party, people.vote_logs_count]
end
end
attachments["Report.csv"] = {mime_type: 'text/csv', content: csv_data}
attachments["Report2.pdf"] = WickedPdf.new.pdf_from_string(
render_to_string(:pdf => "pdf",:template => 'candidates/pdf.html.erb')
)
mail(
from: "SomeOne" + "@SomeHashDomain.mailgun.org",
to: '[email protected]',
subject: "CSV and PDF report"
)
Supplementary note: I use WickedPdf Gem to generate PDF.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With