Mass Importing Attachments

Importing an Attachment into Salesforce with SQLForce can be done with a short script, but what about importing a lot of Attachments at once? This article will show you how to import many Attachments at one time.

The Basics

The script to import a single Attachment into Salesforce is below:

import SQLForce
from SQLForce import AttachmentWriter

session = SQLForce.Session(“MyConnectionParameters”)

salesforceParentId = ‘001A0000014fia3’  # The unique id of the Salesforce object to own the attachment
filename = “/mydir/salesforcecast.docx”   # The file to add as an attachment.

attachmentId = AttachmentWriter( session, salesforceParentId, filename )

That’s it — the part is determining the filenames of the Attachments and their associated parent Ids.

A More Complex Example

Suppose we have a TAB delimited spreadsheet where:

  • Column 1 contains the Salesforce Id of the Attachment’s parent record.
  • Column 2 contains the name of the file.
  • Column 3 contains a description which should be associated with the Attachment.

The following script will import Attachments from the spreadsheet — the most complicated functionality beyond the example above is the processing of the spreadsheet:

import SQLForce
import csv
from SQLForce import AttachmentWriter

##
## Store a reference to each attachment to process in an AttachmentRef instance
##
class AttachmentRef:

def __init__(self, parentId, filename, description=None ):

self.parentId = parentId
self.filename = filename
self.description = description

”’
Read the list of files to attach from a spreadsheet where:
+ Column 1 contains the Salesforce ID of the record to own the attachment.
+ Column 2 is the name of a file.
+ Column 3 is a description to store with the attachment.

Return a list of AttachmentRefs
”’
def loadAttachmentRefsFromFile( filename ):

attachmentRefs = [] with open( filename, ‘r’) as fd:

reader = csv.reader(fd, delimiter=”\t”)
for row in reader:
attachmentRefs.append( AttachmentRef( row[0], row[1], row[2]))

return attachmentRefs

”’
Load a list of attachments into Salesforce.

Return a list of attachments for each recorded uploaded to Salesforce.
”’
def attachFilesToSalesforce( session, attachmentRefs ):

attachmentIds = [] for ref in attachmentRefs:

attachmentId = AttachmentWriter.attachFile(session, ref.parentId, ref.filename, description=ref.description)
attachmentIds.append( attachmentId )
print( ref.parentId + ” : ” + ref.filename + ” : attached as ” + attachmentId)

return attachmentIds

”’
Here’s the main() program
”’
attachmentRefs = loadAttachmentRefsFromFile(“ImportAttachments.txt”)

session = SQLForce.Session(‘SQLForceExample’)

attachmentIds = attachFilesToSalesforce( session, attachmentRefs )

session.delete(‘Attachment’, attachmentIds)