Class: Cybertrain::Mailer

Inherits:
Object
  • Object
show all
Defined in:
cybertrain/mailer.rb,
cybertrain/mailer.rb,
cybertrain/mailer/later.rb,
cybertrain/mailer/message.rb

Overview

Sends e-mail through an SMTP server: plain text, or with html: a multipart/alternative message, now (Mailer.deliver) or from a job (Mailer.deliver_later).

Examples:

config from the environment (CYBERTRAIN_SMTP_HOST, …)

require "cybertrain/mailer"
require "cybertrain/net/tls"

begin
  Cybertrain::Mailer.deliver(to: user.email, subject: "Welcome", body: "Hello!\n")
rescue Cybertrain::Mailer::Error => e
  Cybertrain.logger.warn("mail: #{e.message}") # never contains the password
end

explicit settings

mailer = Cybertrain::Mailer.new(host: "smtp.example.com", user: "app", password: ENV["SMTP_PASSWORD"].to_s,
                                from: "noreply@example.com")
mailer.deliver(to: "a@example.com, b@example.com", subject: "Report", body: text)

HTML from a partial, sent by a job

html = Cybertrain::Views.render_mail("mail/welcome", user: user)
Cybertrain::Mailer.deliver_later(to: user.email, subject: "Welcome", body: "Welcome!\n", html: html)

Defined Under Namespace

Modules: Message Classes: ConnectError, Error, InsecureError, ProtocolError, RejectedError, TLSError, TimeoutError

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host: Cybertrain.config.smtp_host, port: Cybertrain.config.smtp_port, user: Cybertrain.config.smtp_user, password: Cybertrain.config.smtp_password, from: Cybertrain.config.smtp_from, tls: Cybertrain.config.smtp_tls, timeout: 10, deadline: 60, helo: "localhost", delivery_method: Cybertrain.config.mail_delivery_method) ⇒ Mailer

Each setting defaults to Config’s (smtp_host, smtp_port, …, from the CYBERTRAIN_SMTP_* environment variables).

Parameters:

  • host (String) (defaults to: Cybertrain.config.smtp_host) —

    the SMTP server’s name (or an IP address; TLS checks the certificate against this name, so give a name for TLS)

  • port (Integer) (defaults to: Cybertrain.config.smtp_port) —

    0 for the mode’s port (default_port)

  • user (String) (defaults to: Cybertrain.config.smtp_user) —

    the AUTH PLAIN user; “” sends no AUTH

  • password (String) (defaults to: Cybertrain.config.smtp_password) —

    never logged or shown

  • from (String) (defaults to: Cybertrain.config.smtp_from) —

    the sender address #deliver uses by default

  • tls (String) (defaults to: Cybertrain.config.smtp_tls) —

    “starttls” (the default), “tls” (implicit TLS) or “none” (plain text; refuses to send credentials except to loopback)

  • timeout (Numeric) (defaults to: 10) —

    seconds for each wait. Default 10.

  • deadline (Numeric) (defaults to: 60) —

    seconds for a whole delivery, name resolution included. Default 60.

  • helo (String) (defaults to: "localhost") —

    the name sent with EHLO. Default “localhost”.

  • delivery_method (Symbol) (defaults to: Cybertrain.config.mail_delivery_method) —

    :smtp, or :test to store each message in deliveries instead of connecting (no host is needed then). Default Config#mail_delivery_method: :test in the test environment.

Raises:

  • (ArgumentError) —

    an empty host, an unknown mode, a port out of range, a timeout that is not positive, a delivery method that is not :smtp or :test



284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# File 'cybertrain/mailer.rb', line 284

def initialize(host: Cybertrain.config.smtp_host, port: Cybertrain.config.smtp_port,
               user: Cybertrain.config.smtp_user, password: Cybertrain.config.smtp_password,
               from: Cybertrain.config.smtp_from, tls: Cybertrain.config.smtp_tls,
               timeout: 10, deadline: 60, helo: "localhost",
               delivery_method: Cybertrain.config.mail_delivery_method)
  @mail_delivery_method = delivery_method
  unless delivery_method == :smtp || delivery_method == :test
    refusal = "delivery_method must be :smtp or :test (got #{delivery_method.inspect})"
    raise ArgumentError, refusal
  end
  @mail_host = host.to_s.downcase
  @mail_tls = tls.to_s.downcase
  @mail_user = user.to_s
  @password = password.to_s
  @mail_from = from.to_s
  @mail_timeout = timeout.to_f
  @mail_deadline = deadline.to_f
  @helo_name = helo.to_s
  # :test connects nowhere, so it needs no host (a given one is still
  # checked).
  unless @mail_delivery_method == :test && @mail_host.empty?
    raise ArgumentError, "no SMTP host: set CYBERTRAIN_SMTP_HOST (Config#smtp_host) or pass host:" if @mail_host.empty?
    raise ArgumentError, "the SMTP host name is malformed" unless Mailer.host_name?(@mail_host)
  end
  unless @mail_tls == "starttls" || @mail_tls == "tls" || @mail_tls == "none"
    raise ArgumentError, "tls must be \"starttls\", \"tls\" or \"none\""
  end
  raise ArgumentError, "the EHLO name is malformed" unless Mailer.host_name?(@helo_name)

  configured_port = port.to_i
  raise ArgumentError, "the SMTP port must be from 1 to 65535 (0 for the mode's)" if configured_port < 0 || configured_port > 65_535

  @mail_port = configured_port == 0 ? Mailer.default_port(@mail_tls) : configured_port
  raise ArgumentError, "timeout must be positive" unless @mail_timeout > 0.0
  raise ArgumentError, "deadline must be positive" unless @mail_deadline > 0.0
