美文网首页云端配置杂记
python 实现提取Confluence网页内容发送邮件

python 实现提取Confluence网页内容发送邮件

作者: 国服最坑开发 | 来源:发表于2021-11-10 09:07 被阅读0次
    邮件自动化

    0x00 背景

    每天需要对confluence相应内容人工发送邮件处理, 本文记述一种 Python 代码实现方式

    0x01 代码

    import requests
    import json
    import smtplib
    import time
    
    from email.mime.text import MIMEText
    from email.header import Header
    from email.utils import parseaddr
    from email.utils import formataddr
    
    mail_host = 'smtp.mydomain.com'
    mail_user = 'xxx'
    mail_pass = 'xxx'
    
    sender = '邮件服务<robot@gmail.com>'
    receivers = [
        '"小 王" <xiaowang@gmail.com>',
        '"小 炸" <xiaoza@gmail.com>'
    ]
    
    
    today = time.strftime("%Y-%m-%d")
    
    
    def format_address(address):
        # 解析邮件地址,以保证邮有别名可以显示
        name, mail = parseaddr(address)
        # 防止中文问题,进行转码处理,并格式化为str返回
        return formataddr((Header(name, charset="utf-8").encode(), mail))
    
    
    def send_mail(body):
        str_to = list()
    
        for a in receivers:
            str_to.append(format_address(a))
    
        message = MIMEText(body, 'html', 'utf-8')
        message['From'] = format_address(sender)
        message['To'] = ','.join(str_to)
        message['Subject'] = Header('每日推送[ ' + today + ' ]', 'utf-8')
    
        try:
            mail = smtplib.SMTP_SSL(host= mail_host)
            mail.connect(mail_host, 465)
            mail.login(mail_user, mail_pass)
            mail.sendmail(sender, receivers, message.as_string())
            print("Done")
        except smtplib.SMTPException as e:
            print("Error : failed" + e)
    
    
    if __name__ == '__main__':
        try:
            conf_domain = 'conf.domain.com'
            url = 'https://%s:%s@%s/rest/api/content?spaceKey=NEWS&title=%s&expand=body.view' % (mail_user, mail_pass, conf_domain, today)
    
            data = requests.get(url).text
            j = json.loads(data)
    
            viewContent = j['results'][0]['body']['view']['value']
            html = head + viewContent + tail
            send_mail(html)
        except Exception as e:
            print("Something Error:" + e)
    
    

    0x02 Done

    相关文章

      网友评论

        本文标题:python 实现提取Confluence网页内容发送邮件

        本文链接:https://www.haomeiwen.com/subject/bssbzltx.html