Ejemplo n.º 1
0
 def compose(self, to_addrs=[], from_addr='', subject='', message='', cc_addrs=[], 
             bcc_addrs=[], content_type='text/plain', attachments=[]):
     
     self.subject = subject
     self.to_addrs = to_addrs
     self.from_addr = from_addr
     
     if not attachments and content_type == 'text/plain':
         msg = MIMEText(message)
     else:
         msg = MIMEMultipart()
     
     # should be refactored
     msg['To'] = ','.join(to_addrs)
     msg['From'] = from_addr
     if cc_addrs:
         msg['Cc'] = ','.join(cc_addrs)
     msg['Subject'] = subject
     msg['Date'] = Utils.formatdate(localtime=1)
     msg['Message-ID'] = Utils.make_msgid()
     
     if content_type != 'text/plain':
         body = MIMEMultipart('alternative')
         body.attach(genpart(message, content_type))
         msg.attach(body)
     
     for a in attachments:
         msg.attach(attachment(a))
     
     self.msg = msg.as_string()
Ejemplo n.º 2
0
    def getmsg(self, filename):
        '''
        构建邮件数据对象
        '''
        msg = MIMEMultipart('tiancheng testing report email')
        msg['From'] = self.from_addr
        msg['To'] = 'Recver <' + self.from_addr + '>'
        msg['Subject'] = u'来自天秤持续集成测试报告'
        msg['Date'] = Utils.formatdate(localtime = 1)
        msg['Message-ID'] = Utils.make_msgid()

        #邮件内容
        messagetext = u'''Dear All,
        Annex Libra continuous integration test report, please use the browser to open to view, thank you!
        '''
        parttext = MIMEText(messagetext)
        msg.attach(parttext)


        #文件附件
        filepart = MIMEApplication(open(filename,'rb').read())
        filepart.add_header('Content-Disposition', 'attachment', filename=filename.split("/")[-1])
        msg.attach(filepart)
        self.msg = msg
        return True
Ejemplo n.º 3
0
    def generate(alternative=False, subject=None, plain=None, html=None, sender_address=None, sender_name=None):
        alternative = alternative or not html is None
        if alternative:
            message = MIMEMultipart('alternative')
            message.attach(MIMEText('', 'plain'))
            message.attach(MIMEText('', 'html'))
        else:
            message = MIMEText('', 'plain')

        message['Date'] = Utils.formatdate(localtime=1)
        message['Message-ID'] = Utils.make_msgid()

        facade = EmailFacade(message=message)

        if subject:
            facade.subject = subject

        if plain:
            facade.text = plain

        if html:
            facade.html = html

        if sender_address:
            facade.from_address.address = sender_address
            if sender_name:
                facade.from_address.name = sender_name

        return facade
Ejemplo n.º 4
0
    def get_payload(self, i = None, decode = False):
        if i is None:
            payload = self._payload
        elif not isinstance(self._payload, list):
            raise TypeError('Expected list, got %s' % type(self._payload))
        else:
            payload = self._payload[i]
        if decode:
            if self.is_multipart():
                return
            cte = self.get('content-transfer-encoding', '').lower()
            if cte == 'quoted-printable':
                return Utils._qdecode(payload)
            elif cte == 'base64':
                try:
                    return Utils._bdecode(payload)
                except binascii.Error:
                    return payload

            elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
                sfp = StringIO()
                try:
                    uu.decode(StringIO(payload + '\n'), sfp)
                    payload = sfp.getvalue()
                except uu.Error:
                    return payload

        return payload
Ejemplo n.º 5
0
def send_email(config, to_addr, message):
    msg = MIMEMultipart()
    msg["Subject"] = config.subject
    msg["From"] = config.from_addr
    msg["To"] = to_addr
    msg["Date"] = Utils.formatdate(localtime = 1)
    msg["Message-ID"] = Utils.make_msgid()
    body = MIMEText(message, "html", _charset="utf-8")
    msg.attach(body)
    smtp = smtplib.SMTP()
    #smtp.set_debuglevel(1)
    smtp.connect(config.smtp_server)
    ehlo_host = config.from_addr.split("@")[1]
    smtp.ehlo(ehlo_host)
    if config.starttls:
        try:
            smtp.starttls()
            smtp.ehlo()
        except:
            pass
    if config.require_auth:
        try:
            smtp.login(config.smtp_username, config.smtp_password)
        except:
            pass
    smtp.sendmail(msg["From"], msg["To"], msg.as_string())
    smtp.quit()
    return
Ejemplo n.º 6
0
    def __compareMessageObjects(self, mOne, mTwo):
        self.assertNotEqual(mOne, None)
        self.assertNotEqual(mTwo, None)

        self.assertEquals(mOne['From'], mTwo['From'])
        self.assertEquals(mOne['To'], mTwo['To'])
        self.assertEquals(mOne['Cc'], mTwo['Cc'])
        self.assertEquals(mOne['Content-Transfer-Encoding'], mTwo['Content-Transfer-Encoding'])
        self.assertEquals(mOne['Mime-Version'], mTwo['Mime-Version'])
        self.assertEquals(mOne['Subject'], mTwo['Subject'])


        dOne = emailUtils.parsedate(mOne['Date'])
        dTwo = emailUtils.parsedate(mTwo['Date'])

        for i in range(6):
            if dOne[i] != dTwo[i]:
               self.fail("Dates do not match %s != %s" % (mOne['Date'], mTwo['Date']))

        if mOne.get_content_maintype() == 'multipart':
            payloadOne = mOne.get_payload()[0].get_payload()[1].get_payload(decode=True)
        else:
            payloadOne = mOne.get_payload(decode=True)

        if mTwo.get_content_maintype() == 'multipart':
            payloadTwo = mTwo.get_payload()[0].get_payload()[1].get_payload(decode=True)
        else:
            payloadTwo = mTwo.get_payload(decode=True)

        self.assertEquals(payloadOne, payloadTwo)
Ejemplo n.º 7
0
  def mail_headers(self, group, params):
    from email import Utils

    subject  = self._rfc2047_encode(self.make_subject(group, params))
    from_hdr = self._rfc2047_encode(self.from_addr)
    to_hdr   = self._rfc2047_encode(', '.join(self.to_addrs))

    hdrs = 'From: %s\n' \
           'To: %s\n' \
           'Subject: %s\n' \
           'Date: %s\n' \
           'Message-ID: %s\n' \
           'MIME-Version: 1.0\n' \
           'Content-Type: text/plain; charset=UTF-8\n' \
           'Content-Transfer-Encoding: 8bit\n' \
           'X-Svn-Commit-Project: %s\n' \
           'X-Svn-Commit-Author: %s\n' \
           'X-Svn-Commit-Revision: %d\n' \
           'X-Svn-Commit-Repository: %s\n' \
           % (from_hdr, to_hdr, subject,
              Utils.formatdate(), Utils.make_msgid(), group,
              self.repos.author or 'no_author', self.repos.rev,
              os.path.basename(self.repos.repos_dir))
    if self.reply_to:
      hdrs = '%sReply-To: %s\n' % (hdrs, self.reply_to)
    return hdrs + '\n'
