2015-09-25 2 views
5

Как мне привязать почтовый ящик рельсов к Sendgrid, используя драгоценный камень smtpapi-ruby? Я следил за их limited documentation, но мои письма не проходят, я проверял, что моя реализация SendGrid отлично работает при отправке простого электронного письма, так что это не так. Это то, что у меня есть:Rails Mailer с использованием шаблона SendGrid

user_controller.rb

def create 
    @user = User.new(user_params) 

    respond_to do |format| 
     if @user.save 
     format.html { redirect_to @user, notice: 'User was successfully created.' } 
     format.json { render :show, status: :created, location: @user } 


     header = Smtpapi::Header.new 
     header.add_to(@user.email) 
     header.add_substitution('user', [@user.name]) 
     header.add_substitution('body', "You've registered! This is from the controller.") 
     header.add_filter('templates', 'enable', 1) 
     header.add_filter('templates', 'template_id', 'xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx') 
     header.to_json 

     UserNotifier.welcome(header).deliver 
     else 
     format.html { render :new } 
     format.json { render json: @user.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

отправители/user_notifier.rb

class UserNotifier < ApplicationMailer 
    default from: "[email protected]" 

    def welcome(header) 
    headers['X-SMTPAPI'] = hdr.to_json 
    mail(subject: "Welcome to the site!") 
    end 
end 

просмотров/user_notifier/welcome.html.erb

<html> 
<body> 
    Hi -user-<br /> 
    Thanks so much for joining us! 

    <p>-body-</p> 

    Thanks,<br /> 
    The Microblog Team 
</body> 
</html> 

Я не вижу ничего в журнале активности SendGrid, поэтому его даже не отправляют туда, по крайней мере, это мое предположение.

Что я делаю неправильно?

ответ

6

Я думаю, что вы перепутали переменные. Вы вызываете hdr.to_json, а имя параметра - header, которое также уже преобразовано в json.

Вы должны включить заголовок мета-данных непосредственно в UserNotifier:

headers "X-SMTPAPI" => { 
    "sub": { 
     "%name%" => [user.name] 
    }, 
    "filters": { 
     "templates": { 
     "settings": { 
      "enable": 1, 
      "template_id": 'xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx' 
     } 
     } 
    } 
    }.to_json 

# the 'to' email can be overridden per action 
mail(
    from: '[email protected]', 
    to: '[email protected]', 
    subject: "Hello World" 
) 

Вы также можете передать содержание, если UserNotifier.welcome используется в других частях вашего приложения:

UserNotifier.welcome(user: @user, subject: "Welcome!").deliver_now 

# user_notifier.rb 

class UserNotifier < ApplicationMailer 
    default from: "[email protected]" 

    def welcome(user: , subject: , template: "default") 

    # template's default view is "default" 
    headers "X-SMTPAPI" => { 
    "sub": { 
     "%name%" => [user.name] 
    }, 
    "filters": { 
     "templates": { 
     "settings": { 
      "enable": 1, 
      "template_id": 'xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx' 
     } 
     } 
    } 
    }.to_json 

    mail(
     from: '[email protected]', 
     to: user.email, 
     subject: subject, 
     template_path: 'path/to/view', 
     template_name: template 
    ) 
    # this would try to render the view: `path/to/view/default.erb` 
    end 
end 

В шаблоне, вы можете включить теги замещения, указав название тега:

<h1>Hello %name%!</h1> 

More information about substitution tags

ЗАКАНЧИВАТЬ документы Sendgrid на using their template system

3

Вы должны изменить код в вашей почтовой программе, чтобы что-то вроде:

class UserNotifier < ApplicationMailer 
    default from: "[email protected]" 

    def welcome(hdr) 
    headers['X-SMTPAPI'] = hdr.asJSON() 
    mail(subject: "Welcome to the site!") 
    end 
end 

Пример: https://sendgrid.com/docs/Integrate/Code_Examples/SMTP_API_Header_Examples/ruby.html

+0

Ok, это имеет смысл, но теперь я получаю 'неопределенного локальные переменные или метод' заголовка»для # ' ' – Godzilla74

+0

ваших ApplicationMailer' inheriths от 'ActionMailer :: Base'? если нет, вы можете попробовать использовать следующее: 'class UserNotifier Aguardientico

+0

Пришлось изменить строку на' headers ['X-SMTPAPI'] = hdr.to_json', после чего она отправит ... все еще не собирается хотя. – Godzilla74