0

I used this code to store attachment xlsx files from a specific address email in Outlook, but now I would like to store these files in a database in SQL Server, not in a folder in my laptop? Do you have any idea about how to store these files directly in a database? Many thanks.

outputDir = r"C:\Users\CMhalla\Desktop\Hellmann_attachment"
i=0
for m in messages:
    if m.SenderEmailAddress == 'adress@outlook.com':
       body_content=m.Body
       for attachment in m.Attachments:
           i=i+1
           attachment.SaveAsFile(os.path.join(outputDir,attachment.FileName + str(i)+'.xlsx'))
Dale K
  • 25,246
  • 15
  • 42
  • 71
Chaa MH
  • 73
  • 7
  • This code is able to download to me all the attachment files (excel files) more then 100 file send by a specific address email, but I would like to store these files automatically in a data base without downloading them and put them in a folder in my desktop. – Chaa MH Jul 01 '21 at 14:26
  • This is not an Outlook question - once you have a file, how your store it in a DB is up to the API you are using. Outlook has nothing to do with that. – Dmitry Streblechenko Jul 01 '21 at 15:35

2 Answers2

0

The Oultook object model doesn't provide any property or method for saving attachments to DBs directly. You need to save the file on the disk first and then add it to the Db in any convenient way.

However, you may be interested in reading the bytes array of the attached item in Outlook. In that case you may write the byte array directly to the Db without touching the file system which may slow down the overall performance. The PR_ATTACH_DATA_BIN property contains binary attachment data typically accessed through the Object Linking and Embedding (OLE) IStream interface. This property holds the attachment when the value of the PR_ATTACH_METHOD property is ATTACH_BY_VALUE, which is the usual attachment method and the only one required to be supported.

The Outlook object model cannot retrieve large binary or string MAPI properties using PropertyAccessor.GetProperty. On the low level (Extended MAPI) the IMAPIProp::GetProps() method does not work for the large PT_STING8 / PT_UNICODE / PT_BINARY properties. They must be opened as IStream in the following way - IMAPIProp::OpenProperty(PR_ATTACH_DATA_BIN, IIS_IStream, ...). See PropertyAccessor.GetProperty( PR_ATTACH_DATA_BIN) fails for outlook attachment for more information.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
0

You can use Microsoft Power Automate to save the attachment in the drive and then upload the file to the Python environment.

  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 17 '22 at 00:19