Ejemplo n.º 8
0
  def xmlrpc_resetpassword_confirm(self, token, mac):
    def badconfirmlinkmsg():
      return self.Fault('Your confirm link was invalid; contact acctserv@hcs '\
          'further assistance.')

    token = (token or '').strip()
    mac = (mac or '').strip()
    cryptor = AES.new(self.secret_cipher, AES.MODE_ECB)

    try:
      plaintext = cryptor.decrypt(base64.urlsafe_b64decode(token))
      mac = base64.urlsafe_b64decode(mac)
    except ValueError: # if the code is a not a multiple of 16 bytes long
      raise badconfirmlinkmsg()
    except TypeError: # invalid padding
      raise badconfirmlinkmsg()
      
    if self.computeMAC(plaintext) != mac:
      raise badconfirmlinkmsg()

    # A proper listvars is of the form
    # [ listname, padding ]
    listvars = plaintext.split("\x00")
    if len(listvars) == 2:
      listname = listvars[0]
    
      # reset password; else return error
      p = subprocess.Popen(('/usr/lib/mailman/bin/change_pw', '-l', listname),
                       stdout=subprocess.PIPE, stderr=subprocess.PIPE)
      retcode = p.wait()

      admins = ', '.join(self.get_admins(listname))
      if retcode is 0:
        # return success message
        output = p.stdout.read()
        mail('*****@*****.**', self.log_password_success_message % {
            'date' : Utils.formatdate(localtime = True),
            'messageid' : Utils.make_msgid(),
            'listname': listname,
            'listadmin': admins})

        return listname

      else:
        # non-standard problem -- e-mail systems/acctserv
        output = p.stdout.read()
        outerr = p.stderr.read()
        mail('*****@*****.**', self.unknown_mailman_password_error % {
            'date' : Utils.formatdate(localtime = True),
            'messageid' : Utils.make_msgid(),
            'listname' : listname,
            'listadmin' : admins,
            'output' : output,
            'outerr' : outerr })
        # return unknown error
        raise self.Fault('Internal error. The systems team has been notified '\
            'and will be getting back to you.')
          
    else: # User submitted bad hash
      raise badconfirmlinkmsg()
Ejemplo n.º 9
0
    def generate_head(self):
        for k in self.headdict.keys():
            v = self.headdict[k]
            newk = '-'.join(map(string.capitalize, k.lower().split('-')))

            if newk == 'Subject':
                self.msg[newk] = email.Header.Header(v, "UTF-8")
            elif newk == 'From':
                if type(v) == types.ListType:
                    self.msg[newk] = '"%s" <%s>' % (email.Header.Header(v[0], 'utf-8'), v[1])
                else:
                    self.msg[newk] = v
            elif newk == 'To':
                s = []
                for x in v:
                    if type(x) == types.ListType:
                        s.append('"%s" <%s>' % (email.Header.Header(x[0], 'utf-8'), x[1]))
                    else:
                        s.append(x)
                self.msg[newk] = '\r\n\t'.join(s)
            else:
                self.msg[newk] = v

        self.msg['Date'] = Utils.formatdate(localtime = 1)
        self.msg['Message-Id'] = Utils.make_msgid()
Ejemplo n.º 10
0
def process(mlist, msg, msgdata):
    # Short circuit if we've already calculated the recipients list,
    # regardless of whether the list is empty or not.
    if msgdata.has_key('recips'):
        return
    # Should the original sender should be included in the recipients list?
    include_sender = 1
    sender = msg.get_sender()
    try:
        if mlist.getMemberOption(sender, mm_cfg.DontReceiveOwnPosts):
            include_sender = 0
    except Errors.NotAMemberError:
        pass
    # Support for urgent messages, which bypasses digests and disabled
    # delivery and forces an immediate delivery to all members Right Now.  We
    # are specifically /not/ allowing the site admins password to work here
    # because we want to discourage the practice of sending the site admin
    # password through email in the clear. (see also Approve.py)
    missing = []
    password = msg.get('urgent', missing)
    if password is not missing:
        if mlist.Authenticate((mm_cfg.AuthListPoster,
                               mm_cfg.AuthListModerator,
                               mm_cfg.AuthListAdmin),
                              password):
            recips = mlist.getMemberCPAddresses(mlist.getRegularMemberKeys() +
                                                mlist.getDigestMemberKeys())
            msgdata['recips'] = recips
            return
        else:
            # Bad Urgent: password, so reject it instead of passing it on.  I
            # think it's better that the sender know they screwed up than to
            # deliver it normally.
            realname = mlist.real_name
            text = _("""\
Your urgent message to the %(realname)s mailing list was not authorized for
delivery.  The original message as received by Mailman is attached.
""")
            raise Errors.RejectMessage, Utils.wrap(text)
    # Calculate the regular recipients of the message
    recips = [mlist.getMemberCPAddress(m)
              for m in mlist.getRegularMemberKeys()
              if mlist.getDeliveryStatus(m) == ENABLED]
    # Remove the sender if they don't want to receive their own posts
    if not include_sender:
        try:
            recips.remove(mlist.getMemberCPAddress(sender))
        except (Errors.NotAMemberError, ValueError):
            # Sender does not want to get copies of their own messages (not
            # metoo), but delivery to their address is disabled (nomail).  Or
            # the sender is not a member of the mailing list.
            pass
    # Handle topic classifications
    do_topic_filters(mlist, msg, msgdata, recips)
    # Regular delivery exclude/include (if in/not_in To: or Cc:) lists
    recips = do_exclude(mlist, msg, msgdata, recips)
    recips = do_include(mlist, msg, msgdata, recips)
    # Bookkeeping
    msgdata['recips'] = recips
Ejemplo n.º 11
0
def getdate(msg):
    if not 'date' in msg:
        return None
    datehdr = msg['date'].strip()
    try:
        return Utils.mktime_tz(Utils.parsedate_tz(datehdr))
    except:
        return None
Ejemplo n.º 12
0
def _unquotevalue(value):
    # This is different than Utils.collapse_rfc2231_value() because it doesn't
    # try to convert the value to a unicode.  Message.get_param() and
    # Message.get_params() are both currently defined to return the tuple in
    # the face of RFC 2231 parameters.
    if isinstance(value, tuple):
        return value[0], value[1], Utils.unquote(value[2])
    else:
        return Utils.unquote(value)
Ejemplo n.º 13
0
    def notify(self, message = '', data = None, listener = None):
        if not data: data = {}

        # Extract all the settings from settings
        from_address = self.conf('from')
        to_address = self.conf('to')
        ssl = self.conf('ssl')
        smtp_server = self.conf('smtp_server')
        smtp_user = self.conf('smtp_user')
        smtp_pass = self.conf('smtp_pass')
        smtp_port = self.conf('smtp_port')
        starttls = self.conf('starttls')

        # Make the basic message
        message = MIMEText(toUnicode(message), _charset = Env.get('encoding'))
        message['Subject'] = self.default_title
        message['From'] = from_address
        message['To'] = to_address
        message['Date']     = Utils.formatdate(localtime = 1)
        message['Message-ID'] = Utils.make_msgid()

        try:
            # Open the SMTP connection, via SSL if requested
            log.debug("Connecting to host %s on port %s" % (smtp_server, smtp_port))
            log.debug("SMTP over SSL %s", ("enabled" if ssl == 1 else "disabled"))
            mailserver = smtplib.SMTP_SSL(smtp_server) if ssl == 1 else smtplib.SMTP(smtp_server)

            if (starttls):
                log.debug("Using StartTLS to initiate the connection with the SMTP server")
                mailserver.starttls()

            # Say hello to the server
            mailserver.ehlo()

            # Check too see if an login attempt should be attempted
            if len(smtp_user) > 0:
                log.debug("Logging on to SMTP server using username \'%s\'%s", (smtp_user, " and a password" if len(smtp_pass) > 0 else ""))
                mailserver.login(smtp_user, smtp_pass)

            # Send the e-mail
            log.debug("Sending the email")
            mailserver.sendmail(from_address, splitString(to_address), message.as_string())

            # Close the SMTP connection
            mailserver.quit()

            log.info('Email notification sent')

            return True
        except:
            log.error('E-mail failed: %s', traceback.format_exc())

        return False
Ejemplo n.º 14
0
def _formatparam(param, value = None, quote = True):
    if value is not None and len(value) > 0:
        if isinstance(value, tuple):
            param += '*'
            value = Utils.encode_rfc2231(value[2], value[0], value[1])
        if quote or tspecials.search(value):
            return '%s="%s"' % (param, Utils.quote(value))
        else:
            return '%s=%s' % (param, value)
    else:
        return param
    return
