|
2 | 2 |
|
3 | 3 | require_relative "supermail/version" |
4 | 4 |
|
| 5 | +require 'mail' |
| 6 | +require "supermail/version" |
| 7 | + |
5 | 8 | module Supermail |
6 | 9 | class Error < StandardError; end |
7 | | - # Your code goes here... |
| 10 | + |
| 11 | + # A simple Email builder that wraps Mail::Message |
| 12 | + class Email |
| 13 | + # Hook to ensure default initialization runs before any subclass initialize |
| 14 | + module Defaults |
| 15 | + def initialize(*args, &block) |
| 16 | + # default fields |
| 17 | + @cc = [] |
| 18 | + @bcc = [] |
| 19 | + @headers = {} |
| 20 | + @attachments = [] |
| 21 | + super |
| 22 | + end |
| 23 | + end |
| 24 | + |
| 25 | + # Whenever subclassing, prepend Defaults to ensure it wraps initialize |
| 26 | + def self.inherited(subclass) |
| 27 | + subclass.prepend Defaults |
| 28 | + super |
| 29 | + end |
| 30 | + |
| 31 | + attr_accessor :from, :to, :cc, :bcc, :subject, |
| 32 | + :reply_to, :return_path, :date, :message_id, |
| 33 | + :in_reply_to, :references, :headers, |
| 34 | + :text_body, :html_body, :attachments |
| 35 | + |
| 36 | + # Builds a Mail::Message from this Email's attributes |
| 37 | + # @return [Mail::Message] |
| 38 | + def message |
| 39 | + mail = Mail.new |
| 40 | + mail.from = Array(from) if from |
| 41 | + mail.to = Array(to) |
| 42 | + mail.cc = cc if cc.any? |
| 43 | + mail.bcc = bcc if bcc.any? |
| 44 | + mail.reply_to = Array(reply_to) if reply_to |
| 45 | + mail.return_path = return_path if return_path |
| 46 | + mail.date = date if date |
| 47 | + mail.message_id = message_id if message_id |
| 48 | + mail.in_reply_to = in_reply_to if in_reply_to |
| 49 | + mail.references = references if references |
| 50 | + |
| 51 | + # Custom headers |
| 52 | + headers.each { |key, value| mail.header[key] = value } |
| 53 | + |
| 54 | + mail.subject = subject if subject |
| 55 | + |
| 56 | + # Bodies |
| 57 | + if text_body |
| 58 | + mail.text_part = Mail::Part.new do |
| 59 | + body text_body |
| 60 | + end |
| 61 | + end |
| 62 | + |
| 63 | + if html_body |
| 64 | + mail.html_part = Mail::Part.new do |
| 65 | + content_type 'text/html; charset=UTF-8' |
| 66 | + body html_body |
| 67 | + end |
| 68 | + end |
| 69 | + |
| 70 | + # Attachments (each as a hash: { filename:, content: }) |
| 71 | + attachments.each do |att| |
| 72 | + mail.add_file filename: att[:filename], content: att[:content] |
| 73 | + end |
| 74 | + |
| 75 | + mail |
| 76 | + end |
| 77 | + |
| 78 | + # Delivers the built Mail::Message via its configured delivery_method |
| 79 | + # @return [Mail::Message] |
| 80 | + def deliver |
| 81 | + raise Error, "`to` address is required" unless to |
| 82 | + message.deliver! |
| 83 | + end |
| 84 | + end |
8 | 85 | end |
0 commit comments