Wednesday, 26 February 2025

Send attachment with mail in rails and active storage

 Routes: 

post "/send_email_with_attachment", to: "articles#send_email_with_attachment"

-----------------------------------

Controller:

class ArticlesController < ApplicationController

  def send_email_with_attachment

    email = "arvind@gmail.com"

    attachment = params[:attachment]

    # Save the file temporarily

    file_path = Rails.root.join('tmp', attachment.original_filename)

    File.open(file_path, 'wb') do |file|

      file.write(attachment.read)

    end

    MyMailer.send_email_with_attachment(email, file_path).deliver_now

    # Delete the temporary file after sending the email

    File.delete(file_path) if File.exist?(file_path)

    redirect_to root_path, notice: 'Email sent successfully'

  end

end


--------------------------

Mailer

class MyMailer < ApplicationMailer

  def send_email_with_attachment(email, attachment_path)

    @greeting = "Hi"

    attachments[File.basename(attachment_path)] = File.read(attachment_path)

    mail(to: email, subject: 'Email with Attachment')

  end

end

-------------------------------

View
Form view:

<%= form_tag "/send_email_with_attachment", class: "inline-form", multipart: true do %>
  <%= file_field_tag :attachment %>
  <%= submit_tag 'Send Email' %>
<% end %>

Mailer view:

<h1>My#send_email_with_attachment</h1>

<p>
  <%= @greeting %>, find me in app/views/my_mailer/send_email_with_attachment.html.erb
</p>

----------------------------

Development.rb

config.action_mailer.perform_deliveries = true
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.default_options = {from: 'localhost:3000'}
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
    address:              'smtp.gmail.com',
    port:                 587,
    domain:               'localhost',
    user_name:            ENV["SMTP_EMAIL"],
    password:             ENV["SMTP_PASSWORD"],
    authentication:       'plain',
    enable_starttls_auto: true
  }

=======================================
With Active storage and with html override

class AnnouncementMailer < ApplicationMailer

  def announcement_created(user, announcement)
    @user = user
    @announcement = announcement
    @association = announcement.custom_association

    # subject = "📢 New Announcement from #{@association.name}"
    subject = "📢 #{announcement.subject}"

    @announcement.announcement_attachments.each do |attachment|
      # next unless attachment.attached? #user this for has_one_attached :announcement_attachment

      # Optional size limit (10MB)
      # next if attachment.byte_size > 10.megabytes

      attachments[attachment.filename.to_s] = {
        mime_type: attachment.content_type,
        content: attachment.download
      }
    rescue StandardError => e
      Rails.logger.info "**********Announcement attachment skipped: #{e.message}"
    end

    template_path = Rails.root.join(
      "app", "views", "announcement_mailer", "announcement_created.html.erb"
    )
    erb_template = File.read(template_path)
    html_body = ERB.new(erb_template).result(binding)
    plain_text = ActionView::Base.full_sanitizer.sanitize(html_body)
    Notification.create(user_id: @user.id, notifiable: announcement, title: subject, message: plain_text, delivery_methods: ["email", "portal"], created_by: announcement.user_id, updated_by: announcement.user_id)
    mail(
      to: @user.email,
      subject: subject,
    ) do |format|
      format.html { render html: html_body.html_safe }
    end
  end
end




No comments:

Post a Comment