Skip to main content
Rollback to Revision 4
Source Link
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 __read_filesend(self,file):
        returnmessage open(file,= "rb").readMIMEMultipart()
    
     defmessage["From"] __zip_in_memory(= self,file):.mail_from
        filename=os.pathmessage["To"] = self.basename(file)mail_to
        zipped_buffermessage["Subject"] = ioself.BytesIO()subject
        zf=zipfile.ZipFile(zipped_buffer,"w", zipfile.ZIP_DEFLATED)
 #message["Bcc"] = receiver_email  # Recommended for zf.write(file,mass filename)emails
        zf.close()
        zipped_buffermessage.seekattach(0MIMEText(self.body, "plain"))
        return zipped_buffer.read()
    
     defif __attach_filelen(self,data,filename.attachments)>0:#If we have attachments
        part = MIMEBase('application', "octet-stream") for file in self.attachments:#For each attachment
        part.set_payload(data)
        Encodersfilename=os.encode_base64path.basename(partfile)
        part.add_header('Content-Disposition', 'attachment; filename="%s"'%(filename))
      #part = self.messageMIMEApplication(f.attachread(part), Name=filename)
    
     def send(self):
        self.messagepart = MIMEMultipartMIMEBase('application', "octet-stream")
        self.message["From"] = self.mail_from
        selfpart.message["To"] =set_payload(open(file, self"rb").mail_toread())
        self.message["Subject"] = self      Encoders.subjectencode_base64(part)
        #message["Bcc"] = receiver_email  # Recommended for mass emailspart.add_header('Content-Disposition', 'attachment; filename="%s"'%(filename))
        
         self.message.attach(MIMEText(self.body, "plain",'UTF-8')part)
        
         for 
 file in      if len(self.attachmentsattachments2zip)>0:#For#If eachwe attachmenthave attachments
            data=self.__read_file(file)#Getfor file datain self.attachments2zip:#For each attachment
                filename=os.path.basename(file)
            self    zipped_buffer = io.__attach_fileBytesIO(data,filename)#Attach 
 file to the message
            zf=zipfile.ZipFile(zipped_buffer,"w", zipfile.ZIP_DEFLATED)
   
         for file in self.attachments2zip:#For each attachmentzf.write(file, thatfilename)
 need to be zipped
            data=selfzf.__zip_in_memoryclose(file)#Get 
 zipped data
            filename="%s.zip"%(os.path  zipped_buffer.basenameseek(file)0)
            self.__attach_file(data,filename)#Attach file to the message
        
         textpart = self.message.as_stringMIMEBase('application', "octet-stream")
        server = smtplib      part.SMTPset_payload('localhost'zipped_buffer.read())
        server.sendmail(self.mail_from, self.mail_to, text)
        serverEncoders.quitencode_base64(part)
 
#Send test email
if __name__=="__main__":
    import getpass
    username=getpass    part.getuseradd_header('Content-Disposition', 'attachment; filename="%s.zip"'%(filename))
    m=sendmail()
    m.new_mail(username,username,"Test mail")
    m   message.add_attachmentattach(__file__part)
    m.add_attachment_zipped(__file__)    
    m.add_body_line("Hi Alex,")
   text m= message.add_body_lineas_string("*** This)
 is an automated message - please do notserver reply= ***smtplib."SMTP('localhost')
    m    server.add_body_linesendmail("Bestself.mail_from, regardsself."mail_to, text)
    m    server.sendquit()
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 __read_file(self,file):
        return open(file, "rb").read()
    
     def __zip_in_memory(self,file):
        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)
        return zipped_buffer.read()
    
     def __attach_file(self,data,filename):
        part = MIMEBase('application', "octet-stream")
        part.set_payload(data)
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"'%(filename))
        self.message.attach(part)
    
     def send(self):
        self.message = MIMEMultipart()
        self.message["From"] = self.mail_from
        self.message["To"] = self.mail_to
        self.message["Subject"] = self.subject
        #message["Bcc"] = receiver_email  # Recommended for mass emails
        
         self.message.attach(MIMEText(self.body, "plain",'UTF-8'))
        
         for file in self.attachments:#For each attachment
            data=self.__read_file(file)#Get file data
            filename=os.path.basename(file)
            self.__attach_file(data,filename)#Attach file to the message
                
         for file in self.attachments2zip:#For each attachment that need to be zipped
            data=self.__zip_in_memory(file)#Get zipped data
            filename="%s.zip"%(os.path.basename(file))
            self.__attach_file(data,filename)#Attach file to the message
        
         text = self.message.as_string()
        server = smtplib.SMTP('localhost')
        server.sendmail(self.mail_from, self.mail_to, text)
        server.quit()
 
