[英]Python-based automation of Outlook using data from an Excel file for the mail body and adding a signature
我正在尝试编写 Python 脚本代码,其中我将每天向我的团队成员发送 email 通知。
有两个 excel 表,比如说abc.xlsx和def.xlsx 。
我已经有一个脚本可以更新这些文件并保存它们。 (这些文件abc和def被删除并使用相同的名称重新创建,但具有更新的信息。)
现在我的目标是将文件abc作为附件附加到邮件中,并将def.xlsx的内容添加到email 正文中。
我正在努力实现这一目标:
Hello All,
Please find the pending lists here as follows:
///The info from def.xlsx sheet comes here///
Thanks and regards!
/// my outlook signature///
这是我的代码:
import win32com.client as win32
import pandas as pd
# reading a file, which needs to be on mail body
df1 = pd.read_excel('def.xlsx')
html_table = df1.to_html(index=False)
outlook = win32.gencache.EnsureDispatch('Outlook.Application')
mail = outlook.CreateItem(0)
mail.To = 'mail@me.com'
mail.CC = 'mail@me.com'
mail.Subject = 'Test mail'
# path to signature should be User\AppData\Roaming\Microsoft\Signatures\signature.htm
pathToIMage = r'path_to_my_signature'
attachment = mail.Attachments.Add(pathToIMage)
attachment.PropertyAccessor.SetProperty("http://schemas.microsoft.com/mapi/proptag/0x3712001F", "MyId1")
# modify the mail body as per need
mail.Attachments.Add(Source="C:\..abc.xlsx")
body = "<p>Hi All, Please find the updates pending updates below:" + html_table + " <br>Thanks and regards <p> <figure><img src=""cid:MyId1""</figure>"
mail.HTMLBody = (body)
mail.Send()
挑战:
我只从堆栈溢出中复制了所有代码。 我做了一些研究,但没有得到预期的 output。
首先,您可以在设置HTMLBody
属性之前尝试设置BodyFormat属性。
其次,要获得添加到消息正文的签名,您需要在设置HTMLBody
属性之前调用Display
方法。
第三,在 Outlook 中不支持<figure>
元素,因为 Word 用作 email 编辑器并将其自己的业务规则应用于消息正文。
第四, HTMLBody
属性返回或设置一个表示消息正文的字符串,它期望获取或设置一个完整的格式良好的 HTML 文档。 尝试设置格式良好的 HTML 文档,然后设置属性。
我修改了它。 我仍在处理挑战 2。我将通过推荐的文档只 go 并将分享我的最终脚本。
import win32com.client as win32
import pandas as pd
import os
import codecs
df1 = pd.read_excel('mail_body.xlsx')
html_table = df1.to_html(index=False)
# below is the coding logic for signature
sig_files_path = 'AppData\Roaming\Microsoft\Signatures\\' + 'signature_file_name' + '_files\\'
sig_html_path = 'AppData\Roaming\Microsoft\Signatures\\' + 'signature_file_name' + '.htm'
signature_path = os.path.join((os.environ['USERPROFILE']), sig_files_path)
html_doc = os.path.join((os.environ['USERPROFILE']), sig_html_path)
html_doc = html_doc.replace('\\\\', '\\')
html_file = codecs.open(html_doc, 'r', 'utf-8', errors='ignore')
signature_code = html_file.read()
signature_code = signature_code.replace(('signature_file_name' + '_files/'), signature_path)
html_file.close()
outlook = win32.gencache.EnsureDispatch('Outlook.Application')
mail = outlook.CreateItem(0)
mail.To = 'mail@me.com'
mail.CC = 'mail@me.com'
mail.Subject = 'TEST EMAIL'
mail.Attachments.Add(Source=r"C:\..abc.xlsx")
# modify the mail body as per need
mail.BodyFormat = 2
body = "<p>Hi All, Please find the updates pending updates below:" + html_table + " <br>Thanks and regards <br><br>"
mail.Display()
mail.HTMLBody = body + signature_code
mail.Send()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.