python发送邮件






#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
# @Author: Alnk(李成果)
# @Email: 1029612787@qq.com
# @Date: 2021/4/16 2:58 下午
"""
import smtplib
from email.mime.text import MIMEText


# 邮箱账号信息
MAIL_HOST = "smtp.qq.com"  # smtp服务器
MAIL_USER = "1029612787@qq.com"  # 用户名
MAIL_PASS = "******"  # 密码(这里的密码不是登录邮箱密码,而是授权码)
SENDER = "1029612787@qq.com"  # 发件人邮箱


def send_mail(receive: list, title: str, content: str):
    """
    邮件发送函数
    @param receive: 收件人
    @param title: 邮件主题
    @param content: 邮件内容
    @return: 标志位, 信息提示
    """
    try:
        message = MIMEText(content, 'plain', 'utf-8')  # 内容, 格式, 编码
        message['From'] = "{}".format(SENDER)
        message['To'] = ",".join(receive)
        message['Subject'] = title

        smtp_Obj = smtplib.SMTP_SSL(MAIL_HOST, 465)  # 启用SSL发信, 端口一般是465
        smtp_Obj.login(MAIL_USER, MAIL_PASS)  # 登录验证
        smtp_Obj.sendmail(SENDER, receive, message.as_string())  # 发送
        return True, "Mail sending success"

    except smtplib.SMTPException as e:
        return False, "Mail sending failed, err:%s" % e


if __name__ == "__main__":
    ret = send_mail(['lichengguo@*****.com', 'lichengguo@*****.net'], "监控中心", "有服务器告警啦")
    print(ret)


posted @ 2021-04-16 14:37  李成果  阅读(52)  评论(0编辑  收藏  举报