我是python的新手,并尝试构建一个python脚本,它将发送一个包含文件路径的电子邮件。我得到了一个示例代码,用于在python中发送电子邮件,在使用pywin32和psutil模块进行几次打嗝之后工作正常。收到电子邮件,但我很难在电子邮件正文中包含一个文件路径,该文件路径是在相同的代码中提取的。我通过评论粘贴下面的代码。你能帮助我解决这个问题吗?
编辑:我遇到了奇怪的问题。我一直在努力,这些是我遇到的问题:
如果我将python代码移动到C:\ tools并在cmd提示符下手动运行,我看到DLL加载失败错误:
C:\ tools> python sendemail.py C:\ Users \<> \ Desktop \ Exp \ xxx.txt Traceback(最近一次调用最后一次): 文件“sendemail.py”,第1行,in 将win32com.client导入为win32 文件“C:\ Python27 \ lib \ site-packages \ win32com__init __。py”,第5行,in import win32api,sys,os ImportError:DLL加载失败:%1不是有效的Win32应用程序。
我在win32上使用Python 2.7.13 [MSC v.1500 32位(Intel)]。 Windows 10 OS 64b
import win32com.client as win32
import psutil
import os
import subprocess
import sys
# Drafting and sending email notification to senders.
def send_notification(path):
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'jdoe@email.com'
mail.Subject = 'File Location'
mail.body = 'Hi User,\nThis is the file location\nFile=%s;' %path
mail.send
# Open Outlook.exe.
def open_outlook():
try:
subprocess.call(['C:\Program Files (x86)\Microsoft Office\root\Office16\Outlook.exe'])
os.system("C:\Program Files (x86)\Microsoft Office\root\Office16\Outlook.exe");
except:
print("Outlook didn't open successfully")
##############################################################
# Extract path of file (using regedit to trigger Python script)
###############################################################
#Filepath gives me the path where file is located: C:\Users\<>\Desktop\Exp
filepath = sys.argv[-1]
#split filepath to move one directory up to give me C:\Users\<>\Desktop
spath = filepath.split('\\')[:-1]
#Check if user is running script on the correct file
file=filepath.split("\\")[-1]
if file != 'xxx.txt':
with open("ErrorMessage.txt","w+") as output:
output.write("INPUT ERROR:Please run script on xxx.txt\n")
os.startfile("ErrorMessage.txt")
sys.exit()
#Final path which I need to include in my email body
path = '\\'.join(spath)
#Checking if outlook is already opened. If not, open Outlook.exe and send email
for item in psutil.pids():
p = psutil.Process(item)
if p.name() == "OUTLOOK.EXE":
flag = 1
break
else:
flag = 0
if (flag == 1):
send_notification(path)
else:
open_outlook()
send_notification(path)