【Python】自动化办公-outlook邮箱处理(获取邮箱附件)/通过下载链接自动下载

outlook邮箱处理-获取邮箱附件

#先引入outlook
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
#花了些时间明白了怎么找邮件folder的名字
#我用下面的三行
root_folder = outlook.Folders.Item(1)
for folder in root_folder.Folders:
	print (folder.Name)

#这样就能得到一个名字表
#如果还有sub folder,假设上一级folder叫Inbox,这么改就行,继续加代码可以一级一级找#下去
root_folder = outlook.Folders.Item("Inbox").Folders.Item(1)

#我的主Folder是2号,下级Folder叫Boîte de réception
#不要问为什么叫test
test = outlook.Folders.Item(2).Folders.Item("Boîte de réception")
messages = test.Items
#有必要的话写个循环可以得到邮件标题和内容,我就不写了
#邮件标题
print("subject: ", message.Subject)
#邮件内容
print("content: ", message.body)
#邮件太多了,我以12小时为限
import datetime as dt
last12HourDateTime = dt.datetime.now() - dt.timedelta(hours = 12)
#to search mails
import os
message = messages.GetFirst()
subject = message.Subject
#附件存放路径
get_path='L:\xxxxxxx\outlook\FAMOO'
时区处理包裹
import pytz
utc=pytz.UTC
for m in messages:
	if "keyword" in m.Subject:
		attachments = message.Attachments
		#我找的邮件只有一个附件,所以下面是1.要是多个附件,得写个循环
		attachment = attachments.Item(1)
		attachment.SaveASFile(os.path.join(get_path,attachment.FileName))
		message = messages.GetNext()
	else:
		message = messages.GetNext()
	else:
		break #阻止无限找下去

此处为无注释代码。

# 无注释代码只有20多行
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
test = outlook.Folders.Item(2).Folders.Item("Boîte de réception")
messages = test.Items

import datetime as dt
last12HourDateTime = dt.datetime.now() - dt.timedelta(hours = 12)

import os
message = messages.GetFirst()
subject = message.Subject
get_path='L:\XXXXXXXXXX\outlook'

import pytz
utc=pytz.UTC
for m in messages:
	if message.ReceivedTime.replace(tzinfo=utc)>last12HourDateTime.replace(tzinfo=utc):
		if "keyword" in m.Subject:
			attachments = message.Attachments
			attachment = attachments.Item(1)
			attachment.SaveASFile(os.path.join(get_path,attachment.FileName))
			message = messages.GetNext()
		else:
			message = messages.GetNext()
	else:
		break

通过下载链接下载文件

#引用 requests文件

import requests
#下载地址
Download_addres='url'
#把下载地址发送给requests模块
f=requests.get(Download_addres)
#下载文件
with open("12.ipg","wb") as code:
     code.write(f.content)

你可能感兴趣的:(python,outlook,自动化)