[英]Rails Mailer using SendGrid Template
如何使用smtpapi-ruby gem將我的rails郵件綁定到Sendgrid? 我已經按照他們有限的文檔 ,但我的電子郵件沒有通過,我已經驗證我的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: "test@test.com"
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活動日志中看到任何內容,所以它甚至沒有被發送到那里,至少我的猜測。
我究竟做錯了什么?
我認為你混淆了你的變量。 你調用hdr.to_json
,param名稱是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: 'test@test.com',
to: 'recipient@test.com',
subject: "Hello World"
)
如果UserNotifier.welcome
用於應用的其他部分,您也可以傳遞內容:
UserNotifier.welcome(user: @user, subject: "Welcome!").deliver_now
# user_notifier.rb
class UserNotifier < ApplicationMailer
default from: "test@test.com"
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: 'test@test.com',
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>
查看使用其模板系統的Sendgrid文檔
您必須將郵件中的代碼更改為:
class UserNotifier < ApplicationMailer
default from: "test@test.com"
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.