コード例 #1
0
ファイル: mail.py プロジェクト: BBOOXX/stash
 def send(self,sendto='',
              subject='',
              attach='',
              body=' '): 
     print('Sending email')
     msg = MIMEMultipart()
     msg["From"]    = self.mailfrom
     msg["To"]      = sendto
     msg["Subject"] = subject
     msg['Date']    = formatdate(localtime=True)
     
     #add messagw
     self._print('Attaching msg: %s' %body)
     message = MIMEText('text', "plain")
     message.set_payload(body+'\n')
     msg.attach(message)
     # attach a file
     if attach:
         self._print('Attachment found: %s'% attach)
         part = MIMEBase('application', "octet-stream")
         part.set_payload( open(attach,"rb").read() )
         Encoders.encode_base64(part)
         part.add_header('Content-Disposition', 'attachment; filename="%s"' % attach)
         msg.attach(part)
     
     self._print('Creating SMTP')
     server = smtplib.SMTP(self.host,int(self.port))
     
     if self.tls == 'True' or self.tls == 'true':
         server.starttls()
         self._print('tls started.')
     if self.auth == 'True' or self.auth == 'true':
         try:
             self._print('Logging into to SMTP: %s %s'%(self.user,self.passwd))
             server.login(self.user, self.passwd)  # optional
         except Exception as e:
             print('Failed Login %s'%e)
             sys.exit(0)
         
     else:
         try:
             self._print('Connecting to SMTP')
             server.connect()
         except Exception as e:
             print('Failed to connect %s'%e)
             sys.exit(0)
  
     try:
         self._print('Sending mail to: %s' %sendto)
         server.sendmail(self.mailfrom, sendto, msg.as_string())
         print('mail sent.')
         server.close()
     except Exception as e:
         errorMsg = "Unable to send email. Error: %s" % str(e)
