【基础扎实】Python操作邮件收发

Win32篇章

Outlook邮件发送

import win32com.client as win32
import datetime, os

addresslist = ['xxx@xy.com']  # 收件人邮箱列表

class send_email():
    def outlook(self):
        for address in addresslist:
            outlook = win32.Dispatch(dispatch='outlook.application')
            mail = outlook.CreateItem(0)
            mail.To = addresslist[0]  # 收件人
            mail.Subject = str(datetime.datetime.now())[0:19] + 'XXX测试'  # 邮件主题
            # mail.Body = 'content'  # 邮件正文中的内容
            mail.BodyFormat = 2
            mail.HtmlBody = "<h1>你好, 测试文件</h1><div><img src='Test.png'/></div>"  # Html格式, 展示图片
            mail.Attachments.Add(r'C:Users13697Desktopdataxxx.xlsx')
            mail.Attachments.Add(r'C:Users13697DesktopdataTest.png')  # 页面图片路径中不能有中文
            mail.Display()  # 携带图片时候需要设置
            mail.Send()  # 发送

if __name__ == '__main__':
    send_email().outlook()
    print("send email ok!!!!!!!!!!")

获取Outlook附件

# 下载附件
today = datetime.datetime.today().date()  # 今日日期
msgSubject = 'xxx表'  # 某特定邮件标题

def get_outlook_att():
    outlook = win32.Dispatch(dispatch='outlook.application').GetNamespace("MAPI")
    inbox = outlook.GetDefaultFolder(6)
    
    messages = inbox.Items
    message = inbox.Items.GetFirst()  # GetLast(), GetNext()
    
    # 逐条处理邮件信息
    for msg in messages:
        try:
            if (str(message.Subject) == msgSubject) and (str(message.ReceivedTime)[:10] == str(today)):  # 下载今日接收&特定邮件标题
                print(message.Subject, message.ReceivedTime)
                attachments = message.Attachments
                attachment = attachments.Item(1)  # 获取第一个附件, 若是有多个, 需要再创建子循环: for att in range(1, len([x for x in attachments])+1)

                path = os.path.join(os.getcwd(), attachment.FileName)  # 下载至当前文件夹
                print(path)
                attachment.SaveASFile(path)
            else:
                pass
        except:
            pass
        
        message = messages.GetNext()  # 若是前面的是GetLast(), 这里会得到n+1个,重复的Last文件
        

if __name__ == '__main__':
    get_outlook_att()

参考资源

1.MicroSoft Doc -- 另外几个博客论坛的问答对话给了很多指示,忘了是啥链接就没贴,谢过前辈
2.利用Outlook配置自动下载附件 -- 这个方法也可

原文地址:https://www.cnblogs.com/cheney97/p/15001413.html