我有格式的元组(名称,电子邮件,已售出的单位)。我想生成一个HTML表,按名称分组,然后通过Outlook将该表嵌入到电子邮件中。
我的代码:
from itertools import groupby
from operator import itemgetter
import win32com.client
mytuple = [('Andrew','Andrew@gmail.com','20'),('Jim',"Jim@gmail.com",'12'),("Sarah","Sarah@gmail.com",'43'),("Jim","Jim@gmail.com",'15'),("Andrew","Andrew@gmail.com",'56')]
mytuple = sorted(mytuple)
FULL_HTML = []
for name, rows in groupby(mytuple, itemgetter(0)):
table = []
for name, value2 in rows:
table.append(
"<tr><td>{}</td><td>{}</td></tr>".format(
name, value2 ))
html_code = "<html><table>" + str(table) + "</table></html>"
olMailItem = 0x0
obj = win32com.client.Dispatch("Outlook.Application")
newMail = obj.CreateItem(olMailItem)
newMail.Subject = "This is the subject"
newMail.HTMLBody = html_code
newMail.To = "sampleemail@gmail.com"
newMail.Display()
期望的输出:
这将打开3封电子邮件,其中包含HTML代码。
电子邮件1:
<html>
<table>
<tr><td>Andrew</td><td>20</td><td></tr>
<tr><td>Andrew</td><td>56</td><td></tr>
</table>
</html>
电子邮件2:
<html>
<table>
<tr><td>Jim</td><td>12</td><td></tr>
<tr><td>Jim</td><td>15</td><td></tr>
</table>
</html>
电子邮件3:
<html>
<table>
<tr><td>Sarah</td><td>43</td><td></tr>
</table>
</html>
答案 0 :(得分:1)
这是你的问题:
for name, value2 in rows:
table.append(
"<tr><td>{}</td><td>{}</td></tr>".format(
name, value2 ))
将其更改为:
for n, e, id in rows:
table.append(
"<tr><td>{}</td><td>{}</td></tr>".format(
n, id ))
html_code = "<html><table>" + ''.join(table) + "</table></html>"
groupby函数仍然返回3元组。