2016-02-25 53 views
4

這是我第一次在rails項目中設置郵件。 我被告知使用SparkPost併爲多種動作創建不同語言的模板。Actionmailer - Sparkpost模板和多語言

爲了簡單起見,可以說一個user_signed_up(用戶)郵件。

目前我有這樣的設置工作:

寶石安裝: 'sparkpost'

mail.rb

ActionMailer::Base.smtp_settings = { 
    address: "smtp.sparkpostmail.com", 
    port: 587, 
    enable_starttls_auto: true, 
    user_name: "SMTP_Injection", 
    password: SPARKPOST_API_KEY, 
    domain: 'foo-bar.com' 
} 

ActionMailer::Base.delivery_method = :smtp 
ActionMailer::Base.default charset: "utf-8" 

application_mailer.rb

require 'sparkpost' 
class ApplicationMailer < ActionMailer::Base 
    default from: "Seal Notification <[email protected]>" 
    layout 'mailer' 
end 

signup_mailer.rb

class SignupMailer < ApplicationMailer 
    def user_signed_up(user) 
    receiver = user.email 
    sender = '[email protected]' 
    title = 'Thanks for registering' 
    body = 'This is a test body' 
    sparky = SparkPost::Client.new(SPARKPOST_API_KEY) 
    sparky.transmission.send_message(receiver,sender,title,body) 
    end 
end 

而且我可以成功發送電子郵件。

雖然,由於多種語言和身體風格不同,這絕對不是可擴展的。

現在我需要設置模板以允許非技術人員調整電子郵件模板。

SparkPost Template Create

但這裏是我堅持和回答下列問題會幫助我極大:

1)如何發送特定電子郵件模板?

2)如何將變量傳遞給這些模板?

3)如何處理多語言支持?

謝謝。

回答

7

Here's an intro article在SparkPost中創建模板。

Here's one預覽您的模板併發送測試消息 - 包括變量如何工作(又名'替代數據')。

朗形式紅寶石爲中心的答案如下:

一對夫婦在你的代碼觀察第一:它看起來像你都配置SMTP全球,但在您的註冊郵件使用REST API。我建議通過SMTP的REST API,因爲它具有您需要的模板和其他豐富的功能。

1)您可以管理電子郵件模板SparkPost UI here或直接通過API調用as documented hereThe template syntax is documented here.

一旦你有一個創建併發布了一個模板,你可以使用SparkPost客戶端這樣的發送(假設你的模板ID是「你的模板-EN」):

require 'sparkpost' 

host = 'https://api.sparkpost.com' 
SparkPost::Request.request("#{host}/api/v1/transmissions", API_KEY, { 
    recipients: [ 
    { address: { email: '[email protected]' } } 
    ], 
    content: { 
    template_id: 'your-template-en' 
    } 
}) 

2)SparkPost支持消息級別和收件人級別的'substitution_data',它們是用於模板的JSON格式的變量。以下是一個示例傳輸請求:

SparkPost::Request.request("#{host}/api/v1/transmissions", API_KEY, { 
    recipients: [ 
    { 
     address: { email: '[email protected]' }, 
     substitution_data: { 
     first_name: 'Recip', 
     favorites: { 
      color: 'Orange', 
      ice_cream: 'Vanilla' 
     } 
     } 
    } 
    ], 
    content: { 
    template_id: 'your-template-en' 
    }, 
    substitution_data: { 
    title: 'Daily News' 
    } 
}) 

您現在在模板中使用替代數據。例如:

<h1>{{title}}</h1> 
<p>Hi {{first_name or 'there'}}</p> 
<p>This {{favorites.color}} bulletin is all about {{favorites.ice_cream}} ice cream</p> 

注意:接收者替換數據優先於消息級別字段。

3)對於多語言用例,您可能會考慮像我們其他許多客戶那樣按照語言創建一個模板。

順便說一句,這看起來像幾個問題 - 我們應該考慮分裂它們嗎?

+0

非常感謝你,特別是你對問題2的回答使它「點擊」。 –