Im trying to upload a folder full of emails to Salesforce, one email per case. The script does everything fine, but the emails it uploads are totally blank, and are 0 bytes.
Im pretty sure its something to do with the base64 encoding required to upload attachments, but I've tried everything to make it work.
I read this Uploading Attachments to Salesforce API via Beatbox, Python, which was helpful, but I cannot solve the problem.
Any help will be greatly appreciated.
Here is my code:
import wx
import email.parser
import os
import re
#import time
import beatbox
import base64
def browse(parent = None, message = 'Browse for the dealsheet folder'):
app = wx.App()
dialog = wx.DirDialog(None, "Choose a directory:",style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
if dialog.ShowModal() == wx.ID_OK:
return dialog.GetPath()
dialog.Destroy()
service = beatbox.PythonClient()
service.serverUrl = 'https://login.salesforce.com/services/Soap/u/20.0'
loginresponse = service.login('USERNAME', 'PASSWORD')
filespath = browse()
files = os.listdir(filespath)
global bodytext
global subject
global toAdd
global uploadfile
uploadfile = ''
for f in files:
with open(filespath + '\\' + f, 'rb') as emailfile:
message = email.message_from_file(emailfile)
uploadfile = base64.b64encode(emailfile.read())
subject = str(message.get('subject'))
toAdd = str(message.get('to'))
toAdd = re.findall(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}', toAdd)[0]
toAdd = toAdd[:-10] # cut the email bits
toAdd = toAdd.replace('.', ' ')
toAdd = toAdd.title()
print toAdd
for part in message.walk():
if part.get_content_type() == 'text/plain':
bodytext = part.get_payload()
bodytext = str(bodytext)
bodytext = unicode(bodytext, errors = 'replace')
# print bodytext
# LOG CASE
details = {'type': 'Case', 'Reason': 'SFDC Admin', 'Origin': 'Email', 'Status': 'Awaiting Analysis', 'Description': ''}
result = service.create(details)
print 'log result = ', result[0]['success']
#TRIAGE CASE
details_triage = {'type': 'Case', 'id': result[0]['id'], 'Case_Triaged__c': 'True'}
triage_result = service.update(details_triage)
print 'triage result = ', triage_result[0]['success']
url = 'https://naX.salesforce.com/{}'.format(triage_result[0]['id'])
print url
attachement_dict = {'type': 'Attachment', 'ParentId': triage_result[0]['id'], 'name': f, 'Body': uploadfile }
if result[0]['success'] == True:
res = service.create(attachement_dict)
print res