Attach file in mail ruby
In Ruby, you can attach a file to an email using the Action Mailer
gem. Here's an example:
# Assuming you have a Mailer class called UserMailer
class UserMailer < ApplicationMailer
def send_file(file_path)
@file = File.read(file_path)
mail to: '[email protected]', subject: 'File Attachment'
end
end
In this example, we're reading the file contents using File.read
and storing it in the @file
instance variable. We're then using the mail
method to send the email with the file attachment.
To attach the file, you can use the attachments
method:
class UserMailer < ApplicationMailer
def send_file(file_path)
attachments['file.pdf'] = File.read(file_path)
mail to: '[email protected]', subject: 'File Attachment'
end
end
In this example, we're attaching the file with the name file.pdf
using the attachments
method. The file contents are stored in the File.read(file_path)
variable.
You can also specify additional options for the attachment, such as the content type and disposition:
class UserMailer < ApplicationMailer
def send_file(file_path)
attachments['file.pdf'] = File.read(file_path)
attachments['file.pdf'].content_type = 'application/pdf'
attachments['file.pdf'].disposition = 'attachment'
mail to: '[email protected]', subject: 'File Attachment'
end
end
In this example, we're setting the content type to application/pdf
and the disposition to attachment
, which tells the email client to download the file instead of displaying it inline.
You can then call the send_file
method in your controller or model to send the email with the file attachment:
class UsersController < ApplicationController
def send_file
UserMailer.send_file('/path/to/file.pdf').deliver_now
end
end
Make sure to replace /path/to/file.pdf
with the actual path to the file you want to attach.