How to attach file in an e-mail using ruby?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • littlemaster
    New Member
    • Apr 2010
    • 25

    How to attach file in an e-mail using ruby?

    I have the following code, it is sending text message. I want to attach a file. How to do that?

    require 'net/smtp' # plain mail
    smtpclient = Net::SMTP::new( '192.168.1.1' ) # create new object to send mail
    the_email="From : ruby_using_smtp @webdevel.co.in \nTo:xxxx@bksys .co.in\nSubject :Birthday \n\n"+"This is for demo" #Frame a mail
    smtpclient.star t # start the mail process
    smtpclient.send mail(the_email, 'ruby_using_smt p@webdevel.co.i n','xxxx@bksys. co.in') # send mail via ruby
    smtpclient.fini sh # operation finished.
    puts "Mail sent Successfully "
  • improvcornartist
    Recognized Expert Contributor
    • May 2007
    • 303

    #2
    Here is an example.

    Comment

    • littlemaster
      New Member
      • Apr 2010
      • 25

      #3
      It is sending mail properly with text message. It is not attach the file. In that program no syntax specified to attach mail.I have already tried this example. Any other simplest example ???

      Comment

      • improvcornartist
        Recognized Expert Contributor
        • May 2007
        • 303

        #4
        There is a section near the bottom for adding attachments.
        Code:
        filename = "/tmp/test.txt"
        # Read a file and encode it into base64 format
        filecontent = File.read(filename)
        encodedcontent = [filecontent].pack("m")   # base64
        
        marker = "AUNIQUEMARKER"
        
        ...
        
        # Define the attachment section
        part3 =<<EOF
        Content-Type: multipart/mixed; name=\"#{filename}\"
        Content-Transfer-Encoding:base64
        Content-Disposition: attachment; filename="#{filename}"
        
        #{encodedcontent}
        --#{marker}--
        EOF
        You then need to add part3 to your email.

        Comment

        • littlemaster
          New Member
          • Apr 2010
          • 25

          #5
          Could you able to understand my question?

          In sendmail function, there is no option to attach file. U can configure the file attachment details properly. How will you embed this ?

          Comment

          • improvcornartist
            Recognized Expert Contributor
            • May 2007
            • 303

            #6
            The attachment is part of the email. In sendmail, you send the complete email which already has attachments added.

            Comment

            Working...