Ejemplo n.º 15
0
 def test_encode_header(self):
     eq = self.assertEqual
     s = 'this is some text'
     eq(Utils.encode(s), '=?iso-8859-1?q?this=20is=20some=20text?=')
     s = 'Keld_J\xf8rn_Simonsen'
     eq(Utils.encode(s), '=?iso-8859-1?q?Keld_J=F8rn_Simonsen?=')
     s1 = 'If you can read this yo'
     s2 = 'u understand the example.'
     eq(Utils.encode(s1, encoding='b'),
        '=?iso-8859-1?b?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=')
     eq(Utils.encode(s2, charset='iso-8859-2', encoding='b'),
        '=?iso-8859-2?b?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?=')
Ejemplo n.º 16
0
def getdate(msg):
    """Returns the date/time from msg in seconds-since-epoch, if possible.
    Otherwise, returns None."""

    if not 'date' in msg:
        # No Date header present.
        return None

    datehdr = msg['date'].strip()
    try:
        return Utils.mktime_tz(Utils.parsedate_tz(datehdr))
    except:
        # Some sort of error occured, likely because of an invalid date.
        return None
Ejemplo n.º 17
0
def CreateEmailTo(sender_name, sender_email, recipient, subject, body):
    mail = MIMEMultipart('alternative')
    mail['From'] = emailutils.formataddr((sender_name, sender_email))
    mail['To'] = recipient
    mail['Subject'] = Header(subject.encode('utf-8'), 'utf-8')
    mail['Message-Id'] = emailutils.make_msgid()
    mail['Date'] = emailutils.formatdate(localtime=True)
    mail.set_param('charset', 'utf-8')
    if isinstance(body, unicode):
        mail.attach(MIMEText(body.encode('utf-8'), 'plain', 'utf-8'))
    else:
        mail.attach(MIMEText(body))

    return mail
Ejemplo n.º 18
0
    def address_to_encoded_header(address):
        """RFC2047-encode an address if necessary.

        :param address: An unicode string, or UTF-8 byte string.
        :return: A possibly RFC2047-encoded string.
        """
        # Can't call Header over all the address, because that encodes both the
        # name and the email address, which is not permitted by RFCs.
        user, email = Utils.parseaddr(address)
        if not user:
            return email
        else:
            return Utils.formataddr((str(Header.Header(safe_unicode(user))),
                email))
Ejemplo n.º 19
0
 def test_iso_8859_1(self):
     eq = self.assertEqual
     s = '=?iso-8859-1?q?this=20is=20some=20text?='
     eq(Utils.decode(s), 'this is some text')
     s = '=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?='
     eq(Utils.decode(s), u'Keld_J\xf8rn_Simonsen')
     s = '=?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=' \
         '=?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?='
     eq(Utils.decode(s), 'If you can read this you understand the example.')
     s = '=?iso-8859-8?b?7eXs+SDv4SDp7Oj08A==?='
     eq(Utils.decode(s),
        u'\u05dd\u05d5\u05dc\u05e9 \u05df\u05d1 \u05d9\u05dc\u05d8\u05e4\u05e0')
     s = '=?iso-8859-1?q?this=20is?= =?iso-8859-1?q?some=20text?='
     eq(Utils.decode(s), u'this is some text')
    def get_payload(self, i=None, decode=False):
        """Return a reference to the payload.

        The payload will either be a list object or a string.  If you mutate
        the list object, you modify the message's payload in place.  Optional
        i returns that index into the payload.

        Optional decode is a flag indicating whether the payload should be
        decoded or not, according to the Content-Transfer-Encoding header
        (default is False).

        When True and the message is not a multipart, the payload will be
        decoded if this header's value is `quoted-printable' or `base64'.  If
        some other encoding is used, or the header is missing, or if the
        payload has bogus data (i.e. bogus base64 or uuencoded data), the
        payload is returned as-is.

        If the message is a multipart and the decode flag is True, then None
        is returned.
        """
        if i is None:
            payload = self._payload
        elif not isinstance(self._payload, ListType):
            raise TypeError, i
        else:
            payload = self._payload[i]
        if decode:
            if self.is_multipart():
                return None
            cte = self.get('content-transfer-encoding', '').lower()
            if cte == 'quoted-printable':
                return Utils._qdecode(payload)
            elif cte == 'base64':
                try:
                    return Utils._bdecode(payload)
                except binascii.Error:
                    # Incorrect padding
                    return payload
            elif cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
                sfp = StringIO()
                try:
                    uu.decode(StringIO(payload+'\n'), sfp)
                    payload = sfp.getvalue()
                except uu.Error:
                    # Some decoding problem
                    return payload
        # Everything else, including encodings with 8bit or 7bit are returned
        # unchanged.
        return payload
    def compose_mail(self):
        """
        Purpose: Compose the complete mail, including header and body
        Returns: The body as an MIMEText object
        """

        message_id = Utils.make_msgid()
        body = MIMEText(self.__message)
        body['Subject'] = '%s test mail from %s[%s]' % (self.__test, __file__, self.__local_hostname)
        body['Date'] = Utils.formatdate(localtime=1)
        body['From'] = self.__mail_from
        body['To'] = self.__rcpt_to
        body['Message-ID'] = message_id

        return body
Ejemplo n.º 22
0
def send_att_mail(sender,
                  to_list,
                  sub,
                  content,
                  att,
                  user=username,
                  passw=password):
    msg = MIMEMultipart()
    sender = getrealmailaddress(sender)[0]
    to_list = getrealmailaddress(to_list)
    msg['Subject'] = Header(sub, 'utf-8')
    msg['From'] = sender
    msg['To'] = ','.join(to_list)
    msg['Date'] = Utils.formatdate(localtime=1)
    print msg['Date']
    attachment_file = att
    att1 = MIMEText(open(attachment_file, 'rb').read(), 'base64', 'gb2312')
    att1["Content-Type"] = 'application/octet-stream'
    att1[
        "Content-Disposition"] = 'attachment; filename=' + attachment_file.split(
            "/")[-1]
    msg.attach(att1)
    # mail_context=MIMEText(content,'text','utf-8')
    mail_context = MIMEText(content, _subtype='plain', _charset='gb2312')
    msg.attach(mail_context)
    smtp = smtplib.SMTP()
    smtp.connect(smtp_server)
    smtp.login(user, passw)
    smtp.sendmail(sender, to_list, msg.as_string())
    smtp.quit
Ejemplo n.º 23
0
def send_mail(sender, receiver, subject, content, ctype="html", pics=(),
              smtpserver='mail.51ping.com',
              username="******", password="******"):
    """subject and body are unicode objects"""
    if ctype == "html":
        msg = MIMEText(content, 'html', 'utf-8')
    else:
        msg = MIMEText(content, 'plain', 'utf-8')

    if len(pics) != 0:
        msgRoot = MIMEMultipart('related')
        msgText = MIMEText(content, 'html', 'utf-8')
        msgRoot.attach(msgText)
        i = 1
        for pic in pics:
            fp = open(pic, "rb")
            image = MIMEImage(fp.read())
            fp.close()
            image.add_header('Content-ID', '<img%02d>' % i)
            msgRoot.attach(image)
            i += 1
        msg = msgRoot

    msg['Subject'] = Header(subject, 'utf-8')
    msg['From'] = sender
    msg['To'] = ';'.join(receiver)
    msg['Message-ID'] = Utils.make_msgid()
    msg['date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z')

    smtp = smtplib.SMTP()
    smtp.connect(smtpserver, 25)
    smtp.login(username, password)
    smtp.sendmail(sender, receiver, msg.as_string())
    smtp.quit()
