Module: Email

Defined in:
lib/email.rb,
lib/email/email.rb

Class Method Summary collapse

Class Method Details

.send_attachments_email(from, password, to, subject, body, attachments) ⇒ Object



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

def Email.send_attachments_email(from, password, to, subject, body, attachments)
  # Read a file and encode it into base64 format
  begin
    encoded_attachments = []
    attachments.each do |attachment|
      file_content = File.read(attachment)
      encoded_content = [file_content].pack("m")   # base64
      encoded_attachments << [attachment, encoded_content]
    end
  rescue
    raise "Could not read file #{attachment}"
  end

  marker = (0...50).map{ ('a'..'z').to_a[rand(26)] }.join
  parts = []
  parts << <<EOF
From: #{from}
To: #{to}
Subject: #{subject}
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=#{marker}
--#{marker}
EOF

  # Define the message action
  parts << <<EOF
Content-Type: text/plain
Content-Transfer-Encoding:8bit

#{body}
--#{marker}
EOF

  encoded_attachments.each do |attachment, encoded_content|
  # Define the attachment section
  parts << <<EOF
Content-Type: multipart/mixed; name=\"#{File.basename(attachment)}\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename="#{File.basename(attachment)}"

#{encoded_content}
--#{marker}--
EOF
  end

  mailtext = parts.join('')
  send_raw_email(from, password, to, mailtext)
end

.send_email(from, password, to, subject, body) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/email/email.rb', line 13

def Email.send_email(from, password, to, subject, body)
  marker = (0...50).map{ ('a'..'z').to_a[rand(26)] }.join
  parts = []
  parts << <<EOF
From: #{from}
To: #{to}
Subject: #{subject}
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=#{marker}
--#{marker}
EOF

  # Define the message action
  parts << <<EOF
Content-Type: text/plain
Content-Transfer-Encoding:8bit

#{body}
--#{marker}
EOF

  mailtext = parts.join('')
  send_raw_email(from, password, to, mailtext)
end

.send_raw_email(from, password, to, mail_text) ⇒ Object



5
6
7
8
9
10
11
# File 'lib/email/email.rb', line 5

def Email.send_raw_email(from, password, to, mail_text)
  smtp = Net::SMTP.new('smtp.gmail.com', 587)
  smtp.enable_starttls
  smtp.start(from.split('@')[-1], from, password, :login) do
    smtp.send_message(mail_text, from, to)
  end
end