Class: SFMC::Transactional::Email

Inherits:
SFMCBase
  • Object
show all
Defined in:
lib/sfmc/transactional/email.rb

Constant Summary

Constants inherited from SFMCBase

SFMCBase::NAME_TO_METHOD

Class Method Summary collapse

Methods inherited from SFMCBase

authenticate_and_retry, request

Methods included from Helpers

#get_subscriber_key, #init, #set_base_uri

Methods included from Errors

#error_class, #error_message

Class Method Details

.create_email_send_definition_and_retry(name, to, params) ⇒ Object

If an email hasn’t ever been sent then we will not have an email send definition We’re waiting a minute for the send definition to fully be initialized Thankfully this is a rare edge case



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/sfmc/transactional/email.rb', line 9

def self.create_email_send_definition_and_retry(name, to, params)
  asset = SFMC::Assets::Asset.query("name eq '#{name}'", 'customerKey')
  raise SFMC::Errors::BadRequestError, "No emails found with name #{name}" if asset.count == 0

  consumer_key = asset.items.first["customerKey"]

  SFMC::Transactional::SendDefinition.create(name, consumer_key)

  # Even though the send def is "Active" it won't function for another minute
  delay(run_at: 70.seconds.from_now).send_email(email: name, to: to, params: params, create_email_if_needed: false)
end

.send_email(email:, to:, params: {}, create_email_if_needed: true) ⇒ Object

Will attempt once to create a new email send definition if one isn’t found



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
# File 'lib/sfmc/transactional/email.rb', line 22

def self.send_email(email:, to:, params: {}, create_email_if_needed: true)
  subscriber_key = get_subscriber_key(to)
  message_key = SecureRandom.uuid
  data_extension_params = {
    SubscriberKey: subscriber_key,
    EmailAddress: to,
    **params,
  }

  email_params = {
    definitionKey: email,
    recipient: {
      contactKey: subscriber_key,
      to: to,
      attributes: data_extension_params,
    },
  }

  # If SFMC::Errors::NotFoundError is raised then we need to create an email send definition
  begin
    create(message_key, email_params)
  rescue SFMC::Errors::NotFoundError
    raise unless create_email_if_needed

    create_email_send_definition_and_retry(email, to, params)
  end
end