Ejemplo n.º 24
0
def corrupt_message(why, fromlines=None, fromstring=None):
    log = getmailcore.logging.Logger()
    log.error('failed to parse retrieved message; constructing container for '
              'contents\n')
    if fromlines == fromstring == None:
        raise SystemExit('corrupt_message() called with wrong arguments')
    msg = email.message_from_string('')
    msg['From'] = '"unknown sender" <>'
    msg['Subject'] = 'Corrupt message received'
    msg['Date'] = Utils.formatdate(localtime=True)
    body = [
        b'A badly-corrupt message was retrieved and could not be parsed',
        b'for the following reason:',
        b'',
        b'    %s' % why,
        b'',
        b'Below the following line is the original message contents.',
        b'',
        b'--------------------------------------------------------------',
    ]
    if fromlines:
        body.extend([line.rstrip() for line in fromlines])
    elif fromstring:
        body.extend([line.rstrip() for line in fromstring.splitlines()])
    msg.set_payload(_NL.join(body))
    for attr in message_attributes:
        setattr(msg, attr, '')
    return msg
Ejemplo n.º 25
0
def testEmailAddresses(arr):
    for email in arr:
        print "\tEmail Address: ", email
        print "\t---------------------------------"

        #Strip any name information from email address
        email = Utils.parseaddr(email)[1]

        if isvalidEmailOne(email):
            print "\t\tisvalidEmailOne PASSED"
        else:
            print "\t\tisvalidEmailOne FAILED"

        if isvalidEmailTwo(email):
            print "\t\tisvalidEmailTwo PASSED"
        else:
            print "\t\tisvalidateEmailTwo FAILED"

        if isvalidEmailThree(email):
            print "\t\tisvalidateEmailThree PASSED"
        else:
            print "\t\tisvalidateEmailThree FAILED"

        if isvalidEmailFour(email):
            print "\t\tisvalidateEmailFour PASSED"
        else:
            print "\t\tisvalidateEmailFour FAILED"

        if isvalidEmailFive(email):
            print "\t\tisvalidateEmailFive PASSED"
        else:
            print "\t\tisvalidateEmailFive FAILED"

        print "\n"
Ejemplo n.º 26
0
def _mail_recipient(recipient_name, recipient_email,
        sender_name, sender_url, subject,
        body, headers={}):
    mail_from = config.get('ckan.mail_from')
    body = add_msg_niceties(recipient_name, body, sender_name, sender_url)
    msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8')
    for k, v in headers.items(): msg[k] = v
    subject = Header(subject.encode('utf-8'), 'utf-8')
    msg['Subject'] = subject
    msg['From'] = _("%s <%s>") % (sender_name, mail_from)
    recipient = u"%s <%s>" % (recipient_name, recipient_email)
    msg['To'] = Header(recipient, 'utf-8')
    msg['Date'] = Utils.formatdate(time())
    msg['X-Mailer'] = "CKAN %s" % __version__
    try:
        server = smtplib.SMTP(
            config.get('test_smtp_server',
                       config.get('smtp_server', 'localhost')))
        #server.set_debuglevel(1)
        server.sendmail(mail_from, [recipient_email], msg.as_string())
        server.quit()
    except Exception, e:
        msg = '%r' % e
        log.exception(msg)
        raise MailerException(msg)
Ejemplo n.º 27
0
    def send_txt(self, filename):
        # 这里发送附件尤其要注意字符编码,当时调试了挺久的,因为收到的文件总是乱码
        self.smtp = smtplib.SMTP()
        self.smtp.connect(self.server)
        self.smtp.login(self.username, self.password)
        self.msg = MIMEMultipart()
        self.msg['to'] = self.to_mail
        self.msg['from'] = self.from_mail
        self.msg['Subject'] = "Convert"
        self.filename = filename + ".txt"
        self.msg['Date'] = Utils.formatdate(localtime=1)
        content = open(self.filename.decode('utf-8'), 'rb').read()
        # print content
        self.att = MIMEText(content, 'base64', 'utf-8')
        self.att['Content-Type'] = 'application/octet-stream'
        # self.att["Content-Disposition"] = "attachment;filename=\"%s\"" %(self.filename.encode('gb2312'))
        self.att[
            "Content-Disposition"] = "attachment;filename=\"%s\"" % Header(
                self.filename, 'gb2312')
        # print self.att["Content-Disposition"]
        self.msg.attach(self.att)

        self.smtp.sendmail(self.msg['from'], self.msg['to'],
                           self.msg.as_string())
        self.smtp.quit()
Ejemplo n.º 28
0
    def send_txt(self, name, price, percent, status):
        if 'up' == status:
            content = '%s > %.2f , %.2f' % (name, price, percent)
        if 'down' == status:
            content = '%s < %.2f , %.2f' % (name, price, percent)

        content = content + '%'
        print content
        subject = '%s' % name
        self.msg = MIMEText(content, 'plain', 'utf-8')
        self.msg['to'] = self.to_mail
        self.msg['from'] = self.from_mail
        self.msg['Subject'] = subject
        self.msg['Date'] = Utils.formatdate(localtime=1)
        try:

            self.smtp = smtplib.SMTP_SSL(port=465)
            self.smtp.connect(self.server)
            self.smtp.login(self.username, self.password)
            self.smtp.sendmail(self.msg['from'], self.msg['to'],
                               self.msg.as_string())
            self.smtp.quit()
            print "sent"
        except smtplib.SMTPException, e:
            print e
            return 0
def sendMail(body,targetName,targetEmail,targetName2,targetEmail2,dataset):
    print "Sending email!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
    #targetEmail = "*****@*****.**"
    #targetEmail2 = "*****@*****.**"
    mail_from = '*****@*****.**'
    body = add_msg_niceties(targetName, body, "ILRI Datasets Portal", "http://data.ilri.org/portal")
    msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8')
    ssubject = "The dataset " + '"' + dataset + '"' + " will be made available in next two weeks"
    subject = Header(ssubject.encode('utf-8'), 'utf-8')
    msg['Subject'] = subject
    msg['From'] = u"%s <%s>" % ("CKAN Portal", mail_from)
    recipient = u"%s <%s>" % (targetName, targetEmail) + "," + u"%s <%s>" % (targetName2, targetEmail2)
    msg['To'] = Header(recipient, 'utf-8')
    msg['Date'] = Utils.formatdate(time())

    try:

        smtp_server = 'smtp.office365.com'
        smtp_user = '******'
        smtp_password = '******'

        server = smtplib.SMTP(smtp_server,587)
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(smtp_user, smtp_password)
        server.sendmail(mail_from, [targetEmail,targetEmail2], msg.as_string())
        server.quit()
        print("Email sent to " + targetEmail + " and " + targetEmail2)

    except Exception,e:
        print str(e)
        print("Sendmail error: " + str(e))
Ejemplo n.º 30
0
    def configure_sender(self, sender):
        """Properly formats the sender address.

        :param sender: A dictionary containing information about the sender.

        """
        return Utils.formataddr((sender['real_name'], sender['address']))
Ejemplo n.º 31
0
    def message(address):

        body = """
Dear Editor,

the author {user} has uploaded replication files to your journal's data archive.\n

{submission_id}

You can review it here:\n\n\t {url}

best regards from ZBW--Journal Data Archive

"""
        d = {
            'user': author,
            'url': package_url(dataset),
            'submission_id': subid()
        }
        body = body.format(**d)
        msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8')
        msg['Subject'] = Header(
            u"ZBW Journal Data Archive: Review Notification")
        msg['From'] = config.get('smtp.mail_from')
        msg['To'] = Header(address, 'utf-8')
        msg['Date'] = Utils.formatdate(time())
        msg['X-Mailer'] = "CKAN {} [Plugin edawax]".format(ckan_version)
        return msg
Ejemplo n.º 32
0
def send_mail(sender, to_list, sub, content, user, passw):

    msg = MIMEText(content, _subtype='plain', _charset='gb2312')

    msg['Subject'] = Header(sub, 'utf-8')

    msg['From'] = sender

    msg['To'] = to_list

    msg['Date'] = Utils.formatdate(localtime=1)

    print msg['Date']

    smtp = smtplib.SMTP()

    smtp.connect(smtp_server)

    smtp.login(user, passw)

    for recipient in to_list.split(','):

        smtp.sendmail(sender, recipient, msg.as_string())

    smtp.quit
