Exemplo n.º 1
0
 def setUp(self):
     # In Python, audiotest.au lives in Lib/test not Lib/test/data
     fp = open(findfile('audiotest.au'))
     try:
         self._audiodata = fp.read()
     finally:
         fp.close()
     self._au = MIMEAudio(self._audiodata)
Exemplo n.º 2
0
 def test_custom_encoder(self):
     eq = self.assertEqual
     def encoder(msg):
         orig = msg.get_payload()
         msg.set_payload(0)
         msg['Content-Transfer-Encoding'] = 'broken64'
     au = MIMEAudio(self._audiodata, _encoder=encoder)
     eq(au.get_payload(), 0)
     eq(au['content-transfer-encoding'], 'broken64')
Exemplo n.º 3
0
class TestMIMEAudio(unittest.TestCase):
    def setUp(self):
        # In Python, audiotest.au lives in Lib/test not Lib/test/data
        fp = open(findfile('audiotest.au'))
        try:
            self._audiodata = fp.read()
        finally:
            fp.close()
        self._au = MIMEAudio(self._audiodata)

    def test_guess_minor_type(self):
        self.assertEqual(self._au.get_type(), 'audio/basic')

    def test_encoding(self):
        payload = self._au.get_payload()
        self.assertEqual(base64.decodestring(payload), self._audiodata)

    def checkSetMinor(self):
        au = MIMEAudio(self._audiodata, 'fish')
        self.assertEqual(im.get_type(), 'audio/fish')

    def test_custom_encoder(self):
        eq = self.assertEqual

        def encoder(msg):
            orig = msg.get_payload()
            msg.set_payload(0)
            msg['Content-Transfer-Encoding'] = 'broken64'

        au = MIMEAudio(self._audiodata, _encoder=encoder)
        eq(au.get_payload(), 0)
        eq(au['content-transfer-encoding'], 'broken64')

    def test_add_header(self):
        eq = self.assertEqual
        unless = self.failUnless
        self._au.add_header('Content-Disposition',
                            'attachment',
                            filename='audiotest.au')
        eq(self._au['content-disposition'],
           'attachment; filename="audiotest.au"')
        eq(self._au.get_params(header='content-disposition'),
           [('attachment', ''), ('filename', 'audiotest.au')])
        eq(self._au.get_param('filename', header='content-disposition'),
           'audiotest.au')
        missing = []
        eq(self._au.get_param('attachment', header='content-disposition'), '')
        unless(
            self._au.get_param('foo',
                               failobj=missing,
                               header='content-disposition') is missing)
        # Try some missing stuff
        unless(self._au.get_param('foobar', missing) is missing)
        unless(
            self._au.get_param('attachment', missing, header='foobar') is
            missing)
Exemplo n.º 4
0
    def test_custom_encoder(self):
        eq = self.assertEqual

        def encoder(msg):
            orig = msg.get_payload()
            msg.set_payload(0)
            msg['Content-Transfer-Encoding'] = 'broken64'

        au = MIMEAudio(self._audiodata, _encoder=encoder)
        eq(au.get_payload(), 0)
        eq(au['content-transfer-encoding'], 'broken64')
Exemplo n.º 5
0
class TestMIMEAudio(unittest.TestCase):
    def setUp(self):
        # In Python, audiotest.au lives in Lib/test not Lib/test/data
        fp = open(findfile('audiotest.au'))
        try:
            self._audiodata = fp.read()
        finally:
            fp.close()
        self._au = MIMEAudio(self._audiodata)

    def test_guess_minor_type(self):
        self.assertEqual(self._au.get_type(), 'audio/basic')

    def test_encoding(self):
        payload = self._au.get_payload()
        self.assertEqual(base64.decodestring(payload), self._audiodata)

    def checkSetMinor(self):
        au = MIMEAudio(self._audiodata, 'fish')
        self.assertEqual(im.get_type(), 'audio/fish')

    def test_custom_encoder(self):
        eq = self.assertEqual
        def encoder(msg):
            orig = msg.get_payload()
            msg.set_payload(0)
            msg['Content-Transfer-Encoding'] = 'broken64'
        au = MIMEAudio(self._audiodata, _encoder=encoder)
        eq(au.get_payload(), 0)
        eq(au['content-transfer-encoding'], 'broken64')

    def test_add_header(self):
        eq = self.assertEqual
        unless = self.failUnless
        self._au.add_header('Content-Disposition', 'attachment',
                            filename='audiotest.au')
        eq(self._au['content-disposition'],
           'attachment; filename="audiotest.au"')
        eq(self._au.get_params(header='content-disposition'),
           [('attachment', ''), ('filename', 'audiotest.au')])
        eq(self._au.get_param('filename', header='content-disposition'),
           'audiotest.au')
        missing = []
        eq(self._au.get_param('attachment', header='content-disposition'), '')
        unless(self._au.get_param('foo', failobj=missing,
                                  header='content-disposition') is missing)
        # Try some missing stuff
        unless(self._au.get_param('foobar', missing) is missing)
        unless(self._au.get_param('attachment', missing,
                                  header='foobar') is missing)
