python实现发送邮件和企业微信功能

import platform
import smtplib
from email.header import Header
from email.mime.text import MIMEText
import requests


def sendMail(subject, body, receiver_address, oncopy_address):
    """
    windows和linux环境都支持发送邮件
    :param subject: 邮件主题
    :param body: 内容
    :param receiver_address: 收件人,';' 分隔
    :param oncopy_address: 抄送人,';' 分隔
    :return:
    """
    subject = subject.replace('<font color=\"info\">', '').replace('<font color=\"warning\">', '').replace('</font>', '').replace('#', '').replace('*', '')
    body = body.replace('<font color=\"comment\">', '').replace('<font color=\"warning\">', '').replace('</font>','').replace('>', '').replace('"', "").replace("'", "").replace("`", "").replace("**", "")
    HTMLBody = """
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mail Test</title>

<style>
body,html,div,ul,li,button,p,pre,h1,h2,h3,h4,h5,h6 {
  margin: 0;
  padding: 0;
}

pre { // 兼容多个浏览器
    white-space: pre-wrap;
    white-space: -moz-pre-wrap;
    white-space: -pre-wrap;
    white-space: -o-pre-wrap;
    *word-wrap: break-word;
    *white-space : normal ;
}
body,html {
  background: #fff;
  line-height: 1.8;
}
h1,h2,h3,h4,h5,h6 {
  line-height: 1.8;
}
h2.email-title {
  font-size: 26px;
  font-weight: 100;
  margin-bottom: 15px;
  color: #FF5151;
}

</style>
</head>
<body>
<h2 class="email-title">
##xxx程序执行信息,请相关同事注意。##
</h2>

<pre>
%s
</pre>

</body>

</html>""" % (body.strip())
    sender = 'xxxx.com'    # 发送者
    smtpserver = 'xxxxxx.com'
    smtpserver_port = 25
    msg = MIMEText(HTMLBody, _subtype='html', _charset='utf-8')
    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = Header(sender, 'utf-8')  # 发送者
    msg['To'] = receiver_address  # 收件人,将列表转换为字符串以;隔开
    msg['Cc'] = oncopy_address  # 抄送人,将列表转换为字符串以;隔开
    smtp = ''
    try:
        smtp = smtplib.SMTP(smtpserver, smtpserver_port)
        smtp.connect(smtpserver, smtpserver_port)
        # smtp.login(username,password)
        smtp.starttls()
        smtp.sendmail(sender, receiver_address.split(";") + oncopy_address.split(";"), msg.as_string())
        print("sendmail finshed!")
    except Exception as err:
        print("send mail failed")
    finally:
        smtp.quit()


# 需按照pypiwin32包,命令为:pip install pypiwin32
import win32com.client as win32
def send_mail(subject, body, receiver_address, oncopy_address):
    """
    Windows环境下发送邮件
    :param subject:
    :param body:
    :param receiver_address:
    :param oncopy_address:
    :return:
    """
    subject = subject.replace('<font color=\"info\">', '').replace('<font color=\"warning\">', '').replace('</font>', '').replace('#', '').replace('*', '')
    body = body.replace('<font color=\"comment\">', '').replace('<font color=\"warning\">', '').replace('</font>','').replace('>', '').replace('"', "").replace("'", "").replace("`", "").replace("**", "")
    # 调用Outlook application
    outlook = win32.Dispatch('Outlook.Application')

    mail_item = outlook.CreateItem(0)  # 0: olMailItem

    mail_item.To = receiver_address  # 收件人
    mail_item.CC = oncopy_address  # 抄送人
    mail_item.Subject = subject  # 主题
    mail_item.BodyFormat = 2  # 2: Html format
    # 邮件body
    mail_item.HTMLBody = """
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mail Test</title>

<style>
body,html,div,ul,li,button,p,pre,h1,h2,h3,h4,h5,h6 {
  margin: 0;
  padding: 0;
}

pre { // 兼容多个浏览器
    white-space: pre-wrap;
    white-space: -moz-pre-wrap;
    white-space: -pre-wrap;
    white-space: -o-pre-wrap;
    *word-wrap: break-word;
    *white-space : normal ;
}
body,html {
  background: #fff;
  line-height: 1.8;
}
h1,h2,h3,h4,h5,h6 {
  line-height: 1.8;
}
h2.email-title {
  font-size: 26px;
  font-weight: 100;
  margin-bottom: 15px;
  color: #FF5151;
}

</style>
</head>
<body>
<h2 class="email-title">
##xxx程序执行信息,请相关同事注意。##
</h2>

<pre>
%s
</pre>

</body>

</html>
"""%(body.strip())

    # 添加附件
    # mail_item.Attachments.Add(xlfile)
    mail_item.Send()


def send_wechat(subject, body, url):
    """
    发送企业微信报警
    文本类型:文本内容,最长不超过2048个字节,必须是utf8编码
    markdown类型:markdown内容,最长不超过4096个字节,必须是utf8编码
    :param subject:主题
    :param body:内容
    :param url:企业微信机器人id
    :return:
    """
    content="""
{subject}
{body}
    """.format(subject=subject,body=body)
    content = content.encode('utf-8')[:4096].decode('utf-8')
    system = platform.system()
    headers = {
        "accept": "*/*",
        "Content-Type": "application/json"
    }
    data = {
        "appName": "wework",
        "format": "json",
        "param": {
            "addressList": [url],
            "appName": "wework",
            "attach": [],
            "businessSubject": "异常告警",
            "contentBody": {
                "content": content,
                "contentType": "markdown",
                "title": ""
            },
            "type": "wework"
        },
        "sign": "",
        "source": "",
        "timestamp": "",
        "version": ""
    }
    # windows本地跑代码
    if system == 'Windows':
        print("Windows跳过发微信步骤")
        ###上线需要关闭
        # url = 'http://xxxxxxx'
        # r = requests.post(url, headers=headers, json=data, verify=False)
        # print(r.text)
    else:
        print("发送企业微信")
        url = 'http://xxxxxxx'
        r = requests.post(url, headers=headers, json=data, verify=False)
        print(r.text)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值