Ejemplo n.º 33
0
    def get_boundary(self, failobj=None):
        missing = object()
        boundary = self.get_param('boundary', missing)
        if boundary is missing:
            return failobj

        return Utils.collapse_rfc2231_value(boundary).rstrip()
Ejemplo n.º 34
0
    def get_filename(self, failobj=None):
        missing = object()
        filename = self.get_param('filename', missing, 'content-disposition')
        if filename is missing:
            return failobj

        return Utils.collapse_rfc2231_value(filename).strip()
Ejemplo n.º 35
0
def _mail_recipient(recipient_name,
                    recipient_email,
                    sender_name,
                    sender_url,
                    subject,
                    body,
                    headers={}):
    mail_from = config.get('ckan.mail_from')
    body = add_msg_niceties(recipient_name, body, sender_name, sender_url)
    msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8')
    for k, v in headers.items():
        msg[k] = v
    subject = Header(subject.encode('utf-8'), 'utf-8')
    msg['Subject'] = subject
    msg['From'] = _("%s <%s>") % (sender_name, mail_from)
    recipient = u"%s <%s>" % (recipient_name, recipient_email)
    msg['To'] = Header(recipient, 'utf-8')
    msg['Date'] = Utils.formatdate(time())
    msg['X-Mailer'] = "CKAN %s" % __version__
    try:
        server = smtplib.SMTP(
            config.get('test_smtp_server',
                       config.get('smtp_server', 'localhost')))
        #server.set_debuglevel(1)
        server.sendmail(mail_from, [recipient_email], msg.as_string())
        server.quit()
    except Exception, e:
        msg = '%r' % e
        log.exception(msg)
        raise MailerException(msg)
def sendTokenRequestMail(body, targetName, targetEmail):
    #print "IN sendTokenRequestMail********************"
    #targetEmail = "*****@*****.**"
    #targetEmail2 = "*****@*****.**"
    mail_from = config.get('smtp.mail_from')
    body = add_msg_niceties(targetName, body, "ILRI Datasets Portal",
                            "http://data.ilri.org/portal")
    msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8')
    ssubject = "Your application for confidential information at http://data.ilri.org/portal"
    subject = Header(ssubject.encode('utf-8'), 'utf-8')
    msg['Subject'] = subject
    msg['From'] = _("%s <%s>") % ("CKAN Portal", mail_from)
    recipient = u"%s <%s>" % (targetName, targetEmail)
    msg['To'] = Header(recipient, 'utf-8')
    msg['Date'] = Utils.formatdate(time())

    try:
        smtp_server = config.get('smtp.server', 'localhost')
        smtp_user = config.get('smtp.user')
        smtp_password = config.get('smtp.password')

        server = smtplib.SMTP(smtp_server, 587)
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(smtp_user, smtp_password)
        server.sendmail(mail_from, [targetEmail], msg.as_string())
        server.quit()
        logging.debug("Token Email sent to " + targetEmail)
    except Exception, e:
        print str(e)
        logging.debug("Token Sendmail error: " + str(e))
Ejemplo n.º 37
0
def send_mail(from_user, to_user, cc_users, subject, text, attach):
    COMMASPACE = ", "
    msg = MIMEMultipart("alternative")
    msg["From"] = from_user
    msg["To"] = to_user
    msg["Cc"] = COMMASPACE.join(cc_users)
    msg["Subject"] = Header(s=subject, charset="utf-8")
    msg["Date"] = Utils.formatdate(localtime=1)
    msg.attach(MIMEText(text, "html", _charset="utf-8"))

    if (attach != None):
        part = MIMEBase("application", "octet-stream")
        part.set_payload(open(attach, "rb").read())
        Encoders.encode_base64(part)
        part.add_header(
            "Content-Disposition",
            "attachment; filename=\"%s\"" % os.path.basename(attach))
        msg.attach(part)

    smtp = smtplib.SMTP(smtp_server, port)
    smtp.ehlo()
    smtp.starttls()
    smtp.login(userid, passwd)
    smtp.sendmail(from_user, cc_users, msg.as_string())
    smtp.close()
Ejemplo n.º 38
0
def _mail_recipient(recipient_name, recipient_email,
        sender_name, sender_url, subject,
        body, headers={}):
    mail_from = config.get('smtp.mail_from')
    body = add_msg_niceties(recipient_name, body, sender_name, sender_url)
    msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8')
    for k, v in headers.items(): msg[k] = v
    subject = Header(subject.encode('utf-8'), 'utf-8')
    msg['Subject'] = subject
    msg['From'] = _("%s <%s>") % (sender_name, mail_from)
    recipient = u"%s <%s>" % (recipient_name, recipient_email)
    msg['To'] = Header(recipient, 'utf-8')
    msg['Date'] = Utils.formatdate(time())
    msg['X-Mailer'] = "CKAN %s" % __version__

    # Send the email using Python's smtplib.
    smtp_connection = smtplib.SMTP()
    if 'smtp.test_server' in config:
        # If 'smtp.test_server' is configured we assume we're running tests,
        # and don't use the smtp.server, starttls, user, password etc. options.
        smtp_server = config['smtp.test_server']
        smtp_starttls = False
        smtp_user = None
        smtp_password = None
    else:
        smtp_server = config.get('smtp.server', 'localhost')
        smtp_starttls = paste.deploy.converters.asbool(
                config.get('smtp.starttls'))
        smtp_user = config.get('smtp.user')
        smtp_password = config.get('smtp.password')
    smtp_connection.connect(smtp_server)
    try:
        #smtp_connection.set_debuglevel(True)

        # Identify ourselves and prompt the server for supported features.
        smtp_connection.ehlo()

        # If 'smtp.starttls' is on in CKAN config, try to put the SMTP
        # connection into TLS mode.
        if smtp_starttls:
            if smtp_connection.has_extn('STARTTLS'):
                smtp_connection.starttls()
                # Re-identify ourselves over TLS connection.
                smtp_connection.ehlo()
            else:
                raise MailerException("SMTP server does not support STARTTLS")

        # If 'smtp.user' is in CKAN config, try to login to SMTP server.
        if smtp_user:
            assert smtp_password, ("If smtp.user is configured then "
                    "smtp.password must be configured as well.")
            smtp_connection.login(smtp_user, smtp_password)

        smtp_connection.sendmail(mail_from, [recipient_email], msg.as_string())
        log.info("Sent email to {0}".format(recipient_email))

    except smtplib.SMTPException, e:
        msg = '%r' % e
        log.exception(msg)
        raise MailerException(msg)
Ejemplo n.º 39
0
    def send_email(self, from_address, to_addresses, cc_addresses, bcc_addresses, subject, body):
        """
        Send an email

        Args:
            to_addresses: must be a list
            cc_addresses: must be a list
            bcc_addresses: must be a list
        """
        try:
            # Note: need Python 2.6.3 or more
            conn = SMTP_SSL(self.smtp_host, self.smtp_port)
            conn.login(self.user, self.password)
            msg = MIMEText(body, 'plain', self.email_default_encoding)
            msg['Subject'] = Header(subject, self.email_default_encoding)
            msg['From'] = from_address
            msg['To'] = ', '.join(to_addresses)
            if cc_addresses:
                msg['CC'] = ', '.join(cc_addresses)
            if bcc_addresses:
                msg['BCC'] = ', '.join(bcc_addresses)
            msg['Date'] = Utils.formatdate(localtime=True)
            # TODO: Attached file
            conn.sendmail(from_address, to_addresses, msg.as_string())
        except:
            raise
        finally:
            conn.close()
