Saturday, October 4, 2008

Sending Email with attachment in Ruby on Rails using Gmail Account

Its very important to send an email with attachment in Ruby on Rails. Generally most of the applications use this.

I'll write you step by step procedure.

For sending an email you need to to specify the mailer details in environment.rb

require 'smtp_tls' #this is used for GMAIL . click here to get this file. Copy this file in your lib folder.

# ActionMailer Settings
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.default_charset = "utf-8"
ActionMailer::Base.logger = nil #this will prevent you by printing in the log.


ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "gmail.com",
:authentication => :login,
:user_name => "username@gmail.com",
:password => "your assword",
}

To use ActionMailer, you need to create a mailer model.

$ script/generate mailer SendMail

This will create the model file app/models/send_mail.rb

Where ever you want to call the mailer method,
SendMail.deliver_send_attachment(subject, message, document)

"deliver_ " will deliver the email specified with the method.
"send_attachment" method should be in send_mail.rb (model)
In you models app/models/send_mail.rb
class SendMail < ActionMailer::Base
def send_mail(subject, message, document)
@from = "your email"
@subject = subject
@body['message'] = message #@body["message"] here @message will be the instance variable
@recipients = "some email" #recipient email
content_type "text/html"
@sent_on = Time.now
unless document.nil?
part :content_type => document.content_type do |p|
p.attachment :content_type => document.content_type,
:body => File.open("./public/#{your file name}", 'rb') { |f| f.read },
:filename => document.filename
end
end
@layout = :some layout
end
end

In the above code for the attachment I passed document object, in which content type (image, doc, pdf etc.,)is saved.
generally the content type will be
"application/msword" -> for MSword
"application/pdf" -> for MSword
"image/gif" -> for gif images

Instead of document.content_type you hard code it by the type mentioned above.
eg:
part :content_type => "application/pdf" do |p|
p.attachment :content_type => "application/pdf",
:body => File.open("./public/#{your file name}", 'rb') { |f| f.read },
:filename => "file_name"
end

In your views app/views/send_mail/send_attachment.rhtml
Hi some name,
This is the message <%= @message %>

Yours truly,
blah blah.

This will send an email with the attachment using Gmail.

No comments: