Rails - ActionMailer - How to send an attachment that you create?
Asked Answered
P

2

30

In rails3 w ActionMailer, I want to send a .txt file attachment. The challenge is this txt file does not exist but rather I want to create the txt file given a large block of text that I have.

Possible? Ideas? Thanks

Pottle answered 28/2, 2011 at 18:16 Comment(1)
Hey! I wrote a blog post covering this in depth — Rails ActionMailer attachments. Basically, in our mailer methods, we get access to an attachments hash. You can assign file blogs to that hash, like attachments['file.xlsx'] = File.read(/path/to/file.xlsx)Nathalienathan
S
76

It's described for files in the API documentation of ActionMailer::Base

class ApplicationMailer < ActionMailer::Base
  def welcome(recipient)
    attachments['free_book.pdf'] = File.read('path/to/file.pdf')
    mail(:to => recipient, :subject => "New account information")
  end
end

But that doesn't have to be a File, it can be a string too. So you could do something like (I'm also using the longer Hash-based form where you can specify your own mimetype too, you can find documentation for this in ActionMailer::Base#attachments):

class ApplicationMailer < ActionMailer::Base
  def welcome(recipient)
    attachments['filename.jpg'] = {:mime_type => 'application/mymimetype',
                                   :content => some_string }
    mail(:to => recipient, :subject => "New account information")
  end
end
Scuttle answered 28/2, 2011 at 18:18 Comment(6)
Thanks, that worked, but the attachment is showing up at the top of the message. and not at the bottom, ideas?Pottle
Afraid not, that shouldn't happen I think. Maybe something to do with the mimetype of your attachment?Scuttle
If you want your attachment to appear at the bottom instead of the top, try this answer: https://mcmap.net/q/472293/-rails-actionmailer-sometimes-shows-attachments-before-the-email-contentSenhorita
Something gives me the jeebies about an API where you create the attachments but never add them to the mail... I wish the attachments were at least passed into the mail method call...Memoir
@Trejkaz Completely agree. It's strange because if you create a Mail::Message object, you can add attachments to it: ActionMailer::Base.mail( from: ..., to: ... ).attachments['filename.jpg'] = some_stringRequest
Is it possible to do something similar and attach html files?Swaddle
N
4

First the method to send email

class ApplicationMailer < ActionMailer::Base
   def welcome(user, filename, path)
      attachments[filename] = File.read(path)
      mail(:to => user.email, :subject => "New account information")
   end
end

Call the method with the params

UserMailer.welcome(user, filename, path).deliver
Niu answered 11/3, 2020 at 16:58 Comment(1)
I think this does not answer the real question: The challenge is this txt file does not exist but rather I want to create the txt file given a large block of text that I have.Goblet

© 2022 - 2024 — McMap. All rights reserved.