如何使用 Python 将提取的电子邮件 ID 保存在 excel 工作表中,这也是连续的?


outlook = Dispatch("Outlook.Application")
mapi = outlook.GetNamespace("MAPI")
your_folder = mapi.Folders['email@outlook.com'].Folders['Blah']
blah_inbox = your_folder.Items
f = open("email_txt.csv", "w")
for message in blah_inbox:
if message.Class == 43:
if message.SenderEmailType == 'EX':
print(message.Sender.GetExchangeUser().PrimarySmtpAddress)
f.write(message.Sender.GetExchangeUser().PrimarySmtpAddress)
else:
print(message.SenderEmailAddress)

我打开了一个新的 fie 并将其写入 csv,但我得到以下结果。

user1@outlook.comuser2@outlook.comuser3@outook.com.....

但是,我需要结果

如下所示
user1@outlook.com
user2@outlook.com
user3@outlook.com

简单的解决方案如下

f = open("email_txt.csv", "w")
for message in blah_inbox:
if message.Class == 43:
if message.SenderEmailType == 'EX':
print(message.Sender.GetExchangeUser().PrimarySmtpAddress)
f.write(message.Sender.GetExchangeUser().PrimarySmtpAddress + 'n')
else:
print(message.SenderEmailAddress)

我在写入命令的末尾添加了"">

或者,因为我的全部意图是保存在带有某种标题的 CSV 中。以下是对我有用的东西。这是整个代码。

Todays_Mail = dt.datetime.now() - dt.timedelta(hours=24)
Todays_Mail = Todays_Mail.strftime('%m/%d/%Y %H:%M %p')
# Connect to Outlook inbox
outlook = Dispatch("Outlook.Application")
mapi = outlook.GetNamespace("MAPI")
your_folder = mapi.Folders['email'].Folders['Blah']
blah_inbox = your_folder.Items
blah_inbox = blah_inbox.Restrict("[ReceivedTime] >= '" + Todays_Mail + "'")
f = open("email.csv", "w")
f.write('Emails,Indexn')
index = 0
for message in blah_inbox:
if message.Class == 43:
if message.SenderEmailType == 'EX':
print(message.Sender.GetExchangeUser().PrimarySmtpAddress)
f.write(message.Sender.GetExchangeUser().PrimarySmtpAddress + ',' + str(index) + 'n')
index = index + 1

else:
print(message.SenderEmailAddress)
f.close()

上面将为您提供两列,一列带有标题电子邮件,第二列是标题索引的列。

最新更新