Send Outlook email with attachment to list of users in Excel with python

Viewed 5244

I am able to send email using outlook with below script, but if I try to send attachment it gives error.

File Name_Email.xlsx

NAME    EMAIL
Roy     Roy@gmail.com
Jack    Jack@gmail.com

Python Script

import win32com.client as win32
import pandas as pd

email_list = pd.read_excel(r'C:\Users\roy\Name_Email.xlsx')

names = email_list['NAME']
emails = email_list['EMAIL']

for i in range(len(emails)):
   name = names[i]
   email = emails[i]

   outlook = win32.Dispatch('outlook.application')
   mail = outlook.CreateItem(0)
   mail.To = email
   mail.Subject = 'Message subject'
   mail.Body = 'Hello ' + name
   attachment = "hosts.txt"
   mail.Attachments.Add(attachment)
   mail.Send()

error i am getting:

pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'Cannot find this file. Verify the path and file name are correct.', None, 0, -2147024894), None)

The file name is correct, and it's in same directory as the script.

Also I tried to change attachment = 'hosts.txt', but same error. Not sure what is missing.

2 Answers

try this

from win32com.client import Dispatch
import win32com
import pandas as pd

def mailprepare():
    num = range(0, 5)
    for kk in num:
        outlook = win32com.client.Dispatch("Outlook.Application")
        for accoun in outlook.Session.Accounts:
            if accoun.SmtpAddress == 'your@mail.com':
                newaccount = accoun
                break
        mail = outlook.CreateItem(0)
        mail._oleobj_.Invoke(*(64209, 0, 8, 0, newaccount))
        data = pd.ExcelFile('D:\\path.xlsx')
        sheet = data.parse('Sheet1')
        name = sheet['Names'][kk]
        mailto = sheet['Mails'][kk]

        att = 'D:\\yourattchment.txt'
        with open(att, 'r') as my_attch:
            myfile=my_attch.read()

        mail.To = mailto
        mail.Subject = 'Subject'
        mail.Body = 'mail body'+ name
        mail.Attachments.Add(att)

        mail.Display(True)
        mail.send

mailprepare()

You are simply assigning hosts.txt to a variable but Attachments.Add is looking for full file system path with a file name

To get the current directory use

Example

import os
print(os.getcwd() + "\hosts.txt")

Or

import os

attachment = "hosts.txt"
print(os.path.realpath(attachment))

FYI - I'm on 3.8 python

Related