3

I'm making a Python Webhook to intercept FormStack data (sent in JSON format) which includes a file attachment url. I need to download the file attachment and the send it as a mail attachment through SendGrid API.

The SendGrid API requires filename and path as arguments to attach the file. message.add_attachment('stuff.txt', './stuff.txt')

I referred to urllib2 but I can't seem to find out a way to download file with any extension and get its location for uploading it further.

Harvey
  • 184
  • 1
  • 3
  • 15
  • So you need to download the file and attach it to an email? _What_ do you mean by _uploading it further_? – albert Feb 13 '16 at 09:11
  • Yep you understood it right. I need to attach it to an email. At least for now. – Harvey Feb 13 '16 at 09:13
  • You might take a look at this [answer](http://stackoverflow.com/a/22776/3991125) and save the read/downloaded file to a dedicated directory. Then you could use `os.path`'s functions or, since you know the directory/path a priori, even simpler string methods to separete filename and extension if needed and add it to the message. – albert Feb 13 '16 at 09:14

2 Answers2

0

Download it to a temporary file, e.g. using tempfile.
Key lines (simplified):

s = urllib2.urlopen(url).read()
tf = tempfile.NamedTemporaryFile(suffix='.txt', delete=False)  # OPT: dir=mytempdir
tf.write(s)
path = tf.name
tf.close()
kxr
  • 4,841
  • 1
  • 49
  • 32
0

Complete elaborated code that worked for me

import tempfile
import sendgrid

url = 'your download url'
file_name = file_name = url.split('/')[-1]
t_file = tempfile.NamedTemporaryFile(suffix=file_name, dir="/mydir_loc" delete=False) 

# Default directory is '/tmp' but you can explicitly mention a directory also  
# Set Delete to True if you want the file to be deleted after closing

data = urllib2.urlopen(url).read()
t_file.write(data)

# SendGrid API calls
message.add_attachment(file_name, tf.name)
status, msg = sg.send(message)

t_file.close()
Harvey
  • 184
  • 1
  • 3
  • 15