📅  最后修改于: 2022-03-11 14:45:13.098000             🧑  作者: Mango
import sys,os,smtplib,email,io,zipfile
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import Encoders
class sendmail(object):
def __init__(self):
self.subject=""
self.body=""
self.mail_from=""
self.mail_to=""
self.attachments=[]
self.attachments2zip=[]
def add_body_line(self,text):
self.body="%s\r\n%s"%(self.body,text)
def set_body(self,text):
self.body=text
def new_mail(self,frm,to,sbj):
self.subject=sbj
self.body=""
self.mail_from=frm
self.mail_to=to
self.attachments=[]
self.attachments2zip=[]
def set_subject(self,text):
self.subject=text
def set_from(self,text):
self.mail_from=text
def set_to(self,text):
self.mail_to=text
def add_attachment(self,file):
self.attachments.append(file)
def add_attachment_zipped(self,file):
self.attachments2zip.append(file)
def send(self):
message = MIMEMultipart()
message["From"] = self.mail_from
message["To"] = self.mail_to
message["Subject"] = self.subject
#message["Bcc"] = receiver_email # Recommended for mass emails
message.attach(MIMEText(self.body, "plain"))
if len(self.attachments)>0:#If we have attachments
for file in self.attachments:#For each attachment
filename=os.path.basename(file)
#part = MIMEApplication(f.read(), Name=filename)
part = MIMEBase('application', "octet-stream")
part.set_payload(open(file, "rb").read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'%(filename))
message.attach(part)
if len(self.attachments2zip)>0:#If we have attachments
for file in self.attachments2zip:#For each attachment
filename=os.path.basename(file)
zipped_buffer = io.BytesIO()
zf=zipfile.ZipFile(zipped_buffer,"w", zipfile.ZIP_DEFLATED)
zf.write(file, filename)
zf.close()
zipped_buffer.seek(0)
part = MIMEBase('application', "octet-stream")
part.set_payload(zipped_buffer.read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s.zip"'%(filename))
message.attach(part)
text = message.as_string()
server = smtplib.SMTP('localhost')
server.sendmail(self.mail_from, self.mail_to, text)
server.quit()