python 发送邮件

1. 使用python 发送邮件时,有时需要进行kerberos认证,以及登录认证。

# !/usr/bin/python
# -*- coding: UTF-8 -*-

import smtplib
from email.mime.text import MIMEText 
from email.header import Header  
import os
from pyhive import hive

mail_host = "webmail.qq.com"  # 10.135.15.14
username = "kk"  # kk@qq.com
passwd = "qwe123rfd"  # 邮箱密码

sender = 'kk@qq.com'
receivers = ['kk@qq.com']


def kerberos_authentication():
    os.system("kinit -kt /home/zz.keytab zz@CENTER.DATAPLAT")
    #conn = hive.Connection(host='sjpt-other-standby-9.wxxdc', port=10000, username='zz', database='zz',
    #    auth='KERBEROS', kerberos_service_name="hive")
    #cursor = conn.cursor()
    #cursor.close()
    #conn.close()


def get_message(file_path, subject):
    content_list = []
    with open(file_path, "r") as f:
        for line in f:
            content_list.append(line)
    content = "".join(content_list)
    message = MIMEText(content, 'plain', 'utf-8')
    # message['From'] = Header("监控邮件", 'utf-8')
    # message['To'] = Header("XX团队成员", 'utf-8')
    message['Subject'] = Header(subject, 'utf-8')
    return message


if __name__ == "__main__":
    # 邮件内容
    file_path = "data.txt"
    # 邮件主题
    subject = '测试一下'
    message = get_message(content, subject)
    # kerberos_authentication()  # 进行kerberos认证
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)  # SMTP端口号为25
    smtpObj.login(username, passwd)  # 登录认证
    smtpObj.sendmail(sender, receivers, message.as_string())
    smtpObj.close()

备注:

发送不成功可能与python 版本有关。

2. 自定义邮件类,实现发送附件

# coding:utf-8
import email
import smtplib
import base64
import sys

class Mailer:
    def __init__(self, smtp_host, smtp_user, smtp_passwd, smtp_port=25):
        self.smtp_host = smtp_host
        self.smtp_user = smtp_user
        self.smtp_passwd = smtp_passwd
        self.smtp_port = smtp_port
        self.mail = email.MIMEMultipart.MIMEMultipart('related')
        self.alter = email.MIMEMultipart.MIMEMultipart('alternative')
        self.mail.attach(self.alter)
        self.attachments = []

    def mailfrom(self, mail_from):
        self._from = mail_from
        self.mail['from'] = mail_from

    def mailto(self, mail_to):
        """
        mail_to : comma separated emails
        """
        self._to = mail_to
        if type(mail_to) == list:
            self.mail['to'] = ','.join(mail_to)
        elif type(mail_to) == str:
            self.mail['to'] = mail_to
        else:
            raise Exception('invalid mail to')
        print mail_to

    def mailsubject(self, mail_subject):
        self.mail['subject'] = mail_subject

    def mailbcc(self, bcc):
        self._bcc = bcc
        if type(bcc) == list:
            self.mail['bcc'] = ','.join(bcc)
        elif type(bcc) == str:
            self.mail['bcc'] = bcc
        else:
            raise Exception('invalid bcc')
        print bcc

    def text_body(self, body, encoding='utf-8'):
        self.alter.attach(email.MIMEText.MIMEText(body, 'plain', encoding))

    def html_body(self, body, encoding='utf-8'):
        self.alter.attach(email.MIMEText.MIMEText(body, 'html', encoding))

    def addattach(self, filepath, mime_type='octect-stream', rename=None):
        import os
        filecontent = ''
        with open(filepath, 'rb') as f:
            filecontent = f.read()
        mb = email.MIMEBase.MIMEBase('application', mime_type)
        mb.set_payload(filecontent)
        email.Encoders.encode_base64(mb)
        fn = os.path.basename(filepath)
        mb.add_header('Content-Disposition', 'attachment', filename=rename or fn)
        self.mail.attach(mb)

    def send(self):
        self.mail['Date'] = email.Utils.formatdate()
        smtp = False
        try:
            smtp = smtplib.SMTP()
            smtp.set_debuglevel(1)
            smtp.connect(self.smtp_host, self.smtp_port)
            smtp.docmd("AUTH LOGIN", base64.b64encode(self.smtp_user))
            smtp.docmd(base64.b64encode(self.smtp_passwd), "")
            # smtp.login(self.smtp_user, self.smtp_passwd)
            # smtp.sendmail(self._from, self._to+[]+self._bcc, self.mail.as_string())
            smtp.sendmail(self._from, self._to, self.mail.as_string())
            return True
        except Exception, e:
            import traceback
            print traceback.format_exc()
            return False
        # finally :
        smtp and smtp.quit()


def get_mailer():
    # 邮件服务器以及发邮件需要的账户密码
    mailer = Mailer("webmail.qq.com", "123@qq.com", "123123" ) # smtp,user,pwd
    mailer.mailfrom('11@qq.com') # 发件人邮箱
    return mailer

