Skip to content

Instantly share code, notes, and snippets.

@johnstanfield
Created December 21, 2016 03:22
Show Gist options
  • Save johnstanfield/82e266f7d9480750b2d313ed995b721a to your computer and use it in GitHub Desktop.
Save johnstanfield/82e266f7d9480750b2d313ed995b721a to your computer and use it in GitHub Desktop.
Example showing how to create a Mail::Message and extract bcc addresses, html, and plain body
# build an email
mail = Mail.new do
to '[email protected]'
from '[email protected]'
bcc ['[email protected]','[email protected]','[email protected]']
subject 'test email'
end
text_part = Mail::Part.new do
body 'This is plain text'
end
html_part = Mail::Part.new do
content_type 'text/html; charset=UTF-8'
body '<h1>This is HTML</h1>'
end
mail.text_part = text_part
mail.html_part = html_part
mail.delivery_method :smtp, address: "yourserver.example.com"
# deliver the email
mail.deliver
# extract the list of bcc addrs
Mail::AddressList.new(mail.header[:bcc].decoded).addresses.each do |bcc|
puts "looks like you want to bcc '#{bcc}'"
end
# extract the html body
html_body = mail.parts.detect{|p|p.content_type =~ /text\/html/}
html = html_body ? html_body.body.raw_source : ""
# extract the plain body
plain_body = mail.parts.detect{|p|p.content_type =~ /text\/plain/}
plain = plain_body ? plain_body.body.raw_source : ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment