您当前的位置: 首页 >  Python

每日出拳老爷子

暂无认证

  • 4浏览

    0关注

    135博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Python:如何方便地用Python发outlook邮件

每日出拳老爷子 发布时间:2021-08-19 10:22:10 ,浏览量:4

背景

单位有自动定时邮件需求,而Windows自带的定时任务不好用,不灵活,于是自己用Python写。

重点库
  1. outlook邮件库:exchangelib
  2. 定时跑批的库:schedule
完整源码

https://gitee.com/sheep431/Automail

实现方法
  1. 造一个发送邮件的通用函数exchangelib
  2. 每一个邮件任务单独形成一个函数,调用exchangelib发送邮件,对发送配置项进行配置。
  3. 造一个运行用py文件,用schdule实现轮询调用各邮件任务函数。
  4. 对于需要月初月末等特定日期发送的邮件,为了方便实现添加了计算月末日期和前一个业务日期的函数。
诀窍
  1. 比较麻烦的是HTML富文本形式的邮件如何正确配置内容。有一个很方便的方法就是发一个相同内容的邮件到网络邮箱,然后直接复制相应的HTML到自己的代码中作为发送的content部分。
  2. 没有条件做1的话,直接Outlook桌面程序右键选择查看源文件也可以参考。
  3. Outlook的嵌入img src不能直接引用本地文件,而是必须将img作为attachment放到相应邮件中后,以cid(outlook中的资源名称引用),其实挺合乎逻辑的。
def send_no_cellphone_notice():
    from Code.sendMail_exchange import exg_send_mail
    to_address = "xyy@cn.test.jp"
    cc_address = "wk@cn.test.jp"
    subject = "No cellphone notice"
    attachments = ["resource/img/no_phone.PNG"]
    content = '''
    
    '''
    auth = "wk@cn.test.jp"

    exg_send_mail(to_address,cc_address,subject,content,attachments,auth)

上述代码其实在发送邮件部分我自己进行了封装,exg_send_mail是我写的通用函数,直接将png文件同时放在attatchment和正文中即可嵌入。

通用函数内容如下,更多详细内容可以参考我的github资源

def exg_send_mail(mail_addr, cc_addr, subject, htmlBody, attchmentList,auth="Robot"):
    from exchangelib import DELEGATE, Account, Credentials, Message, Mailbox, HTMLBody, Configuration, NTLM, \
        FileAttachment
    from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter
    import urllib3
    import datetime

    BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter
    urllib3.disable_warnings()

    cred = Credentials(r'username', 'pwd')

    config = Configuration(server='exgmail.cn.test.jp', credentials=cred, auth_type=NTLM)
    a = Account(
        primary_smtp_address="robot@tmp.cn.test.jp", config=config, autodiscover=False, access_type=DELEGATE
    )

    commen_message = '''
这是一封系统自动生成的邮件,请勿直接回复!
This mail is from:%s
'''%auth to_list = [] for x in mail_addr.split(';'): if x: to_list.append(Mailbox(email_address=x)) cc_list = [] for x in cc_addr.split(';'): if x: cc_list.append(Mailbox(email_address=x)) m = Message( account=a, folder=a.sent, subject=subject, body=HTMLBody(commen_message+htmlBody), to_recipients=to_list, cc_recipients=cc_list ) for file in attchmentList: print(file.split('/')[-1]) with open(file, 'rb') as f: content = f.read() new_attach = FileAttachment(name=file.split('/')[-1], content=content) m.attach(new_attach) m.send_and_save()
关注
打赏
1657016083
查看更多评论
立即登录/注册

微信扫码登录

0.1849s