Class: Render25::Emails
- Inherits:
-
Object
- Object
- Render25::Emails
- Defined in:
- lib/render25/emails.rb
Instance Method Summary collapse
-
#initialize(client) ⇒ Emails
constructor
A new instance of Emails.
- #send(options = {}) ⇒ Object
Constructor Details
#initialize(client) ⇒ Emails
Returns a new instance of Emails.
8 9 10 |
# File 'lib/render25/emails.rb', line 8 def initialize(client) @client = client end |
Instance Method Details
#send(options = {}) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
# File 'lib/render25/emails.rb', line 12 def send( = {}) sender = [:from] || [:from_address] raise ValidationError, "Render25: :from address is required" unless sender to = [:to] raise ValidationError, "Render25: :to must contain at least one recipient" unless to to = [to] if to.is_a?(String) raise ValidationError, "Render25: :subject is required" unless [:subject] payload = { from: sender, to: to, subject: [:subject], text: [:text] || '', html: [:html] || '' } if [:cc] payload[:cc] = [:cc].is_a?(Array) ? [:cc] : [[:cc]] end if [:bcc] payload[:bcc] = [:bcc].is_a?(Array) ? [:bcc] : [[:bcc]] end reply_to = [:reply_to] || [:replyTo] payload[:reply_to] = reply_to if reply_to if [:attachments] && [:attachments].is_a?(Array) payload[:attachments] = [:attachments].map do |att| filename = att[:filename] || 'attachment.bin' content = att[:content] content_type = att[:content_type] || att[:contentType] || 'application/octet-stream' b64_content = if content.is_a?(String) && File.exist?(content) Base64.strict_encode64(File.binread(content)) elsif content.is_a?(String) begin Base64.strict_decode64(content) content rescue Base64.strict_encode64(content) end else Base64.strict_encode64(content.to_s) end { filename: filename, content: b64_content, content_type: content_type } end end uri = URI.parse("#{@client.base_url}/api/send") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = (uri.scheme == 'https') http.open_timeout = 10 http.read_timeout = 30 request = Net::HTTP::Post.new(uri.request_uri) request['Authorization'] = "Bearer #{@client.api_key}" request['Content-Type'] = 'application/json' request['User-Agent'] = "render25-ruby/#{Render25::VERSION}" request.body = payload.to_json begin response = http.request(request) parsed = JSON.parse(response.body) rescue { "error" => response.body } if response.code.to_i >= 200 && response.code.to_i < 300 parsed else raise Error, "Render25 Error (#{response.code}): #{parsed['error'] || 'Unknown REST API error'}" end rescue StandardError => e raise Error, "Render25 Error: #{e.}" end end |