Peter Boomsma
Peter Boomsma

Reputation: 9798

Mail sent through Rails app is empty

I'm trying to set up a contact form on my Rails app but although a email is send and recieved the content of the email is empty.

This is the body of the email

!!!
%html
  %body
    %p
      = @message.name
      Schreef het volgende:
    %p= @message.email
    %p= @message.message

So at the moment I'm only getting Schreef het volgende in my email.

My MessagesController

class MessagesController < ApplicationController

    def create
      @message = Message.new(message_params)
      if @message.valid?
        # TODO send message here
        Messages.new_messages_email(@messages).deliver
        redirect_to root_url, notice: "Message sent! Thank you for contacting us."
      else
        redirect_to root_url, notice: "Something went wrong, try again!"
      end
    end

    private
    def message_params
      params.require(:message).permit(
        :name, 
        :message,
        :email
      )
    end
end

My Messages model

class Message
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :name, :email, :message

  validates_presence_of :name
  validates :email, :email_format => {:message => 'is not looking good'}
  validates_length_of :message, :maximum => 500

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def persisted?
    false
  end
end

My Messages mailer,

class Messages < ActionMailer::Base
  default from: "[email protected]"

    def new_messages_email(message)

    @message = Message.new
    mail(to: '[email protected]',
        subject: 'Iemand wilt contact met U')
    end
end

And the form

= form_for @message do |f|
  .field
    %br/
    = f.text_field :name, :placeholder => "Naam"
  .field
    %br/
    = f.text_field :email, :placeholder => "Emailadres"
  .field
    %br/
    = f.text_area :message, :rows => 5, :placeholder => "Uw bericht"
  .actions= f.submit "Verstuur bericht", :id => "submit"

I'm trying to do set this up without storing the emails in a database. Does anyone know why the content put in the fields isn't send in the email?

Upvotes: 0

Views: 99

Answers (1)

blelump
blelump

Reputation: 3243

You have very similar issue to the previous one :-) .

First, Messages.new_messages_email(@messages).deliver. Not @messages, but @message. Second:

class Messages < ActionMailer::Base
  default from: "[email protected]"

    def new_messages_email(message)

      @message = message # See the difference?
      mail(to: '[email protected]', subject: 'Iemand wilt contact met U')
    end
end

Upvotes: 2

Related Questions