Exemplo n.º 6
0
def sendemail(from_addr,
              to_addr_list,
              cc_addr_list,
              subject,
              message,
              files,
              smtpserver='smtp.gmail.com:587'):
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = from_addr
    msg['To'] = to_addr_list
    msg['Cc'] = cc_addr_list
    text = message
    msg.attach(MIMEText(text))

    #Mail with attachment
    ctype = "application/octet-stream"
    maintype, subtype = ctype.split('/', 1)
    if maintype == 'image':
        fp = open(files, 'rb')
        part = MIMEImage(fp.read())
        fp.close()
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment', filename=files)
        msg.attach(part)
    elif maintype == 'audio':
        fp = open(files, 'rb')
        part = MIMEAudio(fp.read())
        fp.close()
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment', filename=files)
        msg.attach(part)
    else:
        fp = open(files, 'rb')
        part = MIMEApplication(maintype, subtype)
        part.set_payload(fp.read())
        fp.close()
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment', filename=files)
        msg.attach(part)

    #Login Credentials
    username = from_addr
    password = getpass('Enter Password:'******'Email Address not Valid'
Exemplo n.º 7
0
def getAttachment(attachmentFilePath):
    contentType, encoding = mimetypes.guess_type(attachmentFilePath)

    if contentType is None or encoding is not None:
        contentType = 'application/octet-stream'

    mainType, subType = contentType.split('/', 1)
    file = open(attachmentFilePath, 'rb')

    if mainType == 'text':
        attachment = MIMEText(file.read())
    elif mainType == 'message':
        attachment = email.message_from_file(file)
    elif mainType == 'image':
        attachment = MIMEImage(file.read(), _subType=subType)
    elif mainType == 'audio':
        attachment = MIMEAudio(file.read(), _subType=subType)
    else:
        attachment = MIMEBase(mainType, subType)
    attachment.set_payload(file.read())
    encode_base64(attachment)

    file.close()

    ## 设置附件头
    attachment.add_header('Content-Disposition',
                          'attachment',
                          filename=os.path.basename(attachmentFilePath))
    return attachment
def getAttachments(msg, attachmentDirPath):

    for filename in os.listdir(attachmentDirPath):
        path = os.path.join(attachmentDirPath, filename)
        if not os.path.isfile(path):
            continue

        contentType, encoding = mimetypes.guess_type(path)
        if contentType is None or encoding is not None:
            contentType = 'application/octet-stream'
        mainType, subType = contentType.split('/', 1)

        fp = open(path, 'rb')

        if mainType == 'text':
            attachment = MIMEText(fp.read())
        elif mainType == 'image':
            attachment = MIMEImage(fp.read(), _subType=subType)
        elif mainType == 'audio':
            attachment = MIMEAudio(fp.read(), _subType=subType)
        else:
            attachment = MIMEBase(mainType, subType)
            attachment.set_payload(fp.read())
            encode_base64(attachment)
            fp.close()

        attachment.add_header('Content-Disposition',
                              'attachment',
                              filename=os.path.basename(path))
        msg.attach(attachment)
Exemplo n.º 9
0
def file2msg(file):
    ## TODO: check if file exists
    ctype, encoding = mimetypes.guess_type(file)

    if ctype is None or encoding is not None:
        ctype = 'application/octet-stream'

    maintype, subtype = ctype.split('/')

    print "==> Adding file [%s] using [%s]" % (file, ctype)

    if maintype == "text":
        fp = open(file)
        msg = MIMEText(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == "image":
        fp = open(file, 'rb')
        msg = MIMEImage(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == "audio":
        fp = open(file, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=subtype)
        fp.close()
    else:
        fp = open(file, 'rb')
        msg = MIMEBase(maintype, subtype)
        msg.set_payload(fp.read())
        fp.close()
        Encoders.encode_base64(msg)

    return msg
Exemplo n.º 10
0
def attach_files(msg):

    filename = raw_input('File name: ')
    try:
        f = open(filename, 'rb')
    except IOError:
        print 'Attachment not found'
        return msg

    ctype, encoding = mimetypes.guess_type(filename)

    if ctype is None or encoding is not None:
        ctype = 'application/octet-stream'

    maintype, subtype = ctype.split('/', 1)

    if maintype == 'text':
        part = MIMEText(f.read(), _subtype=subtype)
    elif maintype == 'image':
        part = MIMEImage(f.read(), _subtype=subtype)
    elif maintype == 'audio':
        part = MIMEAudio(f.read(), _subtype=subtype)
    else:
        part = MIMEBase(maintype, subtype)
        msg.set_payload(f.read())

    part.add_header('Content-Disposition',
                    'attachment; filename="%s"' % os.path.basename(filename))
    msg.attach(part)
    f.close()

    return msg
Exemplo n.º 11
0
 def get_content_data(self, data, filename, charset=None):
     "Vrátí data jako instanci třídy odvozené od MIMEBase."
     # Guess the content type based on the file's extension.  Encoding
     # will be ignored, although we should check for simple things like
     # gzip'd or compressed files.
     ctype, encoding = mimetypes.guess_type(filename)
     if ctype is None or encoding is not None:
         # No guess could be made, or the file is encoded (compressed), so
         # use a generic bag-of-bits type.
         ctype = 'application/octet-stream'
     maintype, subtype = ctype.split('/', 1)
     if maintype == 'text':
         # Note: we should handle calculating the charset
         if not charset:
             charset = self.charset
         content = MIMEText(data, _subtype=subtype, _charset=charset)
     elif maintype == 'image':
         content = MIMEImage(data, _subtype=subtype)
     elif maintype == 'audio':
         content = MIMEAudio(data, _subtype=subtype)
     else:
         content = MIMEBase(maintype, subtype)
         content.set_payload(data)
         email.Encoders.encode_base64(content)
     return content
Exemplo n.º 12
0
 def setUp(self):
     # In Python, audiotest.au lives in Lib/test not Lib/test/data
     fp = open(findfile('audiotest.au'))
     try:
         self._audiodata = fp.read()
     finally:
         fp.close()
     self._au = MIMEAudio(self._audiodata)
Exemplo n.º 13
0
 def sendAudio(self,audioFilePath):
     self.audioFilePath=audioFilePath
     mail_body='Send a png picture from gmail'
     mail_from='*****@*****.**'
     mail_to=['*****@*****.**']
     msg=MIMEMultipart()
     msg['Subject']='test email'
     msg['To']=';'.join(mail_to)
     msg['date']=time.strftime('%Y-%m-%d',time.localtime(time.time()))
     txt=MIMEText('test message')
     msg.attach(txt)
     for audioFile in audioFilePath:
         print os.getcwd()
         audioFileBit=open(audioFile,'rb')
         audioFileRead=MIMEAudio(audioFileBit.read())
         audioFileRead.add_header('Content-Disposition', 'attachment; filename="ddd"')
         msg.attach(audioFileRead)
         self.smtp.sendmail(mail_from,mail_to,msg.as_string())
Exemplo n.º 14
0
def sendAPI(sender, to, subject, body, attachment=None):
    try:
        service = authAPI()

        message = MIMEMultipart()
        message['to'] = to
        message['from'] = sender
        message['subject'] = subject

        msg = MIMEText(body, 'html')
        message.attach(msg)

        if attachment != None:
            mime = MimeTypes()
            content_type, encoding = mime.guess_type(attachment)

            if content_type is None or encoding is not None:
                content_type = 'application/octet-stream'
            main_type, sub_type = content_type.split('/', 1)

            if main_type == 'text':
                fp = open(attachment, 'rb')
                msg = MIMEText(fp.read(), _subtype=sub_type)
                fp.close()
            elif main_type == 'image':
                fp = open(attachment, 'rb')
                msg = MIMEImage(fp.read(), _subtype=sub_type)
                fp.close()
            elif main_type == 'audio':
                fp = open(attachment, 'rb')
                msg = MIMEAudio(fp.read(), _subtype=sub_type)
                fp.close()
            else:
                fp = open(attachment, 'rb')
                msg = MIMEBase(main_type, sub_type)
                msg.set_payload(fp.read())
                fp.close()
            filename = os.path.basename(attachment)
            msg.add_header('Content-Disposition',
                           'attachment',
                           filename=filename)

        message.attach(msg)
        message = {
            'raw': base64.urlsafe_b64encode(message.as_string()),
            'payload': {
                'mimeType': 'text/html'
            }
        }
        message = (service.users().messages().send(userId=sender,
                                                   body=message).execute())
        return True, ''

    except Exception, error:
        return False, error
Exemplo n.º 15
0
def sendVoicemail(dest, sender, draftfile):
    import smtplib
    from email.MIMEAudio import MIMEAudio
    from email.Message import Message
    infp = open(draftfile,'rb')
    draft = encodeAudio(infp, dest)
    print "wav is in", draft
    audio = MIMEAudio(open(draft).read())
    sender = '%s@%s'%(sender.username, sender.host)
    audio['Subject'] = 'A voicemail from %s'%sender
    audio['From'] = sender
    audio['To'] = dest
    server = smtplib.SMTP('localhost')
    server.set_debuglevel(0)
    server.sendmail(sender, dest, str(audio))
    server.quit()
Exemplo n.º 16
0
    def addAttachments(self, mainmsg, bodytext, attaches):
        # format a multi-part message with attachments
        msg = MIMEText(bodytext)  # add main text/plain part
        mainmsg.attach(msg)
        for filename in attaches:  # absolute or relative paths
            if not os.path.isfile(filename):  # skip dirs, etc.
                continue

            # guess content type from file extension, ignore encoding
            contype, encoding = mimetypes.guess_type(filename)
            if contype is None or encoding is not None:  # no guess, compressed?
                contype = 'application/octet-stream'  # use generic default
            self.trace('Adding ' + contype)

            # build sub-Message of apropriate kind
            maintype, subtype = contype.split('/', 1)
            if maintype == 'text':
                data = open(filename, 'r')
                msg = MIMEText(data.read(), _subtype=subtype)
                data.close()
            elif maintype == 'image':
                data = open(filename, 'rb')
                msg = MIMEImage(data.read(), _subtype=subtype)
                data.close()
            elif maintype == 'audio':
                data = open(filename, 'rb')
                msg = MIMEAudio(data.read(), _subtype=subtype)
                data.close()
            else:
                data = open(filename, 'rb')
                msg = MIMEBase(maintype, subtype)
                msg.set_payload(data.read())
                data.close()  # make generic type
                email.Encoders.encode_base64(msg)  # encode using Base64

            # set filename and attach to container
            basename = os.path.basename(filename)
            msg.add_header('Content-Disposition',
                           'attachment',
                           filename=basename)
            mainmsg.attach(msg)

        # text outside mime structure, seen by non-MIME mail readers
        mainmsg.preamble = 'A multi-part MIME format message.\n'
        mainmsg.epilogue = ''  # make sure message ends with a newline
Exemplo n.º 17
0
 def send_mail(self, target, subject, body, *file_names):
     """
     send a mail with files to the target
     @param target: send the mail to the target
     @param subject: mail's subject
     @param file_names= list of files to send
     """
     msg = MIMEMultipart()
     msg['From'] = self.mail
     msg['To'] = target
     msg['Subject'] = subject
     body_part = MIMEText(body, 'plain')
     msg.attach(body_part)
     for file_name in file_names:
         f = open(file_name, 'rb')
         ctype, encoding = mimetypes.guess_type(file_name)
         if ctype is None or encoding is not None:
             ctype = 'application/octet-stream'
         maintype, subtype = ctype.split('/', 1)
         # in case of a text file
         if maintype == 'text':
             part = MIMEText(f.read(), _subtype=subtype)
         # in case of an image file
         elif maintype == 'image':
             part = MIMEImage(f.read(), _subtype=subtype)
         # in case of an audio file
         elif maintype == 'audio':
             part = MIMEAudio(f.read(), _subtype=subtype)
         # any other file
         else:
             part = MIMEBase(maintype, subtype)
             part.set_payload(f.read())
         encoders.encode_base64(part)
         part.add_header(
             'Content-Disposition',
             'attachment; filename="%s"' % os.path.basename(file_name))
         msg.attach(part)
         f.close()
     # ssl server doesn't support or need tls,
     # so don't call server_ssl.starttls()
     self.server_ssl.sendmail(self.mail, target, msg.as_string())
     self.server_ssl.quit()
Exemplo n.º 18
0
def attachFile(path, multipart, assumedCharset=_7BIT_CHARSET):
    # Guess the content type based on the file's extension.  Encoding
    # will be ignored, although we should check for simple things like
    # gzip'd or compressed files.
    ctype, encoding = mimetypes.guess_type(path)
    if ctype is None or encoding is not None:
        # No guess could be made, or the file is encoded (compressed), so
        # use a generic bag-of-bits type.
        ctype = 'application/octet-stream'
    maintype, subtype = ctype.split('/', 1)
    if maintype == 'text':
        fp = open(path, 'rt')
        txt = fp.read()
        txt, charset = safelyEncode(txt, assumedCharset)
        # If the file was not pure ascii, but we encoded it,
        # report the encoding we're *going* to use, not the one
        # the file was in originally.'
        if charset != _7BIT_CHARSET:
            charset = _PREFERRED_NONASCII_CHARSET
        msg = MIMEText(txt, subtype, charset)
        fp.close()
    elif maintype == 'image':
        fp = open(path, 'rb')
        msg = MIMEImage(fp.read(), _subtype=subtype)
        fp.close()
    elif maintype == 'audio':
        fp = open(path, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=subtype)
        fp.close()
    else:
        fp = open(path, 'rb')
        msg = MIMEBase(maintype, subtype)
        txt = fp.read()
        msg.set_payload(fp.read())

        fp.close()
    # Set the filename parameter
    msg.add_header('Content-Disposition',
                   'attachment',
                   filename=os.path.basename(path))
    multipart.attach(msg)
Exemplo n.º 19
0
    def add_attachment(self, path):
        #Create a multipart message and each attachment gets a part
        if not self.email.is_multipart():
            newemail = MIMEMultipart()
            newemail['Subject'] = self.email['Subject']
            newemail['To'] = self.email['To']
            newemail['From'] = self.email['From']
            newemail.preamble = 'There are attachments\n'
            newemail.epilogue = ''
            self.email = newemail

        f = File.File(path)
        filename = f.get_filename()
        mt = f.get_mimetype()
        maintype, subtype = mt.split('/', 1)
        if maintype == 'text':
            fp = open(path)
            #We should handle calculating the charset
            msg = MIMEText(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'image':
            fp = open(path, 'rb')
            msg = MIMEImage(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'audio':
            fp = open(path, 'rb')
            msg = MIMEAudio(fp.read(), _subtype=subtype)
            fp.close()
        else:
            fp = open(path, 'rb')
            msg = MIMEBase('application', 'octet-stream')
            msg.set_payload(fp.read())
            fp.close()
            # Encode the payload using Base64
            Encoders.encode_base64(msg)
        # Set the filename parameter
        msg.add_header('Content-Disposition', 'attachment', filename=filename)
        self.email.attach(msg)
        self.attachments.append(path)
Exemplo n.º 20
0
def getAttachment(path, filename):
     ctype, encoding = mimetypes.guess_type(path)
     if ctype is None or encoding is not None:
         ctype = 'application/octet-stream'
     maintype, subtype = ctype.split('/', 1)
     fp = open(path, 'rb')
     if maintype == 'text':
         attach = MIMEText(fp.read(),_subtype=subtype)
     elif maintype == 'message':
         attach = email.message_from_file(fp)
     elif maintype == 'image':
         attach = MIMEImage(fp.read(),_subtype=subtype)
     elif maintype == 'audio':
         attach = MIMEAudio(fp.read(),_subtype=subtype)
     else:
         print maintype, subtype
         attach = MIMEBase(maintype, subtype)
         attach.set_payload(fp.read())
         encode_base64(attach)
     fp.close
     attach.add_header('Content-Disposition', 'attachment',
			filename=filename)
     return attach
Exemplo n.º 21
0
# Copyright (C) 2001 Python Software Foundation
Exemplo n.º 22
0
    def get_mail_text(self, fields, request, **kwargs):
        """Get header and body of e-mail as text (string)
        """
        (headerinfo, additional_headers, body) = self.get_header_body_tuple(fields, request, **kwargs)
        if not isinstance(body, str):
            body = str(body, self._site_encoding())
        portal = getToolByName(self, 'portal_url').getPortalObject()
        email_charset = portal.getProperty('email_charset', 'utf-8')
        mime_text = MIMEText(body.encode(email_charset, 'replace'),
                _subtype=self.body_type or 'html', _charset=email_charset)

        attachments = self.get_attachments(fields, request)

        ## Attachements
        uids = self.getMsg_attachments()
        if uids:
            reference_catalog = getToolByName(self, 'reference_catalog')
            for uid in uids:
                obj = reference_catalog.lookupObject(uid)
                data = obj.data
                mimetype = obj.content_type
                filename = obj.getRawTitle()
                enc = None
                attachments.append((filename, mimetype, enc, data))

        if attachments:
            outer = MIMEMultipart()
            outer.attach(mime_text)
        else:
            outer = mime_text

        # write header
        for key, value in list(headerinfo.items()):
            outer[key] = value

        # write additional header
        for a in additional_headers:
            key, value = a.split(':', 1)
            outer.add_header(key, value.strip())

        for attachment in attachments:
            filename = attachment[0]
            ctype = attachment[1]
            content = attachment[3]

            if ctype is None:
                ctype = 'application/octet-stream'

            maintype, subtype = ctype.split('/', 1)

            if maintype == 'text':
                msg = MIMEText(content, _subtype=subtype)
            elif maintype == 'image':
                msg = MIMEImage(content, _subtype=subtype)
            elif maintype == 'audio':
                msg = MIMEAudio(content, _subtype=subtype)
            else:
                msg = MIMEBase(maintype, subtype)
                msg.set_payload(content)
                # Encode the payload using Base64
                Encoders.encode_base64(msg)

            # Set the filename parameter
            msg.add_header('Content-Disposition', 'attachment', filename=filename)
            outer.attach(msg)

        return outer.as_string()
Exemplo n.º 23
0
    def get_mail_text(self, fields, request, context):
        """Get header and body of e-mail as text (string)
        """
        headerinfo = self.get_header_info(fields, request, context)
        body = self.get_mail_body(fields, request, context)
        if not isinstance(body, unicode):
            body = unicode(body, 'UTF-8')
        email_charset = 'utf-8'
        # always use text/plain for encrypted bodies
        subtype = getattr(self, 'gpg_keyid',
                          False) and 'plain' or self.body_type or 'html'
        mime_text = MIMEText(body.encode(email_charset, 'replace'),
                             _subtype=subtype,
                             _charset=email_charset)

        attachments = self.get_attachments(fields, request)

        if attachments:
            outer = MIMEMultipart()
            outer.attach(mime_text)
        else:
            outer = mime_text

        # write header
        for key, value in headerinfo.items():
            outer[key] = value

        # write additional header
        additional_headers = self.additional_headers or []
        for a in additional_headers:
            key, value = a.split(':', 1)
            outer.add_header(key, value.strip())

        for attachment in attachments:
            filename = attachment[0]
            ctype = attachment[1]
            # encoding = attachment[2]
            content = attachment[3]

            if ctype is None:
                ctype = 'application/octet-stream'

            maintype, subtype = ctype.split('/', 1)

            if maintype == 'text':
                msg = MIMEText(content, _subtype=subtype)
            elif maintype == 'image':
                msg = MIMEImage(content, _subtype=subtype)
            elif maintype == 'audio':
                msg = MIMEAudio(content, _subtype=subtype)
            else:
                msg = MIMEBase(maintype, subtype)
                msg.set_payload(content)
                # Encode the payload using Base64
                Encoders.encode_base64(msg)

            # Set the filename parameter
            if isinstance(filename, unicode):
                filename = filename.encode('utf-8')
            msg.add_header('Content-Disposition',
                           'attachment',
                           filename=('utf-8', '', filename))
            outer.attach(msg)

        return outer.as_string()
Exemplo n.º 24
0
 def checkSetMinor(self):
     au = MIMEAudio(self._audiodata, 'fish')
     self.assertEqual(im.get_type(), 'audio/fish')
Exemplo n.º 25
0
def Envoi_mail(adresseExpediteur="",
               listeDestinataires=[],
               listeDestinatairesCCI=[],
               sujetMail="",
               texteMail="",
               listeFichiersJoints=[],
               serveur="localhost",
               port=None,
               avecAuthentification=False,
               avecStartTLS=False,
               listeImages=[],
               motdepasse=None,
               accuseReception=False):
    """ Envoi d'un mail avec pièce jointe """
    import smtplib
    import poplib
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email.MIMEText import MIMEText
    from email.MIMEImage import MIMEImage
    from email.MIMEAudio import MIMEAudio
    from email.Utils import COMMASPACE, formatdate
    from email import Encoders
    import mimetypes

    assert type(listeDestinataires) == list
    assert type(listeFichiersJoints) == list

    # Corrige le pb des images embarquées
    index = 0
    for img in listeImages:
        img = img.replace(u"\\", u"/")
        img = img.replace(u":", u"%3a")
        texteMail = texteMail.replace(
            _(u"file:/%s") % img, u"cid:image%d" % index)
        index += 1

    # Création du message
    msg = MIMEMultipart()
    msg['From'] = adresseExpediteur
    msg['To'] = ";".join(listeDestinataires)
    msg['Bcc'] = ";".join(listeDestinatairesCCI)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = sujetMail

    if accuseReception == True:
        msg['Disposition-Notification-To'] = adresseExpediteur

    msg.attach(MIMEText(texteMail.encode('utf-8'), 'html', 'utf-8'))

    # Attache des pièces jointes
    for fichier in listeFichiersJoints:
        """Guess the content type based on the file's extension. Encoding
        will be ignored, altough we should check for simple things like
        gzip'd or compressed files."""
        ctype, encoding = mimetypes.guess_type(fichier)
        if ctype is None or encoding is not None:
            # No guess could be made, or the file is encoded (compresses), so
            # use a generic bag-of-bits type.
            ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        if maintype == 'text':
            fp = open(fichier)
            # Note : we should handle calculating the charset
            part = MIMEText(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'image':
            fp = open(fichier, 'rb')
            part = MIMEImage(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'audio':
            fp = open(fichier, 'rb')
            part = MIMEAudio(fp.read(), _subtype=subtype)
            fp.close()
        else:
            fp = open(fichier, 'rb')
            part = MIMEBase(maintype, subtype)
            part.set_payload(fp.read())
            fp.close()
            # Encode the payload using Base64
            Encoders.encode_base64(part)
        # Set the filename parameter
        nomFichier = os.path.basename(fichier)
        if type(nomFichier) == unicode:
            nomFichier = FonctionsPerso.Supprime_accent(nomFichier)
        part.add_header('Content-Disposition',
                        'attachment',
                        filename=nomFichier)
        msg.attach(part)

    # Images incluses
    index = 0
    for img in listeImages:
        fp = open(img, 'rb')
        msgImage = MIMEImage(fp.read())
        fp.close()
        msgImage.add_header('Content-ID', '<image%d>' % index)
        msgImage.add_header('Content-Disposition', 'inline', filename=img)
        msg.attach(msgImage)
        index += 1

##    pop = poplib.POP3(serveur)
##    print pop.getwelcome()
##    pop.user(adresseExpediteur)
##    pop.pass_(motdepasse)
##    print pop.stat()
##    print pop.list()

## Certains SMTP (exemple Orange Pro) demandent une authentifcation (en général user : boite mail et pwd : mot de passe associé au smtp sécurisé )
## mais ne supportent pas le mode starttls
## Ces identifiants sont généralement utilisés lors d'un envoi de mail abec un FAI différent du propriétaire du SMTP
## Par exemple pour envoyer un mail avec le smtp pro orange depuis un autre FAI (Free, SFR....)
##      serveur : smtp.premium.orange.fr - port 587
##      user : [email protected]
##      pwd : mon_pwd
##  On positionne dans ce cas le parametre avecAuthentification a True
##  et le parametre avecStartTLS est positionné selon l'état du support de la fonction startTLS par le SMTP

    if motdepasse == None:
        motdepasse = ""

    if avecAuthentification in (0, False, None):
        # Envoi standard
        smtp = smtplib.SMTP(serveur, timeout=150)
    else:
        # Si identification SSL nécessaire :
        smtp = smtplib.SMTP(serveur, port, timeout=150)
        smtp.ehlo()
        if avecStartTLS == True:
            smtp.starttls()
            smtp.ehlo()
        smtp.login(adresseExpediteur.encode('utf-8'),
                   motdepasse.encode('utf-8'))

    smtp.sendmail(adresseExpediteur,
                  listeDestinataires + listeDestinatairesCCI, msg.as_string())
    smtp.close()

    return True
Exemplo n.º 26
0
def mime_attach(body, attachments, charset, body_charset=None):
    mimetypes.init()

    message = MIMEMultipart('mixed')
    bodypart = BetterMIMEText(body, _charset=(body_charset or charset))
    bodypart.add_header('Content-Disposition', 'inline')
    message.preamble = 'This is a multi-part MIME message sent by reportbug.\n\n'
    message.epilogue = ''
    message.attach(bodypart)
    failed = False
    for attachment in attachments:
        try:
            fp = file(attachment)
            fp.close()
        except EnvironmentError, x:
            ewrite("Warning: opening '%s' failed: %s.\n", attachment,
                   x.strerror)
            failed = True
            continue
        ctype = None
        cset = charset
        info = Popen(['file', '--mime', '--brief', attachment],
                     stdout=PIPE,
                     stderr=STDOUT).communicate()[0]
        if info:
            match = re.match(r'([^;, ]*)(,[^;]+)?(?:; )?(.*)', info)
            if match:
                ctype, junk, extras = match.groups()
                match = re.search(r'charset=([^,]+|"[^,"]+")', extras)
                if match:
                    cset = match.group(1)
                # If we didn't get a real MIME type, fall back
                if '/' not in ctype:
                    ctype = None
        # If file doesn't work, try to guess based on the extension
        if not ctype:
            ctype, encoding = mimetypes.guess_type(attachment, strict=False)
        if not ctype:
            ctype = 'application/octet-stream'

        maintype, subtype = ctype.split('/', 1)
        if maintype == 'text':
            fp = file(attachment, 'rU')
            part = BetterMIMEText(fp.read(), _subtype=subtype, _charset=cset)
            fp.close()
        elif maintype == 'message':
            fp = file(attachment, 'rb')
            part = MIMEMessage(email.message_from_file(fp), _subtype=subtype)
            fp.close()
        elif maintype == 'image':
            fp = file(attachment, 'rb')
            part = MIMEImage(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'audio':
            fp = file(attachment, 'rb')
            part = MIMEAudio(fp.read(), _subtype=subtype)
            fp.close()
        else:
            fp = file(attachment, 'rb')
            part = MIMEBase(maintype, subtype)
            part.set_payload(fp.read())
            fp.close()
            email.Encoders.encode_base64(part)
        part.add_header('Content-Disposition',
                        'attachment',
                        filename=os.path.basename(attachment))
        message.attach(part)
Exemplo n.º 27
0
    def send(self):
        """
        Send the email message represented by this object.
        """
        # Validate message
        if self._textBody is None and self._htmlBody is None:
            raise Exception(
                "Error! Must specify at least one body type (HTML or Text)")
        if len(self._to) == 0:
            raise Exception("Must specify at least one recipient")

        # Create the message part
        if self._textBody is not None and self._htmlBody is None:
            msg = MIMEText(self._textBody, "plain")
        elif self._textBody is None and self._htmlBody is not None:
            msg = MIMEText(self._htmlBody, "html")
        else:
            msg = MIMEMultipart("alternative")
            msg.attach(MIMEText(self._textBody, "plain"))
            msg.attach(MIMEText(self._htmlBody, "html"))

        # Add attachments, if any
        if len(self._attach) != 0:
            tmpmsg = msg
            msg = MIMEMultipart()
            msg.attach(tmpmsg)
        for fname, attachname in self._attach:
            if not os.path.exists(fname):
                raise Exception(
                    "File '{0}' does not exist.  Not attaching to email.".
                    format(fname))
                continue
            if not os.path.isfile(fname):
                raise Exception(
                    "Attachment '{0}' is not a file.  Not attaching to email.".
                    format(fname))
                continue
            # Guess at encoding type
            ctype, encoding = mimetypes.guess_type(fname)
            if ctype is None or encoding is not None:
                # No guess could be made so use a binary type.
                ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/', 1)
            if maintype == 'text':
                fp = open(fname)
                attach = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'image':
                fp = open(fname, 'rb')
                attach = MIMEImage(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'audio':
                fp = open(fname, 'rb')
                attach = MIMEAudio(fp.read(), _subtype=subtype)
                fp.close()
            else:
                fp = open(fname, 'rb')
                attach = MIMEBase(maintype, subtype)
                attach.set_payload(fp.read())
                fp.close()
                # Encode the payload using Base64
                encoders.encode_base64(attach)
            # Set the filename parameter
            if attachname is None:
                filename = os.path.basename(fname)
            else:
                filename = attachname
            attach.add_header('Content-Disposition',
                              'attachment',
                              filename=filename)
            msg.attach(attach)

        # Complete header
        # This is where To, CC, BCC are differentiated
        msg['Subject'] = self._subject
        msg['From'] = self._from
        msg['To'] = ", ".join(self._to)
        msg['CC'] = ", ".join(self._cc)
        msg['BCC'] = ", ".join(self._bcc)
        if self._replyTo is not None:
            msg['reply-to'] = self._replyTo
        msg.preamble = "You need a MIME enabled mail reader to see this message"
        msg = msg.as_string()
        allRecipients = self._to + self._cc + self._bcc

        # Send message
        try:
            server = smtplib.SMTP(self._smtpServer, self._smtpPort,
                                  self._hostname, 5)
            server.set_debuglevel(self._debugLevel)
            server.ehlo()
            if self._username:
                if server.has_extn('STARTTLS'):
                    server.starttls()
                else:
                    server.quit()
                    server = smtplib.SMTP_SSL(self._smtpServer, self._smtpPort,
                                              self._hostname)
                    server.set_debuglevel(self._debugLevel)
                server.ehlo()  # re-identify ourselves over secure connection
                server.login(self._username, self._password)

            result = server.sendmail(self._from, allRecipients, msg)
        except Exception, err:
            raise err
Exemplo n.º 28
0
def main(argv):
    nome = ''
    try:
        opts, args = getopt.getopt(argv, "hi:o:", ["ifile=", "ofile="])
    except getopt.GetoptError:
        print 'convert.py -i <filename>.imm'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'convert.py -i <inputfile>.imm'
            sys.exit()

    conn = sqlite3.connect('Containers.db')
    c = conn.cursor()
    ca = conn.cursor()
    Consulta = conn

    cons = Consulta.execute(
        "Select ContainerID from Containers where FileName ='" + nome +
        "'").fetchall()

    if len(cons) == 0:
        print "File or table not found " + nome
        exit()
    else:
        for caa in cons:
            cid = caa[0]

    dirsaida = './recovered/' + nome
    try:
        os.stat(dirsaida)
    except:
        os.mkdir(dirsaida)

    consulta = "Select HeaderID, FromSender,ToSender,MsgPos,MsgSize,ReceivedDate,Subject from Headers where ContainerID  like'" + cid + "' and Deleted = 0 ;"
    nom = nome + '.imm'
    f = open(nom)
    cnt = 0
    for s in c.execute(consulta):
        header = s[0]  #HeaderID
        fromsender = s[1]  #FromSender
        tosender = 'Delivered-To:' + s[2]  #ToSender
        msgpos = s[3]  #MsgPos
        msgsize = s[4]  #MsgSize
        rec = 'Received: by 10.0.0.1 with SMTP id 123123aa'
        v = datetime.datetime.fromtimestamp(s[5])  #ReceivedDate ja convertido
        con = "select Path from Attachments where HeaderID = '" + header + "';"

        f.seek(msgpos)
        data = f.read(msgsize)
        filename = nome + '-part-%03d%s' % (cnt, '.eml')
        fp = open(os.path.join('./tmp', filename), 'w')
        fp.write(tosender.encode('utf8'))
        fp.write('\n')
        fp.write(data)
        fp.close()
        d = open(os.path.join('./tmp', filename))
        cnt += 1
        msg = email.message_from_file(d)

        for anexos in ca.execute(con):
            an = anexos[0].replace("\\", "/")
            if os.path.isfile(os.path.join('./Attachments',
                                           an.encode('utf8'))):
                path = os.path.join('./Attachments', an.encode('utf8'))
                ctype, encoding = mimetypes.guess_type(path)
                if ctype is None or encoding is not None:
                    ctype = 'application/octet-stream'
                maintype, subtype = ctype.split('/', 1)
                fp = open(path, 'rb')
                print ctype
                if subtype == 'text':
                    part = MIMEText(fp.read(), _subtype=subtype)
                elif subtype == 'image':
                    part = MIMEImage(fp.read(), _subtype=subtype)
                elif subtype == 'audio':
                    part = MIMEAudio(fp.read(), _subtype=subtype)
                else:
                    part = MIMEBase(maintype, subtype)
                    part.set_payload(fp.read())
                    Encoders.encode_base64(part)
                fp.close()
                nan1 = "recuperado-" + an.encode('utf8')
                part.add_header('Content-Disposition',
                                'attachment;filename=\"' + nan1 + '\"')
                try:
                    msg.attach(part)
                    print subtype
                except Exception, e:
                    #print part
                    print header + " " + nan1.decode('utf8')
                    print maintype + ' ' + ctype
                    print e
                    continue
        d.close()
        dirsaida = './recovered/' + nome
        saida = open(os.path.join(dirsaida, filename), 'w')
        generator = email.generator.Generator(saida)
        generator.flatten(msg)
Exemplo n.º 29
0
def emailling(user_name, From, To, PWD, FilePath, FileNames):

    msg = MIMEMultipart()
    msg['From'] = From
    msg['To'] = To
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = email_subject

    msg.attach(MIMEText(welcome_word + user_name))
    msg.attach(MIMEText(email_body))

    try:
        smtp = smtplib.SMTP('smtp.gmail.com:587')
        smtp.starttls()
        smtp.login(From, PWD)
    except:
        i = 1
    else:
        i = 0

    if i == 0:
        for FileName in FileNames:
            file = FilePath + "/" + FileName
            ctype, encoding = mimetypes.guess_type(file)
            if ctype is None or encoding is not None:
                # No guess could be made, or the file is encoded (compressed), so
                # use a generic bag-of-bits type.
                ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/', 1)
            if maintype == 'text':
                fp = open(file)
                # Note: we should handle calculating the charset
                part = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'image':
                fp = open(file, 'rb')
                part = MIMEImage(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'audio':
                fp = open(file, 'rb')
                part = MIMEAudio(fp.read(), _subtype=subtype)
                fp.close()
            else:
                fp = open(file, 'rb')
                part = MIMEBase(maintype, subtype)
                part.set_payload(fp.read())
                fp.close()
                # Encode the payload using Base64
                Encoders.encode_base64(part)
            part.add_header('Content-Disposition',
                            'attachment; filename="%s"' % FileName)
            msg.attach(part)
        try:
            smtp.sendmail(From, To, msg.as_string())
        except:
            print "Mail not sent"
        else:
            print "Mail sent"
        smtp.close()
    else:
        print "Connection failed"
Exemplo n.º 30
0
def createMail(sender, recipients, subject, html_body, attachments=None, images=None, text_message=None, reply_to=''):
    # Create the root message and fill in the from, to, and subject headers
    msgRoot = EmailContent('related')
    msgRoot['Subject'] = subject
    msgRoot['From'] = sender
    msgRoot['To'] = string.join(recipients, ',')
    msgRoot.preamble = 'Message from agilehead services'
    msgRoot['Reply-To'] = reply_to
    msgRoot['Sender'] = reply_to

    # Encapsulate the plain and HTML versions of the message body in an
    # 'alternative' part, so message agents can decide which they want to display.
    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)

    #TODO:Confirm
    #Rumor: Real mail systems always send plain-text alternative (Except spammers)
    if not text_message:
        text_message = html2text.html2text(html_body)
    msgText = MIMEText(text_message, _charset='iso-8859-1')
    msgAlternative.attach(msgText)

    # Adding the Html message body
    # Reference the image in the IMG SRC attribute by the ID like <img src="cid:image1">
    msgText = MIMEText(html_body, _subtype='html')
    msgAlternative.attach(msgText)

    if images:
        # Adding the images
        # images are assumed to be in this format - {'image1':'images/chad.jpg', 'image2':'images/jessy.jpg'}
        for cid, filepath in images.iteritems():
            fp = open(filepath, 'rb')
            msgImage = MIMEImage(fp.read())
            fp.close()

            # Define the image's ID as referenced above
            msgImage.add_header('Content-ID', '<' + cid + '>')
            msgRoot.attach(msgImage)

    if attachments:
        # Adding the attachments
        # Attachments are assumed to be a list of filepaths
        for filepath in attachments:
            # Guess the content type based on the file's extension.  Encoding
            # will be ignored, although we should check for simple things like
            # gzip'd or compressed files.
            ctype, encoding = mimetypes.guess_type(filepath)
            if ctype is None or encoding is not None:
                # No guess could be made, or the file is encoded (compressed), so
                # use a generic bag-of-bits type.
                ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/', 1)
            if maintype == 'text':
                fp = open(filepath)
                # Note: we should handle calculating the charset
                msg = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'image':
                fp = open(filepath, 'rb')
                msg = MIMEImage(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'audio':
                fp = open(filepath, 'rb')
                msg = MIMEAudio(fp.read(), _subtype=subtype)
                fp.close()
            else:
                fp = open(filepath, 'rb')
                msg = MIMEBase(maintype, subtype)
                msg.set_payload(fp.read())
                fp.close()
                # Encode the payload using Base64
                encoders.encode_base64(msg)
            # Set the filename parameter
            msg.add_header('Content-Disposition', 'attachment', filename=os.path.split(filepath)[1])
            msgRoot.attach(msg)                
    return msgRoot
Exemplo n.º 31
0
def SMSToMail(cfg, sms, lookuplist = None, mailbox = False):
    '''
    Converts SMS to formated mail. It will contain all images and sounds from
    message and predefined animations. Also text formatting is preserved in
    HTML.
    '''
    msg = MIMEMultipart('related', None, None, type='text/html')
    prepend = ''
    name = ''
    if lookuplist != None:
        i = SearchNumber(lookuplist, sms['Number'])
        if i != -1:
            msg.add_header(HEADER_FORMAT % 'ContactID', str(i))
            name = '%s ' % lookuplist[i]['Name']

    for header in PARTS_TO_HEADER:
        msg.add_header(HEADER_FORMAT % header, unicode(sms['SMS'][0][header]))
    msg.add_header(HEADER_FORMAT % 'SMSC', sms['SMS'][0]['SMSC']['Number'])
    if sms['SMS'][0]['SMSCDateTime'] is not None:
        msg.add_header(HEADER_FORMAT % 'SMSCDate',
                DateToString(sms['SMS'][0]['SMSCDateTime']))

    remote = '%s<*****@*****.**>' % (name, sms['Number'].replace(' ', '_'))
    local = cfg.Read('/MessageExport/From')

    if sms['SMS'][0]['Type'] == 'Submit':
        msg['To'] = remote
        msg['From'] = local
    else:
        msg['To'] = local
        msg['From'] = remote
        prepend = ('Received: from %s via GSM\n' %
                unicode(sms['SMS'][0]['SMSC']['Number'])) + prepend

    if len(sms['Name']) > 0 :
        msg['Subject'] = SmsTextFormat(cfg, sms['Name'], False)
    else:
        msg['Subject'] = SmsTextFormat(cfg, sms['Text'], False)[:50] + '...'

    if sms['DateTime'] is not None:
        msg['Date'] = DateToString(sms['DateTime'])

    if sms.has_key('SMSInfo'):
        text = ''
        cid = 0
        for i in sms['SMSInfo']['Entries']:
            if i['ID'] in Wammu.Data.SMSIDs['PredefinedAnimation']:
                if i['Number'] > len(Wammu.Data.PredefinedAnimations):
                    sub = MIMEImage(XPMToPNG(Wammu.Data.UnknownPredefined))
                else:
                    img = Wammu.Data.PredefinedAnimations[i['Number']][1]
                    xpm = XPMToPNG(img)
                    sub = MIMEImage(xpm)
                sub.add_header('Content-ID', '<%s>' % CID_FORMAT % cid)
                sub.add_header('Content-Disposition', 'inline')
                msg.attach(sub)
                text = text + '<img src="cid:%s">' % (CID_FORMAT % cid)
                cid = cid + 1

            # FIXME: need sounds
            if 0 and i['ID'] in Wammu.Data.SMSIDs['PredefinedSound']:
                if i['Number'] >= len(Wammu.Data.PredefinedSounds):
                    sub = ''
                else:
                    sub = ''
                sub.add_header('Content-Disposition', 'attachment')
                msg.attach(sub)

            if i['ID'] in Wammu.Data.SMSIDs['Sound']:
                sub = MIMEAudio(RingtoneToMIDI(i['Ringtone']), 'midi')
                sub.add_header('Content-Disposition', 'attachment')
                msg.attach(sub)

            if i['ID'] in Wammu.Data.SMSIDs['Text']:
                fmt = '%s'
                for format_data in Wammu.Data.TextFormats:
                    for name, dummy, style in format_data[1:]:
                        if i.has_key(name) and i[name]:
                            fmt = style % fmt
                text = text + (fmt % SmsTextFormat(cfg, i['Buffer']))

            if i['ID'] in Wammu.Data.SMSIDs['Bitmap']:
                for bitmap in i['Bitmap']:
                    sub = MIMEImage(XPMToPNG(bitmap['XPM']))
                    sub.add_header('Content-ID', '<%s>' % CID_FORMAT % cid)
                    sub.add_header('Content-Disposition', 'inline')
                    msg.attach(sub)
                    text = text + '<img src="cid:%s">' % (CID_FORMAT % cid)
                    cid = cid + 1

            if i['ID'] in Wammu.Data.SMSIDs['Animation']:
                for bitmap in i['Bitmap']:
                    sub = MIMEImage(XPMToPNG(bitmap['XPM']))
                    sub.add_header('Content-ID', '<%s>' % CID_FORMAT % cid)
                    sub.add_header('Content-Disposition', 'inline')
                    msg.attach(sub)
                    text = text + '<img src="cid:%s">' % (CID_FORMAT % cid)
                    cid = cid + 1

    else:
        text = SmsTextFormat(cfg, sms['Text'])

    html = '<html><head></head><body>%s</body></html>'
    sub = MIMEText(html % text.encode('utf-8'), 'html', 'utf-8')
    msg.attach(sub)

    if sms['DateTime'] is not None:
        filename = '%s-%s-%s.eml' % (
                sms['SMS'][0]['Type'],
                sms['DateTime'].strftime("%Y%m%d%H%M%S"),
                md5(sms['Text'].encode('utf-8')).hexdigest())
    else:
        filename = '%s-%s.eml' % (
                sms['SMS'][0]['Type'],
                md5(sms['Text'].encode('utf-8')).hexdigest())

    # Add message ID
    msgid = '<%s@%s>' % (filename[:-4], sms['Number'].replace(' ', '_'))
    msgid = msgid.encode('ascii', 'xmlcharrefreplace')
    msg.add_header('Message-ID', msgid)

    if mailbox:
        if sms['DateTime'] is None:
            timestamp = time.asctime(time.localtime(None))
        else:
            timestamp = time.asctime(sms['DateTime'].timetuple())
        prepend = ('From [email protected] %s\n' % timestamp) + prepend

    return filename, prepend + msg.as_string(), msgid
Exemplo n.º 32
0
def gsp_email(email_from, email_to, subject, message, file_To_Send,
              smtp_server):
    import smtplib
    import mimetypes
    from email.MIMEMultipart import MIMEMultipart
    from email import Encoders
    from email.Message import Message
    from email.MIMEAudio import MIMEAudio
    from email.MIMEBase import MIMEBase
    from email.MIMEImage import MIMEImage
    from email.MIMEText import MIMEText
    emailfrom = email_from
    emailto = email_to
    fileToSend = file_To_Send
    head, tail = os.path.split(fileToSend)
    email_server = smtp_server
    msg = MIMEMultipart()
    msg["From"] = emailfrom
    msg["To"] = ",".join(emailto)
    msg["Subject"] = subject
    msg.attach(MIMEText(message, 'plain'))
    ##Only needed for any preamble##msg.preamble = "YOUR EMAIL PREAMBLE"
    if fileToSend:
        ctype, encoding = mimetypes.guess_type(fileToSend)
        print(ctype)
        if ctype is None or encoding is not None:
            ctype = "application/octet-stream"
        maintype, subtype = ctype.split("/", 1)
        print(maintype)
        print(subtype)
        if maintype == "text":
            print 'text'
            fp = open(fileToSend)
            # Note: we should handle calculating the charset
            attachment = MIMEText(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == "image":
            print 'image'
            fp = open(fileToSend, "rb")
            attachment = MIMEImage(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == "audio":
            print 'audio'
            fp = open(fileToSend, "rb")
            attachment = MIMEAudio(fp.read(), _subtype=subtype)
            fp.close()
        else:
            print 'else'
            fp = open(fileToSend, "rb")
            attachment = MIMEBase(maintype, subtype)
            attachment.set_payload(fp.read())
            fp.close()
            Encoders.encode_base64(attachment)
        attachment.add_header("Content-Disposition",
                              "attachment",
                              filename=tail)
        msg.attach(attachment)
    server = smtplib.SMTP(email_server)
    server.set_debuglevel(0)
    server.sendmail(emailfrom, emailto, msg.as_string())
    server.quit()
Exemplo n.º 33
0
    def send(self):
        """
        Send the mail. Returns True if successfully sent to at least one
        recipient.
        """

        # validation
        if len(self.from_address.strip()) == 0:
            raise NoFromAddress_Exception
        if self.recipients.count() == 0:
            if ((self.cc_recipients.count() == 0)
                    and (self.bcc_recipients.count() == 0)):
                raise NoToAddress_Exception
        if len(self.subject.strip()) == 0:
            raise NoSubject_Exception

        # assemble
        if self.attachments.count() == 0:
            msg = MIMEText(_text=self.message,
                           _subtype=self.content_subtype,
                           _charset=self.content_charset)
        else:
            msg = MIMEMultipart()
            if self.message:
                att = MIMEText(_text=self.message,
                               _subtype=self.content_subtype,
                               _charset=self.content_charset)
                msg.attach(att)

        # add headers
        from_str = formataddr((self.from_caption, self.from_address))
        msg["From"] = from_str
        if self.reply_to_address:
            reply_to_str = formataddr(
                (self.reply_to_caption, self.reply_to_address))
            msg["Reply-To"] = reply_to_str
        if self.recipients.count() > 0:
            msg["To"] = ", ".join(self.recipients.get_list())
        if self.cc_recipients.count() > 0:
            msg["Cc"] = ", ".join(self.cc_recipients.get_list())
        msg["Date"] = formatdate(time.time())
        msg["User-Agent"] = self.user_agent
        try:
            msg["Subject"] = Header(self.subject, self.header_charset)
        except (UnicodeDecodeError):
            msg["Subject"] = Header(self.subject, self.content_charset)
        msg.preamble = "You will not see this in a MIME-aware mail reader.\n"
        msg.epilogue = ""

        # assemble multipart
        if self.attachments.count() > 0:
            for typ, info in self.attachments.get_list():
                if typ == 'file':
                    filename = info
                    if not os.path.isfile(filename):
                        raise AttachmentNotFound_Exception, filename
                    mimetype, encoding = mimetypes.guess_type(filename)
                    if mimetype is None or encoding is not None:
                        mimetype = 'application/octet-stream'
                    if mimetype.startswith('text/'):
                        fp = file(filename)
                    else:
                        fp = file(filename, 'rb')
                    text = fp.read()
                    fp.close()
                else:
                    filename, text, mimetype = info
                maintype, subtype = mimetype.split('/', 1)
                if maintype == 'text':
                    # Note: we should handle calculating the charset
                    att = MIMEText(text, _subtype=subtype)
                elif maintype == 'image':
                    att = MIMEImage(text, _subtype=subtype)
                elif maintype == 'audio':
                    att = MIMEAudio(text, _subtype=subtype)
                else:
                    att = MIMEBase(maintype, subtype)
                    att.set_payload(text)
                    # Encode the payload using Base64
                    Encoders.encode_base64(att)
                # Set the filename parameter
                att.add_header('Content-Disposition',
                               'attachment',
                               filename=os.path.basename(filename).strip())
                msg.attach(att)

        # connect to server
        smtp = smtplib.SMTP()
        if self.smtp_server:
            smtp.connect(self.smtp_server)
        else:
            smtp.connect()

        # TLS?
        if self.use_tls:
            smtp.ehlo()
            smtp.starttls()
            smtp.ehlo()

        # authenticate
        if self.smtp_user:
            smtp.login(user=self.smtp_user, password=self.smtp_password)

        # send
        self.statusdict = smtp.sendmail(
            from_str,
            (self.recipients.get_list() + self.cc_recipients.get_list() +
             self.bcc_recipients.get_list()), msg.as_string())
        smtp.close()

        return True
Exemplo n.º 34
0
    def EnvoyerEmail(self, commentaires="", listeFichiers=[]):
        """ Envoi d'un mail avec pièce jointe """
        import smtplib
        from email.MIMEMultipart import MIMEMultipart
        from email.MIMEBase import MIMEBase
        from email.MIMEText import MIMEText
        from email.MIMEImage import MIMEImage
        from email.MIMEAudio import MIMEAudio
        from email.Utils import COMMASPACE, formatdate
        from email import Encoders
        import mimetypes

        IDrapport = datetime.datetime.now().strftime("%Y%m%d%H%M%S")

        # texte
        if len(commentaires) == 0:
            commentaires = _(u"Aucun")
        texteMail = _(
            u"<u>Envoi de %d fichier(s) de traduction pour Noethys :</u><br/><br/>%s<br/><br/><u>Commentaires :</u><br/><br/>%s"
        ) % (len(listeFichiers), ", ".join(listeFichiers), commentaires)

        # Destinataire
        listeDestinataires = [
            "noethys" + "@gmail.com",
        ]

        # Expéditeur
        dictExp = self.GetAdresseExpDefaut()
        if dictExp == None:
            dlg = wx.MessageDialog(
                self,
                _(u"Vous devez d'abord saisir une adresse d'expéditeur depuis le menu Paramétrage > Adresses d'expédition d'Emails."
                  ), _(u"Erreur"), wx.OK | wx.ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()
            return False
        adresseExpediteur = dictExp["adresse"]
        serveur = dictExp["smtp"]
        port = dictExp["port"]
        ssl = dictExp["ssl"]
        motdepasse = dictExp["motdepasse"]
        utilisateur = dictExp["utilisateur"]

        # Création du message
        msg = MIMEMultipart()
        msg['From'] = adresseExpediteur
        msg['To'] = ";".join(listeDestinataires)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = _(u"Envoi de fichiers de traduction Noethys")

        msg.attach(MIMEText(texteMail.encode('utf-8'), 'html', 'utf-8'))

        # Attache des pièces jointes
        for fichier in listeFichiers:
            """Guess the content type based on the file's extension. Encoding
            will be ignored, altough we should check for simple things like
            gzip'd or compressed files."""
            ctype, encoding = mimetypes.guess_type(fichier)
            if ctype is None or encoding is not None:
                # No guess could be made, or the file is encoded (compresses), so
                # use a generic bag-of-bits type.
                ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/', 1)
            if maintype == 'text':
                fp = open(fichier)
                # Note : we should handle calculating the charset
                part = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'image':
                fp = open(fichier, 'rb')
                part = MIMEImage(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'audio':
                fp = open(fichier, 'rb')
                part = MIMEAudio(fp.read(), _subtype=subtype)
                fp.close()
            else:
                fp = open(fichier, 'rb')
                part = MIMEBase(maintype, subtype)
                part.set_payload(fp.read())
                fp.close()
                # Encode the payload using Base64
                Encoders.encode_base64(part)
            # Set the filename parameter
            nomFichier = os.path.basename(fichier)
            if type(nomFichier) == unicode:
                nomFichier = FonctionsPerso.Supprime_accent(nomFichier)
            part.add_header('Content-Disposition',
                            'attachment',
                            filename=nomFichier)
            msg.attach(part)

        if ssl == False:
            # Envoi standard
            smtp = smtplib.SMTP(serveur)
        else:
            # Si identification SSL nécessaire :
            smtp = smtplib.SMTP(serveur, port, timeout=150)
            smtp.ehlo()
            smtp.starttls()
            smtp.ehlo()
            smtp.login(utilisateur.encode('utf-8'), motdepasse.encode('utf-8'))

        try:
            smtp.sendmail(adresseExpediteur, listeDestinataires,
                          msg.as_string())
            smtp.close()
        except Exception, err:
            dlg = wx.MessageDialog(
                self,
                _(u"Le message n'a pas pu être envoyé.\n\nErreur : %s !") %
                err, _(u"Envoi impossible"), wx.OK | wx.ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()
            return False