python实现foxmail发送邮件

       考虑到项目中每周五下班前都需要发送项目周报,项目进展数据可用从系统中获取,但是需要手工去填写邮件数据并进行发送也是一个浪费时间的事情,最重要的是会经常忘记发邮件。

        所以考虑实现自动发送项目周报,具体思路如下:

1.获取项目进展数据,从系统接口获取(省略)

2.python自动发送邮件

# coding=utf-8
from exchangelib import Credentials, Account, DELEGATE, Configuration, NTLM, Message, Mailbox, HTMLBody, FileAttachment
from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter
import urllib3

urllib3.disable_warnings()  # 取消SSL安全连接警告
BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter


def SendEmail(to, subject):
    """
    邮件发送
    :param to: 收件人
    :param subject: 邮件主题
    :return: 无
    """
    
    cred = Credentials('first\\用户名', 'password')  # 配置邮箱域账号、密码
    config = Configuration(
        server='mail.fxxx.com',
        credentials=cred,
        auth_type=NTLM
        )
    account = Account(
        primary_smtp_address='email.com',
        config=config,
        autodiscover=False,
        access_type=DELEGATE
        )
    print('你的邮箱已连接')

    # 邮件正文
    case = 80
    bug = 70
    image_file = '1.jpg'
    # 正文显示图片,可以将图像链接到HTML中
    with open(image_file, 'rb') as f:
        my_image = FileAttachment(name=image_file, content=f.read(), is_inline=True, content_id=image_file)
    body = '''<html>   
             <body>各位领导,同事,大家好: <br>
             <p>&nbsp&nbsp以下是本项目的测试简报,具体情况介绍如下:</p>
             1.测试用例执行数:%s<br>
             2.发现bug数量:%s<br>
             <br><img src="cid:%s"><br>
              </body>
               </html>''' % (case, bug, image_file)
    m = Message(
        account=account,
        subject=subject,
        body=HTMLBody(body),
        to_recipients=[Mailbox(email_address=to)]
    )

    # 上传附件
    file = r'C:\Users\duan\Desktop\2.pdf'
    with open(file, 'rb') as f:
        my_file = FileAttachment(name=file, content=f.read(), is_inline=False, content_id=file)
    m.attach(my_file)
    m.attach(my_image)
    m.send()
    print('邮箱已发送,请查收')



if __name__ == '__main__':
    SendEmail("email.com", "测试简报")

测试了一下,邮件发送成功后的样子

猜你喜欢

转载自blog.csdn.net/weixin_46361114/article/details/114497126