#Send test email
if __name__=="__main__":
    import getpass
    username=getpass.getuser()
    m=sendmail()
    m.new_mail(username,username,"Test mail")
    m.add_attachment(__file__)
    m.add_attachment_zipped(__file__)
    m.add_body_line("Hi Alex,")
    m.add_body_line("*** This is an automated message - please do not reply ***.")
    m.add_body_line("Best regards.")
    m.send()
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()
added 501 characters in body
Source Link
Alex
  • 151
  • 5
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__read_file(self,file):
        messagereturn =open(file, MIMEMultipart"rb").read()
      
   message["From"] =def __zip_in_memory(self.mail_from,file):
        message["To"] = selffilename=os.mail_topath.basename(file)
        message["Subject"]zipped_buffer = selfio.subjectBytesIO()
        #message["Bcc"]zf=zipfile.ZipFile(zipped_buffer,"w", =zipfile.ZIP_DEFLATED)
 receiver_email  # Recommended for mass emails zf.write(file, filename)
        zf.close()
        messagezipped_buffer.attach(MIMETextseek(self.body, "plain")0)
        return zipped_buffer.read()
     
    ifdef len__attach_file(self.attachments,data,filename)>0:#If we have attachments
            for file inpart self.attachments:#For= eachMIMEBase('application', attachment"octet-stream")
        part.set_payload(data)
        filename=os.pathEncoders.basenameencode_base64(filepart)
        part.add_header('Content-Disposition', 'attachment; filename="%s"'%(filename))
      #part = MIMEApplication(fself.readmessage.attach(), Name=filenamepart)
     
    def send(self):
       part self.message = MIMEBaseMIMEMultipart('application', "octet-stream")
        self.message["From"] = self.mail_from
      part.set_payload(open(file, "rb").read())
    self.message["To"] = self.mail_to
        self.message["Subject"] = Encodersself.encode_base64(part)subject
          #message["Bcc"] = receiver_email  # Recommended part.add_header('Content-Disposition',for 'attachment;mass filename="%s"'%(filename))emails
         
        self.message.attach(partMIMEText(self.body, "plain",'UTF-8'))
               
  
       for file ifin len(self.attachments2zip)>0attachments:#If we#For haveeach attachmentsattachment
            for file in selfdata=self.attachments2zip:#For__read_file(file)#Get eachfile attachmentdata
                filename=os.path.basename(file)
                zipped_buffer = ioself.BytesIO__attach_file(data,filename)
 #Attach file to the message
            zf=zipfile.ZipFile(zipped_buffer,"w", zipfile.ZIP_DEFLATED)
    
        for file in self.attachments2zip:#For each zf.write(file,attachment filename)
that need to be zipped
            zfdata=self.close__zip_in_memory(file)
  #Get zipped data
            zipped_bufferfilename="%s.seekzip"%(0os.path.basename(file))
            self.__attach_file(data,filename)#Attach file to the message
         
        parttext = MIMEBaseself.message.as_string('application', "octet-stream")
              server = part.set_payload(zipped_buffersmtplib.readSMTP()'localhost')
        server.sendmail(self.mail_from, self.mail_to, text)
       Encoders server.encode_base64quit(part)
      
#Send test email
if __name__=="__main__":
    import getpass
  part.add_header('Content-Disposition', 'attachment; filename="%susername=getpass.zip"'%getuser(filename))
       m=sendmail()
    m.new_mail(username,username,"Test mail")
    messagem.attachadd_attachment(part__file__)
        m.add_attachment_zipped(__file__)
     m.add_body_line("Hi Alex,")
  text = messagem.as_stringadd_body_line()
"*** This is an automated message - please do servernot =reply smtplib***.SMTP('localhost'")
        serverm.sendmailadd_body_line(self.mail_from,"Best selfregards.mail_to, text")
        serverm.quitsend()
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()
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 __read_file(self,file):
        return open(file, "rb").read()
     
    def __zip_in_memory(self,file):
        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)
        return zipped_buffer.read()
     
    def __attach_file(self,data,filename):
        part = MIMEBase('application', "octet-stream")
        part.set_payload(data)
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"'%(filename))
        self.message.attach(part)
     
    def send(self):
        self.message = MIMEMultipart()
        self.message["From"] = self.mail_from
        self.message["To"] = self.mail_to
        self.message["Subject"] = self.subject
        #message["Bcc"] = receiver_email  # Recommended for mass emails
         
        self.message.attach(MIMEText(self.body, "plain",'UTF-8'))
         
        for file in self.attachments:#For each attachment
            data=self.__read_file(file)#Get file data
            filename=os.path.basename(file)
            self.__attach_file(data,filename)#Attach file to the message
                 
        for file in self.attachments2zip:#For each attachment that need to be zipped
            data=self.__zip_in_memory(file)#Get zipped data
            filename="%s.zip"%(os.path.basename(file))
            self.__attach_file(data,filename)#Attach file to the message
         
        text = self.message.as_string()
        server = smtplib.SMTP('localhost')
        server.sendmail(self.mail_from, self.mail_to, text)
        server.quit()

#Send test email
if __name__=="__main__":
    import getpass
    username=getpass.getuser()
    m=sendmail()
    m.new_mail(username,username,"Test mail")
    m.add_attachment(__file__)
    m.add_attachment_zipped(__file__)
    m.add_body_line("Hi Alex,")
    m.add_body_line("*** This is an automated message - please do not reply ***.")
    m.add_body_line("Best regards.")
    m.send()
edited title
Source Link
Alex
  • 151
  • 5

Send mailemail with attachments, including in memory zipped attachments

The below class implementing a simple way to create mailsemails with attachments, including the option to create in-memory zip files and attach them to the mailemail.

Because I am not a professional programmer but like to write good code I will be glad to get comments. Two main questions do I create proper mailemail headers and proper attachment headers.

Send mail with attachments, including in memory zipped attachments

The below class implementing a simple way to create mails with attachments, including the option to create in-memory zip files and attach them to the mail.

Because I am not a professional programmer but like to write good code I will be glad to get comments. Two main questions do I create proper mail headers and proper attachment headers.

Send email with attachments, including in memory zipped attachments

The below class implementing a simple way to create emails with attachments, including the option to create in-memory zip files and attach them to the email.

Because I am not a professional programmer but like to write good code I will be glad to get comments. Two main questions do I create proper email headers and proper attachment headers.

added 1 character in body
Source Link
Alex
  • 151
  • 5
Loading
Tweeted twitter.com/StackCodeReview/status/1410885992035209218
deleted 14 characters in body; edited tags
Source Link
Billal Begueradj
  • 3.4k
  • 10
  • 25
  • 34
Loading
Source Link
Alex
  • 151
  • 5
Loading