본문 바로가기

Wep Develop/Ruby on Rails

[Ruby on Rails] mail gun을 이용한 이메일 전송 구현 (+figaro를 이용한 환경변수 설정)

1. rails g mailer lawmailer

rails g controller home index


law mailer은 메일러의 이름이므로 임의로 해준다.


2. 메일건 가입 및 샌드박스 도메인 확인

https://www.mailgun.com/

도메인 메뉴에 들어가면 샌드박스 도메인이 나온다. -> 테스트용에서 사용하는 도메인


3. 메일건, 피가로 젬을 설치한다.

메일건 : 메일을 보내기 위한 젬

피가로 : 환경변수 설정을 위한 젬.


1
2
gem 'mailgun_rails'
gem 'figaro'
cs

bundle install
bundle exec figaro install

config에 application.yml파일이 생성된다.

4. config/application.yml파일에 다음과 같이 중요한 코드를 적는다.

1
2
Mailgun_Api_Key: "발급받은 키"
Mailgun_Domain: "샌드박스 도메인"
cs



5. config/environment/development.rb에 환경변수를 가져와 적는다.

1
2
3
4
5
6
config.action_mailer.delivery_method = :mailgun
config.action_mailer.mailgun_settings = {
  api_key: ENV["Mailgun_Api_Key"],
  domain: ENV["Mailgun_Domain"],
}
 
cs

이곳에 직접 중요한 키들을 적어버리고 깃헙같은 곳에 올리면 털려서 요금 폭탄이 나올 위험이 있다. 꼭 환경변수 설정 해주기!



6. mailer.rb파일에 다음과 같이 보내는 사람, 받는 사람, 제목, 내용을 적는다.

1
2
3
4
5
6
7
8
class LawmailerMailer < ApplicationMailer
    def testmail title, content
    mail from'보내는사람 이메일',
        to: '받는사람 ',
        subject: title,
        body: content
    end
end
cs


*참조 : 지정 가능한 메일 헤더

to 받는 사람

cc 참조

bcc 숨은참조

subject 내용

date 송신날짜

reply_to 답신메일주소


7. home controller에 다음과 같이 적는다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class HomeController < ApplicationController
  def index
 
  end
 
  def email_send
      title = params[:title]
      content = params[:content]
 
      LawmailerMailer.testmail(title, content).deliver_now
      redirect_to '/'
  end
 
end
cs


LawmailerMailer은 내가 만든 메일러 이름이고

testmail은 mailer.rb에 적었던 이름

deliever.now는 메일을 즉시 전송하는 명령어



8. 뷰파일에 다음과 같이 메일 전송 폼을 만든다.

1
2
3
4
5
6
<h1>이메일쓰기</h1>
<%= form_tag(mail_send_path, method: "post"do %>
    <%= text_field_tag "title"nil, placeholder: "제목" %>
    <%= text_field_tag "content"nil, placeholder: "내용" %>
    <%= submit_tag ("전송") %>
<end %>
cs



9. 라우트 설정을 해준다.

1
2
3
4
5
Rails.application.routes.draw do
  root 'home#index'
  post 'home/email_send' => 'home#email_send', as: 'mail_send'
 
end
cs


끝!!!!!!!!!!!!!!!!