end

Instance Attribute Details

#mail_deadline ⇒ Float (readonly)

Returns seconds a whole delivery may take.

Returns:

  • (Float) —

    seconds a whole delivery may take



242
243
244
# File 'cybertrain/mailer.rb', line 242

def mail_deadline
  @mail_deadline
end

#mail_delivery_method ⇒ Symbol (readonly)

Returns :smtp (connect and send) or :test (store in deliveries).

Returns:

  • (Symbol) —

    :smtp (connect and send) or :test (store in deliveries)



246
247
248
# File 'cybertrain/mailer.rb', line 246

def mail_delivery_method
  @mail_delivery_method
end

#mail_from ⇒ String (readonly)

Returns the default sender address.

Returns:

  • (String) —

    the default sender address



233
234
235
# File 'cybertrain/mailer.rb', line 233

def mail_from
  @mail_from
end

#mail_host ⇒ String (readonly)

Returns the SMTP server.

Returns:

  • (String) —

    the SMTP server



224
225
226
# File 'cybertrain/mailer.rb', line 224

def mail_host
  @mail_host
end

#mail_port ⇒ Integer (readonly)

Returns its port.

Returns:



227
228
229
# File 'cybertrain/mailer.rb', line 227

def mail_port
  @mail_port
end

#mail_timeout ⇒ Float (readonly)

Returns seconds any one wait may take.

Returns:

  • (Float) —

    seconds any one wait may take



239
240
241
# File 'cybertrain/mailer.rb', line 239

def mail_timeout
  @mail_timeout
end

#mail_tls ⇒ String (readonly)

Returns “starttls”, “tls” or “none”.

Returns:

  • (String) —

    “starttls”, “tls” or “none”



236
237
238
# File 'cybertrain/mailer.rb', line 236

def mail_tls
  @mail_tls
end

#mail_user ⇒ String (readonly)

Returns the AUTH user, “” for none.

Returns:

  • (String) —

    the AUTH user, “” for none



230
231
232
# File 'cybertrain/mailer.rb', line 230

def mail_user
  @mail_user
end

Class Method Details

.default_port(tls) ⇒ Integer

The port a mode uses when none is configured: 587 (submission) for starttls, 465 (submissions) for tls, 25 for none.

Parameters:

  • tls (String)

Returns:



256
257
258
259
260
261
# File 'cybertrain/mailer.rb', line 256

def self.default_port(tls)
  return 465 if tls == "tls"
  return 25 if tls == "none"

  587
end

.deliver(to:, subject:, body:, html: "", from: "") ⇒ String

Sends one message with the settings in Config (Mailer.new’s defaults).

Parameters:

  • to (String) —

    one address, or several separated by commas

  • subject (String) —

    UTF-8; non-ASCII is RFC 2047-encoded

  • body (String) —

    UTF-8 plain text, any line endings

  • html (String) (defaults to: "") —

    UTF-8 HTML; when not empty the message is multipart/alternative, body its text part and this its HTML part (Cybertrain::Mailer::Message.build)

  • from (String) (defaults to: "") —

    the sender; “” for Config#smtp_from

Returns:

  • (String) —

    the server’s reply to the message (“250 2.0.0 Ok: queued as …”); with Config#mail_delivery_method :test (the test environment’s default) the message is checked and stored in deliveries instead, and the answer is “250 2.0.0 stored in Mailer.deliveries”

Raises:

  • (Error) —

    a subclass; ArgumentError for an address, subject or body refused



337
338
339
# File 'cybertrain/mailer.rb', line 337

def self.deliver(to:, subject:, body:, html: "", from: "")
  Mailer.new.deliver(to: to, subject: subject, body: body, html: html, from: from)
end

.deliver_later(to:, subject:, body:, html: "", from: "") ⇒ Integer

Sends one message later, from a job: enqueues the built-in kind “cybertrain mail” with the five fields as a JSON object (to, subject, body, html, from), and a job thread (./<app> server or ./<app> worker) delivers it with deliver and the settings in Config at that time. The fields are checked now, as deliver checks them, so a refused address or subject raises here and nothing is enqueued. Render the bodies before calling (Views.render_mail): the job has no view context.

