Sample code for 30+ languages & platforms
Ruby Requires Chilkat v11.0.0+

Download a Gmail attachment by filename

See more GMail REST API Examples

Start with a Gmail message ID and the exact filename. Walk the root MIME payload and all nested parts. A unique matching part can contain base64url data directly or an attachment ID for a second request. Duplicate filenames are reported so the application can choose a particular MIME part.

The output path is chosen locally. The example saves to downloaded-attachment.bin and verifies the decoded size. Use an appropriate application-chosen filename or extension when adapting it. Gmail’s filename is treated as a matching value.

Authorize the application with https://www.googleapis.com/auth/gmail.readonly. The example reads the access token from gmail-token.json in a private working directory. Authorize a desktop application.

Google documentation

Chilkat Ruby Downloads

Ruby
require 'chilkat'

success = false

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

token = Chilkat::CkJsonObject.new()
success = token.LoadFile("gmail-token.json")
if (success != true)
    print "Could not read gmail-token.json from the private working directory." + "\n";
    exit
end

if ((token.JsonTypeOf("access_token") != 1) or (token.StringOfEquals("access_token","",true) == true))
    print "An OAuth access token is required." + "\n";
    exit
end

http = Chilkat::CkHttp.new()
http.put_RequireSslCertVerify(true)
http.put_AuthToken(token.stringOf("access_token"))
resp = Chilkat::CkHttpResponse.new()
reply = Chilkat::CkJsonObject.new()
messageId = "GMAIL_MESSAGE_ID"
filename = "attachment.pdf"
messageUrl = Chilkat::CkStringBuilder.new()
messageUrl.Append("https://gmail.googleapis.com/gmail/v1/users/me/messages/")
messageUrl.Append(http.urlEncode(messageId))
url = Chilkat::CkStringBuilder.new()
url.Append(messageUrl.getAsString())
url.Append("?format=full")
success = http.HttpNoBody("GET",url.getAsString(),resp)
if (resp.get_StatusCode() == 0)
    print "Gmail did not return an HTTP response." + "\n";
    exit
end

if ((success != true) or (resp.get_StatusCode() < 200) or (resp.get_StatusCode() >= 300))
    print "Gmail HTTP " + resp.get_StatusCode().to_s() + "\n";
    success = reply.Load(resp.bodyStr())
    if (success == true)
        print reply.stringOf("error.message") + "\n";
    end

    exit
end

success = reply.Load(resp.bodyStr())
if (success != true)
    print "Expected a Gmail JSON response." + "\n";
    exit
end

paths = Chilkat::CkStringTable.new()
success = paths.Append("payload")
if (success != true)
    print paths.lastErrorText() + "\n";
    exit
end

part = Chilkat::CkJsonObject.new()
selected = Chilkat::CkJsonObject.new()
childPath = Chilkat::CkStringBuilder.new()
matches = 0
p = 0
while (p < paths.get_Count())
    success = reply.ObjectOf2(paths.stringAt(p),part)
    if (success != true)
        print reply.lastErrorText() + "\n";
        exit
    end

    if (part.StringOfEquals("filename",filename,true) == true)
        matches = matches + 1
        success = part.MakeCopy(selected)
        if (success != true)
            print part.lastErrorText() + "\n";
            exit
        end

        print "Matching MIME part: " + paths.stringAt(p) + "\n";
    end

    j = 0
    while (j < part.SizeOfArray("parts"))
        childPath.SetString(paths.stringAt(p))
        childPath.Append(".parts[")
        childPath.AppendInt(j)
        childPath.Append("]")
        success = paths.Append(childPath.getAsString())
        if (success != true)
            print paths.lastErrorText() + "\n";
            exit
        end

        j = j + 1
    end
    p = p + 1
end
if (matches != 1)
    print "Expected one filename match. Matches: " + matches.to_s() + "\n";
    exit
end

body = Chilkat::CkJsonObject.new()
success = selected.ObjectOf2("body",body)
if (success != true)
    print selected.lastErrorText() + "\n";
    exit
end

if (body.JsonTypeOf("size") != 2)
    print "The selected part has no byte count." + "\n";
    exit
end

expectedSize = body.IntOf("size")
if (body.JsonTypeOf("attachmentId") == 1)
    url.SetString(messageUrl.getAsString())
    url.Append("/attachments/")
    url.Append(http.urlEncode(body.stringOf("attachmentId")))
    success = http.HttpNoBody("GET",url.getAsString(),resp)
    if (resp.get_StatusCode() == 0)
        print "Gmail did not return an HTTP response." + "\n";
        exit
    end

    if ((success != true) or (resp.get_StatusCode() < 200) or (resp.get_StatusCode() >= 300))
        print "Gmail HTTP " + resp.get_StatusCode().to_s() + "\n";
        success = reply.Load(resp.bodyStr())
        if (success == true)
            print reply.stringOf("error.message") + "\n";
        end

        exit
    end

    success = reply.Load(resp.bodyStr())
    if (success != true)
        print "Expected a Gmail JSON response." + "\n";
        exit
    end

    success = reply.MakeCopy(body)
    if (success != true)
        print reply.lastErrorText() + "\n";
        exit
    end

end

if (body.JsonTypeOf("data") != 1)
    print "The attachment response has no data." + "\n";
    exit
end

data = Chilkat::CkBinData.new()
if (body.StringOfEquals("data","",true) != true)
    success = body.BytesOf("data","base64url",data)
    if (success != true)
        print body.lastErrorText() + "\n";
        exit
    end

end

if (data.get_NumBytes() != expectedSize)
    print "Attachment size mismatch." + "\n";
    exit
end

success = data.WriteFile("downloaded-attachment.bin")
if (success != true)
    print "Could not save the attachment." + "\n";
    exit
end

print "Saved " + data.get_NumBytes().to_s() + " attachment bytes." + "\n";