SendGrid邮件发送正常但模板未加载问题求助
SendGrid邮件发送正常但模板无法加载的排查方案
问题概述
SendGrid邮件可正常发送,但所有模板均无法加载,怀疑是代码调用逻辑问题,相关代码及日志如下:
控制器调用代码
AdminMailer.with( email: "xxxxxxxxx@gmail.com" , id:item.id, name: item.name, room: item.room.name).send_stock.deliver_later
AdminMailer实现代码
class AdminMailer < ApplicationMailer def send_stock mail(to: params[:email], subject: 'Foto sin inventario', body: 'email body', delivery_method_options: { api_key: ENV["SENDGRID_API"] }, template_id: 'd-2d99d960ed47490497f1a99af32cd706', dynamic_template_data:{ 'id': params[:id], 'name': params[:name], 'room': params[:room] } ) end
Rails输出日志
[ActiveJob] [ActionMailer::MailDeliveryJob] [d8927648-36ca-4e60-afd3-7fe6ea1b936f] Performing ActionMailer::MailDeliveryJob (Job ID: d8927648-36ca-4e60-afd3-7fe6ea1b936f) from Async(mailers) enqueued at 2022-09-29T22:08:22Z with arguments: "AdminMailer", "send_stock", "deliver_now", {:params=>{:email=>"xxxxxxxxx@gmail.com", :id=>4, :name=>"foto 3 exclusive", :room=>"Sala 1"}, :args=>[]} [ActiveJob] [ActionMailer::MailDeliveryJob] [d8927648-36ca-4e60-afd3-7fe6ea1b936f] AdminMailer#send_stock: processed outbound mail in 1.0ms [ActiveJob] [ActionMailer::MailDeliveryJob] [d8927648-36ca-4e60-afd3-7fe6ea1b936f] Delivered mail 6336175785e4_366932af97af0d39c27826@miguel.mail (7142.5ms) [ActiveJob] [ActionMailer::MailDeliveryJob] [d8927648-36ca-4e60-afd3-7fe6ea1b936f] Date: Thu, 29 Sep 2022 17:08:23 -0500 From: xxxxxxxxx@gmail.com To: xxxxxxxxx@gmail.com Message-ID: <6336175785e4_366932af97af0d39c27826@miguel.mail> Subject: Foto sin inventario Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit template-id: d-2d99d960ed47490497f1a99af32cd706 dynamic-template-data: {:id=>4, :name=>"foto 3 exclusive", :room=>"Sala 1"} email body [ActiveJob] [ActionMailer::MailDeliveryJob] [d8927648-36ca-4e60-afd3-7fe6ea1b936f] Performed ActionMailer::MailDeliveryJob (Job ID: d8927648-36ca-4e60-afd3-7fe6ea1b936f) from Async(mailers) in 7150.18ms
核心问题与修复步骤
1. 移除body参数
显式设置body会覆盖SendGrid模板的渲染逻辑,导致模板内容无法加载。删除body: 'email body'这一行,让SendGrid优先使用指定的动态模板。
修改后的send_stock方法:
def send_stock mail(to: params[:email], subject: 'Foto sin inventario', delivery_method_options: { api_key: ENV["SENDGRID_API"] }, template_id: 'd-2d99d960ed47490497f1a99af32cd706', dynamic_template_data:{ 'id': params[:id], 'name': params[:name], 'room': params[:room] } ) end
2. 修正邮件内容类型
日志显示邮件Content-Type为text/plain,而动态模板通常为HTML格式,需显式指定内容类型为text/html,确保SendGrid正确解析模板:
mail(to: params[:email], subject: 'Foto sin inventario', content_type: 'text/html', delivery_method_options: { api_key: ENV["SENDGRID_API"] }, template_id: 'd-2d99d960ed47490497f1a99af32cd706', dynamic_template_data:{ 'id': params[:id], 'name': params[:name], 'room': params[:room] } )
3. 验证模板与数据匹配
- 核对
template_id是否与SendGrid控制台中的模板ID完全一致,注意保留d-前缀。 - 确认模板中使用的变量名(如
{{id}}、{{name}})与dynamic_template_data中的键完全匹配,区分大小写。
内容的提问来源于stack exchange,提问作者Msantamaria
相关产品推荐
相关产品推荐