The whole message, body and HTML included, is stored in the database (the cybertrain_jobs row’s payload, shown on the jobs page) until the job finishes, and for as long as the finished row is kept.

The job’s policy:

  • a TimeoutError, a ConnectError, or a RejectedError with a 4xx reply (421, greylisting’s 450 / 451, 452: RFC 5321 calls them transient) is retried 60 seconds later, until 5 attempts have failed, when the row is failed;
  • a RejectedError with a 5xx reply (a refused address will not become deliverable, a refused login needs the configuration fixed) discards the row;
  • an ArgumentError when the job runs (a field the payload can never send: an empty from: with no Config#smtp_from, no Config#smtp_host, a payload changed in the database that fails the checks again) discards the row too, with nothing sent;
  • any other error follows the default policy (Job).

One message goes to all the recipients in one SMTP transaction, so when the server refuses one of several recipients with a 5xx, the whole job is discarded and the other recipients do not get the mail either (with a 4xx it is retried for all of them). Enqueue one message per recipient when they should not depend on each other.

Examples:

id = Cybertrain::Mailer.deliver_later(to: user.email, subject: "Welcome", body: text, html: html)

Parameters:

  • to (String) —

    one address, or several separated by commas

  • subject (String) —

    UTF-8

  • body (String) —

    UTF-8 plain text

  • html (String) (defaults to: "") —

    UTF-8 HTML, “” for a plain-text message

  • from (String) (defaults to: "") —

    the sender; “” for Config#smtp_from when the job runs

Returns:

Raises:

  • (ArgumentError) —

    for an address, subject or body refused

  • (Cybertrain::DB::Error) —

    when the database is not connected or the insert fails



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'cybertrain/mailer/later.rb', line 68

def self.deliver_later(to:, subject:, body:, html: "", from: "")
  sender = from.to_s
  recipients = to.to_s
  title = subject.to_s
  text = body.to_s
  markup = html.to_s
  Mailer.check_address(sender, "from") unless sender.empty?
  Mailer.split_recipients(recipients)
  Mailer.check_subject(title)
  Mailer.normalize_body(text)
  Mailer.normalize_body(markup) unless markup.empty?
  fields = { "to" => recipients, "subject" => title, "body" => text, "html" => markup, "from" => sender }
  payload = JSON.generate(fields)
  Job.enqueue(JOB_KIND, payload)
end

.deliveries ⇒ Array<MailMessage>

Every message delivered with the delivery method :test, oldest first (Rails’ ActionMailer::Base.deliveries): what a test reads. The test harness (cybertrain/test_help) empties it before every test. Nothing else empties it, so it is for tests: a process that kept :test while serving would keep every mail in memory (boot logs a warning then, Config#mail_delivery_warning). Appends take a lock; reads and clear do not, so read it from the test’s thread while no job thread runs (a test program starts none).

Examples:

assert_equal "Welcome", Cybertrain::Mailer.deliveries.last.mail_subject

Returns:



389
390
391
# File 'cybertrain/mailer.rb', line 389

def self.deliveries
  @deliveries
end

Instance Method Details

#deliver(to:, subject:, body:, html: "", from: "") ⇒ String

Sends one message.

Parameters:

  • to (String) —

    one address, or several separated by commas

  • subject (String) —

    UTF-8; non-ASCII is RFC 2047-encoded

  • body (String) —

    UTF-8 plain text, any line endings

  • html (String) (defaults to: "") —

    UTF-8 HTML; when not empty the message is multipart/alternative (the text part, then the HTML part, both base64, Cybertrain::Mailer::Message.build) with a random boundary

  • from (String) (defaults to: "") —

    the sender; “” for the mailer’s from:

Returns:

  • (String) —

    the server’s reply to the message; with the delivery method :test nothing connects: the message, checked as for SMTP, is appended to deliveries and the answer is STORED_REPLY

Raises:

  • (Error) —

    a subclass; ArgumentError for an address, subject or body refused



354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'cybertrain/mailer.rb', line 354

def deliver(to:, subject:, body:, html: "", from: "")
  given = from.to_s
  sender = given.empty? ? @mail_from : given
  Mailer.check_address(sender, "from")
  recipients = Mailer.split_recipients(to.to_s)
  title = subject.to_s
  Mailer.check_subject(title)
  text = Mailer.normalize_body(body.to_s)
  markup = html.to_s
  built = ""
  unless markup.empty?
    boundary = String.new
    boundary << "=_cybertrain_" << Crypto.random_token(16)
    built = Message.build(sender, to.to_s, title, text, markup, boundary)
  end
  if @mail_delivery_method == :test
    stored = MailMessage.new(to: to.to_s, subject: title, body: body.to_s, html: markup, from: sender)
    return Mailer.store_delivery(stored)
  end

  perform(sender, recipients, title, text, built)
end