piątek, 20 sierpnia 2010

Ruby - sending mails with attachements

Recently I have worked on the ruby script that would do some processing and afterwards would send an email containing the results nad charts (generated with gruff).

At first I tried the plain Net:SMTP and it was sufficient for my needs until I reached the attachements part. With the low level API it was very difficult to make it working (I reached the state that the attachements were sent with the email but they were corrupted). Fortunately I found on the web mailfactory gem (http://rubyforge.org/projects/mailfactory/, can be installed using gem install mailfactory) that helps the programmer to construct the content of the email that will be send with the Net:SMTP mechanisms later on. I really recommend it for its simplicity and ease of use. Below I enclose some example to show show to construct basic message with attachements:

def createInitialMail(subject, msg, from, to)
mail = MailFactory.new
mail.to = to
mail.from = from
mail.subject = subject
mail.html = msg
return mail
end

mail = createInitialMail subject, msg, from, to
mail.attach filename

...

Net::SMTP.start(host, port, host, account, password, :plain) do smtp
to_address = mail.to
smtp.send_message mail.to_s, from, to_address
smtp.finish
end


The createInitialMessage method is used in the example to build the main mail object. I marked with green colour the place how add attachements to the message. At the end there is an example how to send the previously constructed message using the Net::SMTP.

Brak komentarzy:

Prześlij komentarz