Skip to content

Sending multiple file attachments

Absalon Castañon Avila edited this page Jun 8, 2018 · 2 revisions

In order to send multiple file attachments you (probably) have to use MessageBuilder, because (as far as I know) it is not possible to define Ruby Hash which has multiple values with the same key (attachment).

Example:

    mg_client = Mailgun::Client.new 'key-YOUR_MG_KEY'
    file = Tempfile.new('name') # more at http://ruby-doc.org/stdlib-1.9.3/libdoc/tempfile/rdoc/Tempfile.html
    file.write('some file content')
    file.rewind
    mb = Mailgun::MessageBuilder.new
    mb.set_from_address("test@test.com")
    mb.add_recipient(:to, "test2@test.com")
    mb.set_subject("Test msg")
    mb.set_text_body("Look at attachments")
    mb.set_html_body("<html><body><h3>Look at attachments</h3></body></html>")
    mb.add_attachment(file.path, 'att1.txt') # first arg is path to the file, second is filename as an attachment
    mb.add_attachment(file.path, 'att2.txt')
    mb.add_attachment(file.path, 'att3.txt')
    mg_client.send_message 'sandboxYOURSANDBOXHASH.mailgun.org', mb
    file.unlink

You may also use regular File, but using Tempfile is another undocumented option. In order to use regular file set first add_attachment argument to the system file path.

There is a solution using hashes

    data[:attachment]=[]
    data[:attachment] << File.new("path/to/file.ext")
    data[:attachment] << File.new("path/to/another_file.ext")

It also works with inline attachments

    data[:inline]=[]
    data[:inline] << File.new("path/to/file.ext")
    data[:attachment] << File.new("path/to/another_file.ext")