python学习--使用QQ邮箱发送邮件

版权声明:本文为博主原创文章,未经博主允许不得转载。如有写的不恰当或者不正确的地方,请指正,欢迎与我讨论。如需要查看博客中的源代码,请联系博主QQ:1477517404 https://blog.csdn.net/hfutzhouyonghang/article/details/89335370

服务器计算数据有时需要大量的时间,使用程序发送一封邮件是一种免费便捷的通知方式,可以让我们及时收到程序中断或者程序运行完成的信息,而不用一直盯着屏幕看。以下以python为例写一个邮件发送程序:

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

class Mail(object):
    def __init__(self,user,token):
        self.host = "smtp.qq.com"   # qq邮箱服务器地址
        self.user = user
        self.token = token
        self.sender = "[email protected]"
        self.subject = "服务器通知"
        self.smtpObj = smtplib.SMTP()
        self.smtpObj.connect(self.host, 25)
        self.smtpObj.login(user,token)


    def generate_message(self,message):
        self.message = MIMEText(message,'plain','utf-8')
        self.message['From'] = Header('计算中心','utf-8')
        self.message['To'] = Header('电商所的同学们','utf-8')
        self.message['Subject'] = Header(self.subject, 'utf-8')

    def send_to(self,receiver):
        try:
            self.smtpObj.sendmail(self.sender, receiver, self.message.as_string())
            print("邮件发送成功")
        except smtplib.SMTPException:
            print("Error: 无法发送邮件")

在程序中的调用:

# -*- coding: <utf-8> -*-
from ServerEmail import Mail
if __name__ == "__main__":
    email = Mail("[email protected]","******")   # QQ邮箱的账号  和token,token是从QQ邮箱网站中获取的授权码
    email.generate_message("程序已经运行完成,请尽快查看实验结果")
    email.send_to("[email protected]")

效果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/hfutzhouyonghang/article/details/89335370
0条评论
添加一条新回复