diff --git a/shard.yml b/shard.yml index 674d7b3..e573f96 100644 --- a/shard.yml +++ b/shard.yml @@ -11,7 +11,7 @@ license: MIT dependencies: carbon: github: luckyframework/carbon - version: ~> 0.4.0 + version: ~> 0.5.1 habitat: github: luckyframework/habitat version: ~> 0.4.8 diff --git a/spec/carbon_sendgrid_adapter_spec.cr b/spec/carbon_sendgrid_adapter_spec.cr index e9c9372..68a82c4 100644 --- a/spec/carbon_sendgrid_adapter_spec.cr +++ b/spec/carbon_sendgrid_adapter_spec.cr @@ -154,6 +154,15 @@ describe Carbon::SendGridAdapter do params["personalizations"].as(Array).first.has_key?("asm").should eq(false) end + + it "handles attachments" do + email = FakeEmail.new(text_body: "0") + params = Carbon::SendGridAdapter::Email.new(email, api_key: "fake_key").params + attachments = params["attachments"].as(Array) + attachments.size.should eq(1) + attachments.first["filename"].should eq("contract.pdf") + Base64.decode_string(attachments.first["content"].to_s).should eq("Sign here") + end end end diff --git a/spec/support/fake_email.cr b/spec/support/fake_email.cr index fab39f0..7b6e7ae 100644 --- a/spec/support/fake_email.cr +++ b/spec/support/fake_email.cr @@ -18,4 +18,13 @@ class FakeEmail < Carbon::Email cc @cc bcc @bcc subject @subject + attachment contract + + def contract + { + io: IO::Memory.new("Sign here"), + file_name: "contract.pdf", + mime_type: "application/pdf", + } + end end diff --git a/src/carbon_sendgrid_adapter.cr b/src/carbon_sendgrid_adapter.cr index 2fd9881..2485017 100644 --- a/src/carbon_sendgrid_adapter.cr +++ b/src/carbon_sendgrid_adapter.cr @@ -1,6 +1,7 @@ require "http" require "json" require "carbon" +require "base64" require "./errors" require "./carbon_sendgrid_extensions" @@ -35,7 +36,6 @@ class Carbon::SendGridAdapter < Carbon::Adapter end # :nodoc: - # Used only for testing def params data = { "personalizations" => [personalizations], @@ -45,6 +45,7 @@ class Carbon::SendGridAdapter < Carbon::Adapter "reply_to" => reply_to_params, "asm" => {"group_id" => 0, "groups_to_display" => [] of Int32}, "mail_settings" => {sandbox_mode: {enable: sandbox?}}, + "attachments" => attachments, }.compact if asm_data = email.asm @@ -138,6 +139,19 @@ class Carbon::SendGridAdapter < Carbon::Adapter ].compact end + private def attachments : Array(Hash(String, String)) + files = [] of Hash(String, String) + email.attachments.map do |attachment| + case attachment + in AttachFile, ResourceFile + files.push({"content" => Base64.encode(File.read(attachment[:file_path])), "type" => attachment[:mime_type].to_s, "filename" => attachment[:file_name].to_s, "disposition" => "attachment"}) + in AttachIO, ResourceIO + files.push({"content" => Base64.encode(attachment[:io].to_s), "type" => attachment[:mime_type].to_s, "filename" => attachment[:file_name].to_s, "disposition" => "attachment"}) + end + end + files + end + private def text_content : Hash(String, String)? body = email.text_body if body && !body.empty?