コード例 #2
0
ファイル: mail.py プロジェクト: CPoirot3/scrapy
    def send(self, to, subject, body, cc=None, attachs=(), mimetype='text/plain', charset=None, _callback=None):
        if attachs:
            msg = MIMEMultipart()
        else:
            msg = MIMENonMultipart(*mimetype.split('/', 1))

        to = list(arg_to_iter(to))
        cc = list(arg_to_iter(cc))

        msg['From'] = self.mailfrom
        msg['To'] = COMMASPACE.join(to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
        rcpts = to[:]
        if cc:
            rcpts.extend(cc)
            msg['Cc'] = COMMASPACE.join(cc)

        if charset:
            msg.set_charset(charset)

        if attachs:
            msg.attach(MIMEText(body, 'plain', charset or 'us-ascii'))
            for attach_name, mimetype, f in attachs:
                part = MIMEBase(*mimetype.split('/'))
                part.set_payload(f.read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="%s"' \
                    % attach_name)
                msg.attach(part)
        else:
            msg.set_payload(body)

        if _callback:
            _callback(to=to, subject=subject, body=body, cc=cc, attach=attachs, msg=msg)

        if self.debug:
            logger.debug('Debug mail sent OK: To=%(mailto)s Cc=%(mailcc)s '
                         'Subject="%(mailsubject)s" Attachs=%(mailattachs)d',
                         {'mailto': to, 'mailcc': cc, 'mailsubject': subject,
                          'mailattachs': len(attachs)})
            return

        dfd = self._sendmail(rcpts, msg.as_string())
        dfd.addCallbacks(self._sent_ok, self._sent_failed,
            callbackArgs=[to, cc, subject, len(attachs)],
            errbackArgs=[to, cc, subject, len(attachs)])
        reactor.addSystemEventTrigger('before', 'shutdown', lambda: dfd)
        return dfd
コード例 #3
0
ファイル: UTILS_Envoi_email.py プロジェクト: neoclust/Noethys
 def AttacheFichiersJoints(self, email=None):
     for fichier in self.fichiers:
         """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()
         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) == six.text_type:
             nomFichier = FonctionsPerso.Supprime_accent(nomFichier)
         # changement cosmetique pour ajouter les guillements autour du filename
         part.add_header('Content-Disposition',
                         "attachment; filename=\"%s\"" % nomFichier)
         email.attach(part)
コード例 #4
0
    def send(self, sendto='', subject='', attach='', body=' '):
        print('Sending email')
        msg = MIMEMultipart()
        msg["From"] = self.mailfrom
        msg["To"] = sendto
        msg["Subject"] = subject
        msg['Date'] = formatdate(localtime=True)

        #add messagw
        self._print('Attaching msg: %s' % body)
        message = MIMEText('text', "plain")
        message.set_payload(body + '\n')
        msg.attach(message)
        # attach a file
        if attach:
            self._print('Attachment found: %s' % attach)
            part = MIMEBase('application', "octet-stream")
            part.set_payload(open(attach, "rb").read())
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition',
                            'attachment; filename="%s"' % attach)
            msg.attach(part)

        self._print('Creating SMTP')
        server = smtplib.SMTP(self.host, int(self.port))

        if self.tls == 'True' or self.tls == 'true':
            server.starttls()
            self._print('tls started.')
        if self.auth == 'True' or self.auth == 'true':
            try:
                self._print('Logging into to SMTP: %s %s' %
                            (self.user, self.passwd))
                server.login(self.user, self.passwd)  # optional
            except Exception as e:
                print('Failed Login %s' % e)
                sys.exit(0)

        else:
            try:
                self._print('Connecting to SMTP')
                server.connect()
            except Exception as e:
                print('Failed to connect %s' % e)
                sys.exit(0)

        try:
            self._print('Sending mail to: %s' % sendto)
            server.sendmail(self.mailfrom, sendto, msg.as_string())
            print('mail sent.')
            server.close()
        except Exception as e:
            errorMsg = "Unable to send email. Error: %s" % str(e)
コード例 #5
0
ファイル: base.py プロジェクト: AndresGutierrezCR/gpgliblib
    def get_mime_signature(self, signature):
        """Get a signature MIME message from the passed signature.

        Parameters
        ----------

        signature : bytes
            A gpg signature.
        """
        msg = MIMEBase(_maintype='application',
                       _subtype='pgp-signature',
                       name='signature.asc')
        msg.set_payload(signature)
        msg.add_header('Content-Description', 'OpenPGP digital signature')
        msg.add_header('Content-Disposition',
                       'attachment; filename="signature.asc"')
        del msg['MIME-Version']
        del msg['Content-Transfer-Encoding']
        return msg
コード例 #6
0
    def add_file(self,
                 theFile=None,
                 data=None,
                 filename=None,
                 content_type=None):
        "add a Zope file or Image to ourselves as an attachment"
        if theFile and data is not None:
            raise TypeError(
                'A file-like object was passed as well as data to create a file'
            )
        if (data is None) != (not filename):
            raise TypeError('Both data and filename must be specified')
        if data is not None:
            if content_type is None:
                content_type, enc = guess_content_type(filename, data)
        elif isinstance(theFile, File):
            filename = theFile.getId()
            data = str(theFile.data)
            content_type = content_type or theFile.content_type
        elif isinstance(theFile, file):
            filename = cookId(theFile.name)
            data = theFile.read()
            if content_type is None:
                content_type, enc = guess_content_type(filename, data)
        elif isinstance(theFile, FileUpload):
            filename = cookId(theFile.filename)
            data = theFile.read()
            headers = theFile.headers
            if content_type is None:
                if 'content-type' in headers:
                    content_type = headers['content-type']
                else:
                    content_type, enc = guess_content_type(filename, data)
        else:
            raise TypeError('Unknown object type found: %r' % theFile)

        msg = MIMEBase(*content_type.split('/'))
        msg.set_payload(data)
        encode_base64(msg)
        msg.add_header('Content-ID', '<%s>' % \
            ''.join(['%s' % ord(i) for i in filename]))
        msg.add_header('Content-Disposition', 'attachment', filename=filename)
        self.attach(msg)
コード例 #7
0
ファイル: base.py プロジェクト: mathiasertl/gpg-mime
    def get_mime_signature(self, signature):
        """Get a signature MIME message from the passed signature.

        Parameters
        ----------

        signature : bytes
            A gpg signature.
        """
        msg = MIMEBase(_maintype='application', _subtype='pgp-signature', name='signature.asc')
        msg.set_payload(signature)
        msg.add_header('Content-Description', 'OpenPGP digital signature')
        msg.add_header('Content-Disposition', 'attachment; filename="signature.asc"')
        del msg['MIME-Version']
        del msg['Content-Transfer-Encoding']
        return msg
コード例 #8
0
    def send(self, to, subject, body, cc=None, attachs=(), mimetype='text/plain', charset=None, _callback=None):
        if attachs:
            msg = MIMEMultipart()
        else:
            msg = MIMENonMultipart(*mimetype.split('/', 1))

        to = list(arg_to_iter(to))
        cc = list(arg_to_iter(cc))

        msg['From'] = self.mailfrom
        msg['To'] = COMMASPACE.join(to)
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject
        rcpts = to[:]
        if cc:
            rcpts.extend(cc)
            msg['Cc'] = COMMASPACE.join(cc)

        if charset:
            msg.set_charset(charset)

        if attachs:
            msg.attach(MIMEText(body, 'plain', charset or 'us-ascii'))
            for attach_name, mimetype, f in attachs:
                part = MIMEBase(*mimetype.split('/'))
                part.set_payload(f.read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="%s"' \
                    % attach_name)
                msg.attach(part)
        else:
            msg.set_payload(body)

        if _callback:
            _callback(to=to, subject=subject, body=body, cc=cc, attach=attachs, msg=msg)

        if self.debug:
            logger.debug('Debug mail sent OK: To=%(mailto)s Cc=%(mailcc)s '
                         'Subject="%(mailsubject)s" Attachs=%(mailattachs)d',
                         {'mailto': to, 'mailcc': cc, 'mailsubject': subject,
                          'mailattachs': len(attachs)})
            return

        dfd = self._sendmail(rcpts, msg.as_string().encode(charset or 'utf-8'))
        dfd.addCallbacks(self._sent_ok, self._sent_failed,
            callbackArgs=[to, cc, subject, len(attachs)],
            errbackArgs=[to, cc, subject, len(attachs)])
        reactor.addSystemEventTrigger('before', 'shutdown', lambda: dfd)
        return dfd
コード例 #9
0
ファイル: mail.py プロジェクト: SenadI/tea
 def _create_attachment(self, filename, content, mimetype=None):
     """Converts the filename, content, mimetype triple into a MIME
     attachment object.
     """
     if mimetype is None:
         mimetype, _ = mimetypes.guess_type(filename)
         if mimetype is None:
             mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
     basetype, subtype = mimetype.split('/', 1)
     if basetype == 'text':
         attachment = SafeMIMEText(smart_bytes(content, DEFAULT_CHARSET),
                                   subtype, DEFAULT_CHARSET)
     else:
         # Encode non-text attachments with base64.
         attachment = MIMEBase(basetype, subtype)
         attachment.set_payload(content)
         encode_base64(attachment)
     if filename:
         attachment.add_header('Content-Disposition',
                               'attachment',
                               filename=filename)
     return attachment
コード例 #10
0
def sendMail(to,
             subject,
             text,
             files=[],
             server="mail1.psfc.mit.edu",
             ssl=False,
             ssl_port=465,
             ssl_username='',
             ssl_passwd=''):
    assert type(to) == list
    assert type(files) == list
    #    me =  '*****@*****.**'
    me = ssl_username  # '*****@*****.**'
    msg = MIMEMultipart()
    msg['From'] = me
    #    msg['To'] = COMMASPACE.join(['*****@*****.**'])
    msg['To'] = COMMASPACE.join(to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(MIMEText(text))

    for file in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload(open(file, "rb").read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition',
                        'attachment; filename="%s"' % os.path.basename(file))
        msg.attach(part)

    if ssl:
        print((server, ssl_port))
        smtp = smtplib.SMTP_SSL(server, ssl_port)
        smtp.login(ssl_username, ssl_passwd)
    else:
        smtp = smtplib.SMTP(server)
    smtp.sendmail(me, to, msg.as_string())
    smtp.close()
コード例 #11
0
def send_mail(to_addr, subj_msg, body_msg, attach_path, serv_addr, serv_port,
              from_addr, passwd):
    """Send an e-mail message using smtplib and email standard python libraries.
    IMPORTANT! Password is stored as plain text! Do NOT use with your personal
    account!

    Args:
        to_addr (str): Recipient address.
        subj_msg (str): Message subject.
        body_msg (str): Message body.
        serv_addr (str): Server's address. Default: <smtp.gmail.com>.
        serv_port (int): Server's port. Default: <587>.
        from_addr (str): Account address. Default: <*****@*****.**>.
        passwd (str): Account password.
    """
    msg = MIMEMultipart()
    if attach_path is not None:
        with open(attach_path, "rb") as fin:
            part = MIMEBase("application", "octet-stream")
            part.set_payload(fin.read())
            encoders.encode_base64(part)
            part.add_header("Content-Disposition",
                            "attachment; filename={0}".format(attach_path))
            msg.attach(part)
    else:
        pass
    msg["From"] = from_addr
    msg["To"] = to_addr
    msg["Subject"] = subj_msg
    msg.attach(MIMEText(body_msg, "plain"))
    server = smtplib.SMTP(serv_addr, serv_port)
    server.starttls()
    server.login(from_addr, passwd)
    text_msg = msg.as_string()
    server.sendmail(from_addr, to_addr, text_msg)
    server.quit
コード例 #12
0
def send_email(xfrom,
               to,
               subject,
               body,
               cc=None,
               bcc=None,
               attachments=None,
               host=None):
    if not has_len(host):
        host = 'localhost'

    outer = MIMEMultipart()

    if has_len(xfrom):
        outer['From'] = xfrom
    elif isinstance(xfrom, (list, tuple)) and len(xfrom) == 2:
        outer['From'] = "%s <%s>" % (Header(unidecoder(xfrom[0]),
                                            'utf-8'), xfrom[1])
        xfrom = xfrom[1]
    else:
        raise ValueError("Invalid e-mail sender. (from: %r)" % xfrom)

    outer['Date'] = formatdate(localtime=True)
    smtp = smtplib.SMTP(host)

    if has_len(to):
        to = [to]

    if isinstance(to, (list, tuple)):
        to = list(to)
        outer['To'] = COMMASPACE.join(list(to))
    else:
        raise ValueError("Invalid e-mail recipients. (to: %r)" % to)

    if has_len(cc):
        cc = [cc]

    if isinstance(cc, (list, tuple)):
        to += list(cc)
        outer['Cc'] = COMMASPACE.join(list(cc))

    if has_len(bcc):
        bcc = [bcc]

    if isinstance(bcc, (list, tuple)):
        to += list(bcc)

    if has_len(subject):
        outer['Subject'] = Header(unidecoder(subject), 'utf-8')

    if has_len(body):
        outer.attach(MIMEText(unidecoder(body), _charset='utf-8'))

    if has_len(attachments):
        attachments = [attachments]

    if attachments:
        if isinstance(attachments, (list, tuple)):
            attachments = dict(
                zip(attachments,
                    len(attachments) * ('application/octet-stream', )))

        for attachment in sorted(iterkeys(attachments)):
            fp = open(attachment, 'rb')
            part = MIMEBase('application', 'octet-stream')
            part.set_type(attachments[attachment])
            filename = os.path.basename(attachment)
            part.set_payload(fp.read())
            fp.close()
            encoders.encode_base64(part)
            part.add_header('Content-Disposition',
                            'attachment',
                            filename=filename)
            outer.attach(part)

    smtp.sendmail(xfrom, to, outer.as_string())
    smtp.quit()
コード例 #13
0
ファイル: __init__.py プロジェクト: mathiasertl/pygpgme-mime
def rfc3156(message, recipients=None, signers=None, context=None, always_trust=False):
    """
    Parameters
    ----------

    message : :py:class:`email.mime.base.MIMEBase` or str
    context : :py:class:`pygpgme.Context`, optional
        If not set, a new object with default parameters will be created.
    always_trust : bool, optional
        If ``True``, always trust recipient keys.
    """

    if (not signers and not recipients) or context and context.signers:
        raise ValueError("No signers or recipients given.")

    if isinstance(message, six.string_types):
        message = MIMEText(message + '\n\n')
        del message['MIME-Version']

    if recipients is None:
        recipients = []
    elif isinstance(recipients, six.string_types):
        recipients = [recipients]

    if signers is None:
        signers = []
    elif isinstance(signers, six.string_types):
        signers = [signers]

    if context is None:
        context = gpgme.Context()
    context.armor = True

    # signers/recpiients may either be a string or a key from the context
    signers = [(context.get_key(k) if isinstance(k, six.string_types) else k) for k in signers]
    recipients = [context.get_key(k) if isinstance(k, six.string_types) else k for k in recipients]

    if signers:
        context.signers = signers

    input_bytes = six.BytesIO(message.as_bytes())
    output_bytes = six.BytesIO()

    if recipients:  # we have recipients, so we encrypt

        # compute flags passed to encrypt/encrypt_sign
        flags = 0
        if always_trust is True:
            flags |= gpgme.ENCRYPT_ALWAYS_TRUST

        # sign message
        if context.signers:
            context.encrypt_sign(recipients, flags, input_bytes, output_bytes)
        else:
            context.encrypt(recipients, flags, input_bytes, output_bytes)
        output_bytes.seek(0)

        # the control message
        control_msg = MIMEApplication(_data='Version: 1\n', _subtype='pgp-encrypted',
                                      _encoder=encode_noop)
        control_msg.add_header('Content-Description', 'PGP/MIME version identification')
        del control_msg['MIME-Version']

        encrypted = MIMEApplication(_data=output_bytes.getvalue(),
                                    _subtype='octed-stream', name='encrypted.asc',
                                    _encoder=encode_noop)
        encrypted.add_header('Content-Description', 'OpenPGP encrypted message')
        encrypted.add_header('Content-Disposition', 'inline; filename="encrypted.asc"')
        del encrypted['MIME-Version']

        msg = MIMEMultipart(_subtype='pgp-encrypted', _subparts=[control_msg, encrypted])
        msg.set_param('protocol', 'application/pgp-encrypted')
        return msg
    else:  # just signing
        del message['MIME-Version']
        for payload in message.get_payload():
            if isinstance(payload, MIMEBase):
                del payload['MIME-Version']
        message.policy = message.policy.clone(max_line_length=0)

        to_sign = message.as_bytes().replace(b'\n', b'\r\n')
        context.sign(six.BytesIO(to_sign), output_bytes, gpgme.SIG_MODE_DETACH)
        output_bytes.seek(0)
        signature = output_bytes.getvalue()

        sig = MIMEBase(_maintype='application', _subtype='pgp-signature', name='signature.asc')
        sig.set_payload(signature.decode('utf-8'))
        sig.add_header('Content-Description', 'OpenPGP digital signature')
        sig.add_header('Content-Disposition', 'attachment; filename="signature.asc"')
        del sig['MIME-Version']
        del sig['Content-Transfer-Encoding']

        msg = MIMEMultipart(_subtype='signed', _subparts=[message, sig])
        msg.set_param('protocol', 'application/pgp-signature')
        del msg['MIME-Version']

        return msg