Any easy-to-use email send module?

Larry Bates larry.bates at websafe.com
Wed Dec 20 09:31:32 EST 2006


oyster wrote:
> I find that the existing email moudle is some hard for me to
> understand, especially the part of how to set the CC, BCC and attach
> the files. Is there any more easy one like this p-code?
> 
> import easyemail
> smtpserver=easyemail.server('something')
> smtpserver.login('usr at gmail.com', pwd)
> newletter=smtpsever.letter(smtpserver)
> newletter.sendto=['to1 at 1.com', 'to2 at 2.com']
> newletter.sendcc=['cc1 at 111.com', 'cc2 at 222.com']
> newletter.sendbcc=['bcc1 at 111.com', 'bcc2 at 222.com']
> newletter.body='this is the body\nline 2'
> newletter.att=['c:/file1.txt', 'd:/program files/app/app.exe']
> 
> if (newletter.send()==True):
>    print 'send ok'
> smtpserver.close()
> 
> Thanx.
I'm not entirely sure where I got this code (Google search
years ago) and I've extended it a little, but you are welcome
to use it and it is very close to what you outlined above.
I had to strip out a bunch of custom logging that I include
in my version, but it think this will either work or at least
be close enough to save you some time.

-Larry


import string,sys,types,os,tempfile,time
import smtplib
import poplib
import mimetypes,mimetools,MimeWriter
class SmtpWriter:
    def __init__(self, server="localhost", dest=None, src=None,
                 userid=None, password=None):

        self.__server = server
        self.__dest   = dest
        self.__src    = src
        self.__userid = userid
        self.__password=password
        self.__debugLevel = 0
        return

    def Debug(self,level):
         self.__debugLevel = level


    def Message(self,sender="",
                     subject="",
                     recipients=[],
                     body="",
                     attachments=[]):


        if self.__debugLevel > 2:
            sys.stderr.write("SmtpWriter: Building RFC822 message From: %s; " \
                             "Subject: %s; (Length=%d with %d attachments)\n" % \
                             (sender, subject, len(body), len(attachments)))

            sys.stderr.flush()

        tempFileName = tempfile.mktemp()
        tempFile = open(tempFileName,'wb')
        message = MimeWriter.MimeWriter(tempFile)
        message.addheader("From",sender)
        message.addheader("To", reduce(lambda a,b: a + ",\n    " + b, recipients))
        message.addheader("Subject", subject)
        message.flushheaders()
        if len(attachments) == 0:
            fp = message.startbody('text/plain')
            fp.write(body)
        else:
            message.startmultipartbody('mixed')
            submessage = message.nextpart()
            fp = submessage.startbody('text/plain')
            fp.write(body)
            for attachFile in attachments:
                if type(attachFile) == types.StringType:
                    fileName = attachFile
                    filePath = attachFile

                elif type(attachFile) == types.TupleType and len(attachFile) == 2:
                    filePath, fileName = attachFile
                else:
                    raise "Attachments Error: must be pathname string or
path,filename tuple"

                submessage = message.nextpart()
                submessage.addheader("Content-Disposition", "attachment;
filename=%s" % fileName)
                ctype,prog = mimetypes.guess_type(fileName)
                if ctype == None:
                    ctype = 'unknown/unknown'

                if ctype == 'text/plain':
                    enctype = 'quoted-printable'
                else:
                    enctype = 'base64'

                submessage.addheader("Content-Transfer-Encoding",enctype)
                fp = submessage.startbody(ctype)
                afp = open(filePath,'rb')
                mimetools.encode(afp,fp,enctype)

            message.lastpart()

        tempFile.close()

        # properly formatted mime message should be in tmp file

        tempFile = open(tempFileName,'rb')
        msg = tempFile.read()
        tempFile.close()
        os.remove(tempFileName)
        #print "about to try to create SMTPserver instance"
        server=None

        #
        # See if I can create a smtplib.SMTP instance
        #
        try: server = smtplib.SMTP(self.__server)
        except:
            if self.__debugLevel > 2:
                emsg="SmtpWriter.Message-Unable to connect to " \
                     "SMTP server=%s" % self.__server
                sys.stderr.write(emsg)
                sys.stderr.flush()

            raise RuntimeError(emsg)

        if self.__debugLevel > 2: server.set_debuglevel(1)
        #
        # If server requires authentication to send mail, do it here
        #
        if self.__userid is not None and self.__password is not None:
            #
            # There are two possible ways to authenticate: direct or indirect
            # direct - smtp.login
            # indirect - smtp after pop3 auth
            #
            try: response=server.login(self.__userid, self.__password)
            except:
                if self.__debugLevel > 2:
                    emsg="SmtpWriter.Message-SMTP auth failed, trying POP3 " \
                          "auth"
                    sys.stderr.write(emsg)
                    sys.stderr.flush()

                try:
                    M=poplib.POP3(self.__server)
                    M.user(self.__src)
                    M.pass_(self.__password)
                    M.stat() # Get mailbox status
                    M.quit()

                except:
                    if self.__debugLevel > 2:
                        emsg="SmtpWriter.Message-Both SMTP and POP3 auth failed " \
                              "email message NOT sent"
                        sys.stderr.write(emsg)
                        sys.stderr.flush()

                    raise RuntimeError(emsg)

        #
        # Send the email
        #
        server.sendmail(self.__src, self.__dest, msg)
        if self.__debugLevel > 1:
            sys.stderr.write("SmptWriter.Message sent\n")
            sys.stderr.flush()

        server.quit()
        return


if __name__ == "__main__":
    import sys
    import time
    server="mail.domain.com"
    email=SmtpWriter(server=server,
                     dest=["name at domain.com.com"],
                     src="smtpwriter at domain.com",
                     userid="smtpwriter at domain.com",
                     password="password")

    email.Message(sender="smtpwriter at domain.com",
                  subject="Test email #2",
                  recipients=["me at domain.com"],
                  body="This is a test email from the SmtpWriter class",
                  attachments=["c:\\output.txt"])



More information about the Python-list mailing list