Ejemplo n.º 40
0
def main():
    """Shows basic usage of the Google Admin-SDK Groups Migration API.

    Creates a Google Admin-SDK Groups Migration API service object and
    inserts a test email into a group.
    """
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('groupsmigration', 'v1', http=http)

    print('Warning: A test email will be inserted into the group entered.')
    groupId = raw_input(
        'Enter the email address of a Google Group in your domain: ')

    # Format an RFC822 message
    message = MIMEText.MIMEText('This is a test.')
    # Generate a random 10 digit number for message Id.
    message['Message-ID'] = '<{0}-{1}>'.format(str(random.randrange(10**10)),
                                               groupId)
    message['Subject'] = 'Groups Migration API Test (Python)'
    message['From'] = '"Alice Smith" <*****@*****.**>'
    message['To'] = groupId
    message['Date'] = Utils.formatdate(localtime=True)

    stream = StringIO.StringIO()
    stream.write(message.as_string())
    media = apiclient.http.MediaIoBaseUpload(stream, mimetype='message/rfc822')

    result = service.archive().insert(groupId=groupId,
                                      media_body=media).execute()
    print(result['responseCode'])
Ejemplo n.º 41
0
 def test_iso_8859_1(self):
     eq = self.assertEqual
     s = '=?iso-8859-1?q?this=20is=20some=20text?='
     eq(Utils.decode(s), 'this is some text')
     s = '=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?='
     eq(Utils.decode(s), u'Keld_J\xf8rn_Simonsen')
     s = '=?ISO-8859-1?B?SWYgeW91IGNhbiByZWFkIHRoaXMgeW8=?=' \
         '=?ISO-8859-2?B?dSB1bmRlcnN0YW5kIHRoZSBleGFtcGxlLg==?='
     eq(Utils.decode(s), 'If you can read this you understand the example.')
     s = '=?iso-8859-8?b?7eXs+SDv4SDp7Oj08A==?='
     eq(
         Utils.decode(s),
         u'\u05dd\u05d5\u05dc\u05e9 \u05df\u05d1 \u05d9\u05dc\u05d8\u05e4\u05e0'
     )
     s = '=?iso-8859-1?q?this=20is?= =?iso-8859-1?q?some=20text?='
     eq(Utils.decode(s), u'this is some text')
Ejemplo n.º 42
0
def mail_recipient(recipient_name,
                   recipient_email,
                   subject,
                   body,
                   headers=None):
    mail_from = config.get('openspending.mail_from',
                           '*****@*****.**')
    body = add_msg_niceties(recipient_name, body, app_globals.site_title)
    msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8')
    if headers:
        msg.update(headers)
    subject = Header(subject.encode('utf-8'), 'utf-8')
    msg['Subject'] = subject
    msg['From'] = _("%s <%s>") % (app_globals.site_title, mail_from)
    recipient = u"%s <%s>" % (recipient_name, recipient_email)
    msg['To'] = Header(recipient, 'utf-8')
    msg['Date'] = Utils.formatdate(time())
    msg['X-Mailer'] = "OpenSpending"
    try:
        server = smtplib.SMTP(config.get('smtp_server', 'localhost'))
        server.sendmail(mail_from, [recipient_email], msg.as_string())
        server.quit()
    except Exception as e:
        msg = '%r' % e
        log.exception(msg)
        raise MailerException(msg)
Ejemplo n.º 43
0
	def SendMail(self, subject, text):
		COMMASPACE = ", "

		from_user = '******'
		to_user = COMMASPACE.join(MAIL_ID_LIST)
#		cc_users = '*****@*****.**'
		cc_users = '*****@*****.**'
#		sender = 'ivms'
		attach = ''
		msg = MIMEMultipart("alternative")
		msg["From"] = from_user
#		msg['From'] = '=?euc-kr?B?' + base64.standard_b64encode(sender) + '?=' + '<' + from_user + '>'
		msg["To"] = to_user
#		msg["Cc"] = cc_users
		msg["Subject"] = Header(s=subject, charset="euc-kr")
#		msg["Subject"] = '=?euc-kr?B?' + base64.standard_b64encode(subject) + '?='
		msg["Date"] = Utils.formatdate(localtime = 1)
#		msg.attach(MIMEText(text, _subtype='html', _charset='euc-kr'))
		msg.attach(MIMEText(text, _charset='euc-kr'))

#		if (attach != None):
#			part = MIMEBase("application", "octet-stream")
#			part.set_payload(open(attach, "rb").read())
#			Encoders.encode_base64(part)
#			part.add_header("Content-Disposition", "attachment; filename=\"%s\"" % os.path.basename(attach))
#			msg.attach(part)

		smtp = smtplib.SMTP(smtp_server, port)
		smtp.login(userid, passwd)
#		smtp.sendmail(from_user, cc_users, msg.as_string())
		smtp.sendmail(from_user, MAIL_ID_LIST, msg.as_string())
		smtp.close()
Ejemplo n.º 44
0
def _mail_recipient(recipient_name, recipient_email,
        sender_name, sender_url, subject,
        body, headers={}):
    mail_from = config.get('smtp.mail_from')
    body = add_msg_niceties(recipient_name, body, sender_name, sender_url)
    msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8')
    for k, v in headers.items(): msg[k] = v
    subject = Header(subject.encode('utf-8'), 'utf-8')
    msg['Subject'] = subject
    msg['From'] = _("%s <%s>") % (sender_name, mail_from)
    recipient = u"%s <%s>" % (recipient_name, recipient_email)
    msg['To'] = Header(recipient, 'utf-8')
    msg['Date'] = Utils.formatdate(time())
    msg['X-Mailer'] = "CKAN %s" % ckan.__version__

    # Send the email using Python's smtplib.
    smtp_connection = smtplib.SMTP()
    if 'smtp.test_server' in config:
        # If 'smtp.test_server' is configured we assume we're running tests,
        # and don't use the smtp.server, starttls, user, password etc. options.
        smtp_server = config['smtp.test_server']
        smtp_starttls = False
        smtp_user = None
        smtp_password = None
    else:
        smtp_server = config.get('smtp.server', 'localhost')
        smtp_starttls = paste.deploy.converters.asbool(
                config.get('smtp.starttls'))
        smtp_user = config.get('smtp.user')
        smtp_password = config.get('smtp.password')
    smtp_connection.connect(smtp_server)
    try:
        #smtp_connection.set_debuglevel(True)

        # Identify ourselves and prompt the server for supported features.
        smtp_connection.ehlo()

        # If 'smtp.starttls' is on in CKAN config, try to put the SMTP
        # connection into TLS mode.
        if smtp_starttls:
            if smtp_connection.has_extn('STARTTLS'):
                smtp_connection.starttls()
                # Re-identify ourselves over TLS connection.
                smtp_connection.ehlo()
            else:
                raise MailerException("SMTP server does not support STARTTLS")

        # If 'smtp.user' is in CKAN config, try to login to SMTP server.
        if smtp_user:
            assert smtp_password, ("If smtp.user is configured then "
                    "smtp.password must be configured as well.")
            smtp_connection.login(smtp_user, smtp_password)

        smtp_connection.sendmail(mail_from, [recipient_email], msg.as_string())
        log.info("Sent email to {0}".format(recipient_email))

    except smtplib.SMTPException, e:
        msg = '%r' % e
        log.exception(msg)
        raise MailerException(msg)
Ejemplo n.º 45
0
def sendTokenRequestMail(body):

    mail_from = config.get('smtp.mail_from')
    body = add_msg_niceties("Carlos", body, "CKAN Portal", "http://data.ilri.org/portal")
    msg = MIMEText(body.encode('utf-8'), 'plain', 'utf-8')
    ssubject = "New token request"
    subject = Header(ssubject.encode('utf-8'), 'utf-8')
    msg['Subject'] = subject
    msg['From'] = _("%s <%s>") % ("CKAN Portal", mail_from)
    recipient = u"%s <%s>" % ("Carlos Quiros", "*****@*****.**")
    msg['To'] = Header(recipient, 'utf-8')
    msg['Date'] = Utils.formatdate(time())

    try:
        smtp_connection = smtplib.SMTP()
        smtp_server = config.get('smtp.server', 'localhost')
        smtp_user = config.get('smtp.user')
        smtp_password = config.get('smtp.password')

        smtp_connection.connect(smtp_server)
        smtp_connection.login(smtp_user, smtp_password)
        smtp_connection.sendmail(mail_from, ["*****@*****.**"], msg.as_string())
        logging.info("Token Email sent to [email protected]")

    except Exception,e:
        logging.info("Token Sendmail error: " + str(e))
