中小型企业通用自动化运维架构

中小型企业通用自动化运维架构

中小型企业通用自动化运维架构 学习 教程

python发送邮件

sendmail.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
import email.MIMEMultipart
import email.MIMEText
import email.MIMEBase
import sys
#from email.mime.application import MIMEApplication
#import os.path

def sendmail(f_from, f_to, f_cclist, alert_info, f_subject):
    From = f_from
    To = f_to
    #file_name = f_file_name

    server = smtplib.SMTP("smtp.xxxx.com.cn")
    server.login("xxxx","xxxx")

    #构造MIMEMultipart对象做为根容器
    main_msg = email.MIMEMultipart.MIMEMultipart()

    text_msg = email.MIMEText.MIMEText("您好。<br><br><br><br>"
                                       + alert_info.title() +
                                       "<br>任凤军 <br>"
                                       "xx技术股份有限公司 <br>"
                                       "手机: xx<br>"
                                       "座机:xxx<br>"
                                       "邮箱:[email protected]<br>"
                                       "地址:xxxx<br>"
                                       "邮编:130011<br>"
                                       "===================================<br>"
                                       "",‘HTML‘,‘utf-8‘)
    main_msg.attach(text_msg)

    #xlsxpart = MIMEApplication(open(file_name, ‘rb‘).read())
    #xlsxpart.add_header(‘Content-Disposition‘, ‘attachment‘, filename=f_subject+".docx")
    #main_msg.attach(xlsxpart)
    # 设置根容器属性
    main_msg[‘From‘] = From
    main_msg[‘To‘] = To
    main_msg[‘Cc‘] = ",".join(f_cclist)
    main_msg[‘Subject‘] = f_subject
    main_msg[‘Date‘] = email.Utils.formatdate()
    #f_cclist为完整的需要接收邮件的列表,原本只存放抄送列表,这里需要添加上收件人
    f_cclist.append(To)
    # 得到格式化后的完整文本
    fullText = main_msg.as_string()

    # 用smtp发送邮件
    try:
        server.sendmail(From, f_cclist, fullText)
    finally:
        server.quit()

if __name__ == "__main__":
    #sys.setdefaultencoding(‘utf-8‘)
    message= [
    ‘Usage:‘,
    ‘      sendmail.py "topic" "mail body text" "mail to"‘,
    ‘Examples of usage:‘,
    ‘                  sendmail.py "topic" "hello world" "[email protected]"‘,
    ]
    try:
        topic = str(sys.argv[1]).encode("utf-8")
        alert = str(sys.argv[2]).encode("utf-8")
        mailto = str(sys.argv[3]).encode("utf-8")
    except IndexError:
        for line in message:
            print line+‘\n‘
        sys.exit()
    cclist=[]
    #clist =[]
    sendmail("xxxx@xxx",mailto,cclist,alert, topic)



  

01-20 10:00