python发送邮件

女生的网名这么多〃 提交于 2019-11-27 18:15:45
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
class Email:

    _sender=""
    _receiver=""
    _username=""
    _password=""
    _mail_title=""
    _message=""
    _SMTP = "smtp.126.com"

    def __init__(self, send, to, username, password, mail_title="主题"):
        self._mail_title=mail_title
        self._password=password
        self._receiver=to
        self._sender=send
        self._username=username


    def create_email(self):
        self._message = MIMEMultipart()
        self._message['From'] = self._sender
        self._message['To'] = self._receiver
        self._message['Subject'] = Header(self._mail_title, 'utf-8')

    def email_content(self, text="hello,world"):
        if not isinstance(self._message,MIMEMultipart):
            print("你还没有创建消息,请先创建消息--create_email")
            return;
        # 体现面对对象的特性
        message = self._message;
        message.attach(MIMEText(text,'plain','utf-8'))


    #添加附件
    def add_enclosure(self,file):
        if not isinstance(self._message, MIMEMultipart):
            print("你还没有创建消息,请先创建消息--create_email")
            return;
        att1 = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8')
        att1["Content-Type"] = 'application/octet-stream'
        att1["Content-Disposition"] = 'attachment; filename="'+file+"\""
        self._message.attach(att1)


    def start_send(self):
        if not isinstance(self._message, MIMEMultipart):
            print("你还没有创建消息,请先创建消息--create_email")
            return;
        smtpObj = smtplib.SMTP_SSL(host=self._SMTP)  # 注意:如果遇到发送失败的情况(提示远程主机拒接连接),这里要使用SMTP_SSL方法
        smtpObj.connect(host=self._SMTP)
        smtpObj.login(self._username, self._password)
        smtpObj.sendmail(self._sender, self._receiver, self._message.as_string())
        smtpObj.quit()


if __name__ == "__main__":
    email = Email("xxx@126.com", "xxx@qq.com", "xx@126.com", "xxx", "test")
    email.create_email()
    email.email_content("test")
    email.add_enclosure("../Images/1.png")
    try:
        email.start_send()
    except:
        print("发生错误")

    else
        print("发送邮件成功")

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!