'send attachment that is created in code via python

 data1=[218031839]
    data3=[204394266]
    
    # dataframe Name and Age columns
    df = pd.DataFrame(data1)
    #Adding the header
    df.set_axis(["Bans"],axis=1,inplace=True)
    df.head()
    
    # Create a Pandas Excel writer using XlsxWriter as the engine.
    writer = pd.ExcelWriter(r'C:\user\file.xlsx', engine='xlsxwriter')
    
    # Convert the dataframe to an XlsxWriter Excel object.
    df.to_excel(writer, sheet_name='Sheet1',startrow=1,index=False)
    
    
    # Close the Pandas Excel writer and output the Excel file.
    writer.save()
    reader = pd.read_excel(r'file.xlsx')
    print(reader)
    #ss_body = ss_df1.to_html(index=False)
    outlook = win32.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.To = '[email protected]';
    '
    mail.Subject = 'Report'
    mail.Body = 'testing purpose now ..Pl ignore the mail'
    mail.attachmensts.add(r'C:\user\file.xlsx')
    mail.send()

    #remove the file
    Os.remove(r'C:\user\file.xlsx')

getting the below:

os.remove(r'C:\Users\file.xlsx'')

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:

I successfully sent the mail from Python and next step is to remove the excel from the location where it is saved on my pc. But getting the above error and can anyone look into this.



Solution 1:[1]

You need to use the Attachments.Add method to attach a file. The source of the attachment can be a file (represented by the full file system path with a file name) or an Outlook item that constitutes the attachment. The file name is not enough. For example, the following VBA macro shows how to use the method (the Outlook object model is common for all kind of programming languages):

Sub AddAttachment() 
 Dim myItem As Outlook.MailItem 
 Dim myAttachments As Outlook.Attachments 
 
 Set myItem = Application.CreateItem(olMailItem) 
 Set myAttachments = myItem.Attachments 
 myAttachments.Add "D:\Test.xlsx", _ 
 olByValue, 1, "Test" 
 myItem.Display 
End Sub

Also there is no need to call the Display method right before Send.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1