if __name__ == '__main__':
    mailer = get_mailer()
    mailto = ["11@qq.com", "22@qq.com"]
    subject = "测试一下"
    body = "----------xixixi---"
    attach_file = 'data.txt'
    mailer.mailto(mailto)
    mailer.mailsubject(subject)
    mailer.html_body(body)
    mailer.addattach(attach_file)  # 添加附件
    mailer.send()
    print("------邮件已发送------")

3. DateFrom 转HTML

#coding=utf-8
import pandas as pd
import smtplib
from email.mime.multipart import MIMEMultipart  # 构建邮件头信息,包括发件人,接收人,标题等
from email.mime.text import MIMEText  # 构建邮件正文,可以是text,也可以是HTML
from email.header import Header  # 专门构建邮件标题的,这样做,可以支持标题中文
from email.mime.application import MIMEApplication

pd.set_option('display.max_colwidth', -1)  # 能显示的最大宽度, 否则to_html出来的地址就不全

def dataframeToHtml(tar_df):
    """
    1. 构造html信息
    """
    df_html = tar_df.to_html(escape=False)

    head = \
        """
        <head>
            <meta charset="utf-8">
            <STYLE TYPE="text/css" MEDIA=screen>

                table.dataframe {
                    border-collapse: collapse;
                    border: 2px solid #000000;
                    /*靠左显示概要数据*/
                    margin-left: 5px;
                }

                table.dataframe thead {
                    border: 2px solid #91c6e1;
                    background: #f1f1f1;
                    padding: 10px 10px 10px 10px;
                    color: #000000;
                }

                table.dataframe tbody {
                    border: 2px solid #91c6e1;
                    padding: 10px 10px 10px 10px;
                }

                table.dataframe tr {

                }

                table.dataframe th {
                    vertical-align: top;
                    font-size: 14px;
                    padding: 10px 10px 10px 10px;
                    color: #105de3;
                    font-family: arial;
                    text-align: center;
                }

                table.dataframe td {
                    text-align: center;
                    padding: 10px 10px 10px 10px;
                }

                body {
                    font-family: 宋体;
                }

                h1 {
                    color: #000000
                }

                div.header h2 {
                    color: #0002e3;
                    font-family: 黑体;
                }

                div.content h2 {
                    text-align: center;
                    font-size: 28px;
                    text-shadow: 2px 2px 1px #de4040;
                    color: #fff;
                    font-weight: bold;
                    background-color: #008eb7;
                    line-height: 1.5;
                    margin: 20px 0;
                    box-shadow: 10px 10px 5px #888888;
                    border-radius: 5px;
                }

                h3 {
                    font-size: 22px;
                    background-color: rgba(0, 2, 227, 0.71);
                    text-shadow: 2px 2px 1px #de4040;
                    color: rgba(239, 241, 234, 0.99);
                    line-height: 1.5;
                }

                h4 {
                    color: #e10092;
                    font-family: 楷体;
                    font-size: 20px;
                    text-align: center;
                }

                td img {
                    /*width: 60px;*/
                    max-width: 300px;
                    max-height: 300px;
                }

            </STYLE>
        </head>
        """

    # 构造模板的附件(100)
    body = \
        """
        <body>

        <hr>

        <div>
            <!--正文内容-->
            <h2 align=left> {date_left}到{date_right} 整体数据情况</h2>

            <div>
                {df_html}
            </div>
            <hr>

            <p style="text-align: left">
                —— 详细数据见附件1 ——
            </p>
        </div>
        </body>
        """.format(df_html=df_html, date_left="2019-03-02", date_right="2019-03-05")

    html_msg= "<html>" + head + body + "</html>"

    # 这里是将HTML文件输出,作为测试的时候,查看格式用的,正式脚本中可以注释掉
    fout = open('t4.html', 'w', encoding="utf-8", newline="")
    fout.write(html_msg)

    return html_msg



def send_data_df(html_msg):
    """发送邮件的脚本"""

    # 邮件头信息
    msg = MIMEMultipart('related')
    msg['Subject'] = Header("我的第一封python邮件")
    msg["From"] = sender
    msg['To'] = ','.join(receiver)  # 这里要注意

    # html 内容
    content_html = MIMEText(html_msg, "html", "utf-8")
    msg.attach(content_html)

    # 发送邮件,测试成功,流程都是固定的:创建客户端,登陆,发送,关闭
    email_client = smtplib.SMTP(smtp_server)
    email_client.login(username, password)
    email_client.sendmail(sender, receiver, msg.as_string())
    email_client.quit()

    # 添加统计结果表格
    if os.path.exists(excel_pth):
        excelFile = MIMEApplication(open(excel_pth, 'rb').read())
        excelFile.add_header("Content-Disposition", "attachment", filename="数据统计.xls")
        message.attach(excelFile)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值