Search code examples
pythonmicrosoft-graph-apiemail-attachments

How to download a file from an email and save it in C:\


I have the attachment info ("contentBytes": "iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAArlBMVEX...etc) (from a graph API request) and below is the code I'm using to convert it, and this is a success, but I need to save it to the C drive. Is there something extra to add to this or should I be going in a different direction?

import base64
imgdata = base64.b64decode(contentBytes)
filename = "sample.png"
with open(filename, 'wb') as f:
    f.write(imgdata)

Solution

  • If you want to change the save location just write the path along with the filename By the way, the code isn't working properly because contentBytes isn't defined so it'll give an error

    import base64
    
    imgdata = base64.b64decode(contentBytes)
    
    filename = "C:/users/user/path/to/save/file/to/sample.png"
    
    with open(filename, 'wb') as f:
       f.write(imgdata)
    

    This should save the file to the chosen directory