Ejemplo n.º 46
0
def main():
    """Shows basic usage of the Google Admin-SDK Groups Migration API.

    Creates a Google Admin-SDK Groups Migration API service object and
    inserts a test email into a group.
    """
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('groupsmigration', 'v1', http=http)

    print('Warning: A test email will be inserted into the group entered.')
    groupId = raw_input(
        'Enter the email address of a Google Group in your domain: ')

    # Format an RFC822 message
    message = MIMEText.MIMEText('This is a test.')
    # Generate a random 10 digit number for message Id.
    message['Message-ID'] = '<{0}-{1}>'.format(str(random.randrange(10**10)),
                                               groupId)
    message['Subject'] = 'Groups Migration API Test (Python)'
    message['From'] = '"Alice Smith" <*****@*****.**>'
    message['To'] = groupId
    message['Date'] = Utils.formatdate(localtime=True)

    stream = StringIO.StringIO()
    stream.write(message.as_string())
    media = apiclient.http.MediaIoBaseUpload(stream,
                                             mimetype='message/rfc822')

    result = service.archive().insert(groupId=groupId,
                                      media_body=media).execute()
    print(result['responseCode'])
Ejemplo n.º 47
0
 def create_data(self):
     self.msg = MIMEText('this is a test email,please ingored it.')
     self.msg['Subject'] = 'python smtplib'
     self.msg['To'] = ','.join(self.toaddr)
     self.msg['From'] = self.fromaddr
     self.msg['Reply_To'] = self.fromaddr
     self.msg['Message_ID'] = Utils.make_msgid().replace("@", "__Rex@")
Ejemplo n.º 48
0
def prepare(
    message,
    from_name,
    from_email,
    to=[],
    cc=[],
    bcc=[],
    subject='(no subject)',
):
    if not to and not cc and not bcc:
        raise MailError("No recipients specified")
    message['From'] = Utils.formataddr((from_name, from_email))
    message['Subject'] = subject
    if isinstance(to, (unicode, str)):
        to = [to]
    if to:
        message['To'] = ', '.join(to)
    if isinstance(cc, (unicode, str)):
        cc = [cc]
    if cc:
        message['Cc'] = ', '.join(cc)
    if isinstance(bcc, (unicode, str)):
        bcc = [bcc]
    if bcc:
        message['Bcc'] = ', '.join(bcc)
    return message
 def send_email(self, from_address, to_addresses, cc_addresses,
                bcc_addresses, subject, body):
     """
     Send an email
     Args:
         to_addresses: must be a list
         cc_addresses: must be a list
         bcc_addresses: must be a list
     """
     try:
         # Note: need Python 2.6.3 or more
         conn = SMTP_SSL(self.smtp_host, self.smtp_port)
         conn.login(self.user, self.password)
         msg = MIMEText(body, 'plain', self.email_default_encoding)
         msg['Subject'] = Header(subject, self.email_default_encoding)
         msg['From'] = from_address
         msg['To'] = ', '.join(to_addresses)
         if cc_addresses:
             msg['CC'] = ', '.join(cc_addresses)
         if bcc_addresses:
             msg['BCC'] = ', '.join(bcc_addresses)
         msg['Date'] = Utils.formatdate(localtime=True)
         # TODO: Attached file
         conn.sendmail(from_address, to_addresses, msg.as_string())
     except:
         raise
     finally:
         conn.close()
Ejemplo n.º 50
0
    def send_email(self, subject, content, attachment):
        # Create a root container
        main_msg = MIMEMultipart('alternative')
        # Create a text container to show the contents of the email
        text_msg = MIMEText(content, 'plain', 'utf-8')

        # Attach the contents
        main_msg.attach(text_msg)
        contype = 'application/octet-stream'
        maintype, subtype = contype.split('/', 1)
        # Create attachment
        att = open(attachment, 'rb')
        att_msg = MIMEBase(maintype, subtype)
        # Read the contents of the attachment and format it
        att_msg.set_payload(att.read())
        att.close()
        encoders.encode_base64(att_msg)
        # Add the header for attachment
        att_msg.add_header('Content-Disposition',
                           'attachment',
                           filename=attachment.split('\\')[-1])
        main_msg.attach(att_msg)
        # Set the attibutes for the root container
        main_msg['Subject'] = subject
        main_msg['From'] = self.mail_from
        main_msg['To'] = ','.join(self.mail_to)
        main_msg['Cc'] = ','.join(self.mail_cc)
        main_msg['Date'] = Utils.formatdate()

        server = smtplib.SMTP()
        server.connect(self.mail_host)
        server.sendmail(self.mail_from, self.mail_to + self.mail_cc,
                        main_msg.as_string())
        server.quit()
Ejemplo n.º 51
0
    def send_email_notification(self, title, number):
        """
        This function sends an email using Gmail SMTP Server to any email with a message telling that
        the manga has been sent to the kindle cloud.

        Keyword arguments:
        title - The title of the manga
        number - The chapter number of the manga
        """
        msg = MIMEMultipart.MIMEMultipart()
        msg['from'] = "*****@*****.**"
        msg['To'] = "*****@*****.**"
        msg['Date'] = Utils.formatdate(localtime=True)
        msg['Subject'] = 'Manga %s %s notification' % (title, number)

        msg.attach(
            MIMEText.MIMEText(
                'The chapter number %s of manga %s has been sent to '
                'the kindle cloud' % (number, title)))

        smtp = smtplib.SMTP("smtp.gmail.com", 587)
        smtp.ehlo()
        smtp.starttls()
        smtp.login("*****@*****.**", "xxxpasswordxxx")
        smtp.sendmail("*****@*****.**", "*****@*****.**", msg.as_string())
        smtp.close()
Ejemplo n.º 52
0
    def configure_sender(self, sender):
        """Properly formats the sender address.

        :param sender: A dictionary containing information about the sender.

        """
        return Utils.formataddr((sender['real_name'], sender['address']))
Ejemplo n.º 53
0
    def __SetBySmtp(self):
        if len(self.__charset) == 0:
            raise Exception(-1, "empty Character Set of SendMail")
        COMMASPACE = ", "
        msg = MIMEMultipart("alternative")
        msg["From"] = self.__str_from
        msg["To"] = COMMASPACE.join(self.__list_to)
        msg["Subject"] = Header(s=self.__str_title, charset=self.__charset)
        msg["Date"] = Utils.formatdate(localtime=1)
        msg.attach(MIMEText(self.__str_text, "html", _charset=self.__charset))
        if len(self.__list_file) > 0:
            for target in self.__list_file:
                part = MIMEBase("application", "octet-stream")
                part.set_payload(open(target, "rb").read())
                Encoders.encode_base64(part)

                # RFC 2047 방식을 이용한 한글파일명 파일전송
                file_target = '=?utf-8?b?' + base64.b64encode(
                    os.path.basename(target)) + '?='
                part.add_header("Content-Disposition",
                                "attachment; filename=\"%s\"" % file_target)
                msg.attach(part)

                # RFC 2231 방식. 추후개발.(현재 오류있음)
                '''
                file_target = "UTF-8''\""+urllib.quote(os.path.basename(target))+"\""
                #part.add_header("Content-Transfer-Encoding", "base64")
                part.add_header("Content-Disposition", "attachment; filename*=%s" % file_target)
                msg.attach(part)
                '''
        return msg
