在Rails中使用SendGrid Web API发送邮件:如何将邮件发送代码从控制器抽象并实现简洁调用
把SendGrid邮件逻辑抽象为服务类的实现方案
第一步:创建服务类文件
在你的Rails项目的app/services目录下(没有的话直接新建这个目录),创建send_grid_mailer_service.rb文件,把邮件发送的核心逻辑封装进去:
class SendGridMailerService def self.perform(from_email, to_email, subject, content) # 初始化邮件核心对象 from = SendGrid::Email.new(email: from_email) to = SendGrid::Email.new(email: to_email) content = SendGrid::Content.new(type: 'text/plain', value: content) mail = SendGrid::Mail.new(from, subject, to, content) # 调用SendGrid API发送邮件 sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']) # 强烈建议把API密钥存到环境变量,别硬编码在代码里! response = sg.client.mail._('send').post(request_body: mail.to_json) # 返回响应结果,方便控制器做后续处理 response end end
第二步:在控制器里简洁调用
现在你只需要在控制器里写一行核心调用代码,就能触发邮件发送了,示例如下:
# 控制器中的调用示例 def send_email response = SendGridMailerService.perform( 'sender@example.com', 'recipient@example.com', 'Sending with SendGrid is Fun', 'and easy to do anywhere, even with Ruby' ) # 根据API返回的响应做后续处理 if response.status_code == '202' redirect_to some_path, notice: '邮件发送成功!' else redirect_to some_path, alert: '邮件发送失败,请稍后重试' end end
进阶:支持更多定制化需求
如果需要发HTML邮件、多个收件人这类功能,你可以扩展服务类的方法,比如:
class SendGridMailerService def self.perform(from_email, to_emails, subject, content, content_type: 'text/plain') from = SendGrid::Email.new(email: from_email) # 处理多个收件人 tos = to_emails.map { |email| SendGrid::Email.new(email: email) } content = SendGrid::Content.new(type: content_type, value: content) mail = SendGrid::Mail.new(from, subject, tos.first, content) # 添加额外的收件人 tos[1..].each { |to| mail.add_to(to) } sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY']) sg.client.mail._('send').post(request_body: mail.to_json) end end # 调用示例(发送HTML邮件给多个人) SendGridMailerService.perform( 'sender@example.com', ['user1@example.com', 'user2@example.com'], 'HTML邮件测试', '<h1>Hello!</h1><p>这是一封HTML格式的邮件</p>', content_type: 'text/html' )
这样所有邮件相关的逻辑都集中在服务类里,控制器代码会非常清爽,后续要修改SendGrid的调用逻辑,只需要维护这一个文件就好~
内容的提问来源于stack exchange,提问作者Andy
相关产品推荐
相关产品推荐

