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("发送邮件成功")
来源:CSDN
作者:欢笑的外表忧郁的内心
链接:https://blog.csdn.net/qq_37543808/article/details/103243048