Ejemplo n.º 54
0
    def send_txt(self, name, price, percent, status):
        if 'up' == status:
            content = '%s > %.2f , %.2f' % (name, price, percent)
        if 'down' == status:
            content = '%s < %.2f , %.2f' % (name, price, percent)

        content = content + '%'
        print(content)
        subject = '%s' % name
        self.msg = MIMEText(content, 'plain', 'utf-8')
        self.msg['to'] = self.to_mail
        self.msg['from'] = self.from_mail
        self.msg['Subject'] = subject
        self.msg['Date'] = Utils.formatdate(localtime=1)
        try:

            self.smtp = smtplib.SMTP_SSL(port=465)
            self.smtp.connect(self.server)
            self.smtp.login(self.username, self.password)
            self.smtp.sendmail(self.msg['from'], self.msg['to'], self.msg.as_string())
            self.smtp.quit()
            print("sent")
        except smtplib.SMTPException, e:
            print(e)
            return 0
def testEmailAddresses(arr):
    for email in arr:
        print "\tEmail Address: ", email
        print "\t---------------------------------"

        #Strip any name information from email address
        email = Utils.parseaddr(email)[1]

        if isvalidEmailOne(email):
            print "\t\tisvalidEmailOne PASSED"
        else:
            print "\t\tisvalidEmailOne FAILED"

        if isvalidEmailTwo(email):
            print "\t\tisvalidEmailTwo PASSED"
        else:
            print "\t\tisvalidateEmailTwo FAILED"

        if isvalidEmailThree(email):
            print "\t\tisvalidateEmailThree PASSED"
        else:
            print "\t\tisvalidateEmailThree FAILED"

        if isvalidEmailFour(email):
            print "\t\tisvalidateEmailFour PASSED"
        else:
            print "\t\tisvalidateEmailFour FAILED"

        if isvalidEmailFive(email):
            print "\t\tisvalidateEmailFive PASSED"
        else:
            print "\t\tisvalidateEmailFive FAILED"

        print "\n"
Ejemplo n.º 56
0
    def send_manga_throw_email(self, title, number):
        """
        This function sends an email using Gmail SMTP Server to the kindle cloud with the
        comic attached into it.

        Keyword arguments:
        title - The title of the manga
        number - The chapter number of the manga
        """
        msg = MIMEMultipart.MIMEMultipart()
        msg['from'] = "*****@*****.**"
        msg['To'] = "*****@*****.**"
        msg['Date'] = Utils.formatdate(localtime=True)
        msg['Subject'] = ''

        msg.attach(MIMEText.MIMEText(''))

        part = MIMEBase.MIMEBase('application', "octet-stream")
        filename = title + "_" + str(number) + ".mobi"
        part.set_payload(open(filename, "rb").read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment', filename=filename)
        msg.attach(part)

        smtp = smtplib.SMTP("smtp.gmail.com", 587)
        smtp.ehlo()
        smtp.starttls()
        smtp.login("*****@*****.**", "xxxpasswordxxx")
        smtp.sendmail("*****@*****.**", "*****@*****.**", msg.as_string())
        smtp.close()
Ejemplo n.º 57
0
    def send_txt(self, name, real_price,price, percent, status):
        if 'up' == status:
#            content = 'stock name:%s current price: %.2f higher than price up:%.2f , ratio:%.2f' % (name, real_price,price, percent)
             content = '证券名称:%s 当前价格: %.2f 高于 定价模型上限价格:%.2f , 可卖出 预计盈利率:%.2f' %(name, real_price,price, percent+15)
        if 'down' == status:
#            content = 'stock name:%s current price: %.2f lower than price down:%.2f , 盈利率:%.2f' % (name, real_price,price, percent)
             content = '证券名称:%s 当前价格: %.2f 低于 定价模型下限价格:%.2f , 可买入 预计盈利率:%.2f' %(name, real_price,price, percent+15)
        content = content + '%'
        print content
        subject = '%s' % name
        self.msg = MIMEText(content, 'plain', 'utf-8')
        self.msg['to'] = self.to_mail
        self.msg['from'] = self.from_mail
        self.msg['Subject'] = subject
        self.msg['Date'] = Utils.formatdate(localtime=1)
        try:

            self.smtp = smtplib.SMTP_SSL(port=465)
            self.smtp.connect(self.server)
            self.smtp.login(self.username, self.password)
            self.smtp.sendmail(self.msg['from'], self.msg['to'], self.msg.as_string())
            self.smtp.quit()
            print "sent"
        except smtplib.SMTPException, e:
            print e
            return 0
Ejemplo n.º 58
0
def sendMail():
	sender = '*****@*****.**'  
	receiver = ['*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**']
	# receiver = ['*****@*****.**']
	smtpserver = 'mail.epcare.com.cn'  
	username = '******'  
	password = '******'  
	yestoday = date.today() - timedelta(hours=24);
	msgRoot = MIMEMultipart('related') 
	msgRoot['Subject'] = '每日域报告'
	msgRoot['From'] = sender
	msgRoot['To'] = ';'.join(receiver)
	msgRoot["Date"] = Utils.formatdate(localtime = 1)
	  
	#文本内容
	html = '''
	<html>
	    <head><head>
	    <body>
	        <p>Hi, all<br>
	            <br>
	            &nbsp;&nbsp;&nbsp;&nbsp;以上是昨天各个域的发送情况,详看附件!<br>
	            <br>
	            顺祝工作愉快!<br>
	            <br>
	            <img src="cid:image1">
	        </p>
	    </body>
	</html>
	'''
	msgText = MIMEText(html, 'html', 'utf-8')
	msgRoot.attach(msgText)
	fp = open('D:\\me.jpg', 'rb')
	msgImage = MIMEImage(fp.read())
	fp.close()
	msgImage.add_header('Content-ID', '<image1>')
	msgRoot.attach(msgImage)

	#构造附件  
	the_dir = 'C:\\Users\\zhang\\Desktop\\%s\\' % yestoday
	if os.path.exists(the_dir) :
	    os.chdir('%s' % (the_dir))
	else:
	    print 'no %s' % the_dir
	    sys.exit() 

	for dirfile in os.listdir(the_dir):
	    if os.path.isfile(dirfile):
	        csvfile = open(dirfile, 'rb')
	        att = MIMEText(csvfile.read(), 'base64', 'utf-8')  
	        csvfile.close()
	        att["Content-Type"] = 'application/octet-stream'  
	        att["Content-Disposition"] = 'attachment; filename="%s"'  % dirfile
	        msgRoot.attach(att)  
	          
	smtp = smtplib.SMTP()  
	smtp.connect(smtpserver)  
	smtp.login(username, password)  
	smtp.sendmail(sender, receiver, msgRoot.as_string())  
	smtp.quit()
def timehandler(rawtime):
    timeinput = re.split('[\s:-]', rawtime)
    timeinput.insert(2, year)
    t1 = ' '.join(timeinput)
    timeobject = time.strptime(t1, "%d %b %Y %H %M")
    unixtime = time.mktime(timeobject)
    date = Utils.formatdate(unixtime)
    return unixtime, date
Ejemplo n.º 60
0
    def __make_header(self):
        # Header
        # self.message['Message-Id'] = Header(self.__make_msgid(), self.character)
        self.message['Message-Id'] = Header(Utils.make_msgid(), self.character)
        if self.reply_to:
            self.message['Reply-to'] = Header(self.reply_to, self.character)
        self.message['Subject'] = Header(self.subject, self.character)
        self.message['From'] = Header(self.mail_from, self.character)
        self.message['To'] = Header(self.mail_to, self.character)
        self.message["Date"] = Utils.formatdate(localtime=True)

        # self.message['List-Unsubscribe'] = "<mailto:[email protected]>"

        if self.is_need_receipt:
            self.message['Disposition-Notification-To'] = Header(self.mail_from, self.character)
        if self.edm_check_result:
            self.message['Edm-Check-Result'] = Header(self.edm_check_result, self.character)