当前位置: 首页>>代码示例>>Python>>正文


Python smtp.sendmail函数代码示例

本文整理汇总了Python中twisted.mail.smtp.sendmail函数的典型用法代码示例。如果您正苦于以下问题:Python sendmail函数的具体用法?Python sendmail怎么用?Python sendmail使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了sendmail函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: mail_IRC_log

def mail_IRC_log(logger, channel, smtp, from_addr, to_addr):

    """
    Send latest IRC log to mailing list

    """
    minloglength = 20
    _log = logger.read_unpublished_log()
    lenlog = log.count('\n')
    if not lenlog >= minloglength:
        # skip publication
        report("skipping log publication due to small size (%i/%i lines)" % (lenlog, minloglength))
    else:
        # log long enough, format it
        date = time.strftime("%Y-%m-%d", time.localtime(time.time()))
        string = "Log of IRC channel %s (log published %s)" % (channel, date)
        _log = "%s\n\n%s" % (string, _log)
        # convert log to email
        mail = MIMEText(log)
        mail['Subject'] = "[evennia] %s IRC log - %s" % (channel, date)
        mail['From'] = str(from_addr)
        mail['To'] = str(to_addr)
        # send mail to mailing list

        def errback(fail):
            report("... irc-log mail could not be published: %s" % fail.value)

        def callback(ret):
            logger.mark_log_as_published()
            report("... irc-log mail from %s to %s successfully published." % (from_addr, to_addr))

        report("publishing irc log (%i lines) ..." % lenlog)
        sendmail(smtp, from_addr, to_addr, mail.as_string()).addCallbacks(callback, errback)
开发者ID:evennia,项目名称:evdemo,代码行数:33,代码来源:evennia_codebot.py

示例2: send_email_copy

def send_email_copy(message):
    """
    Sends an email copy of a message to all relevant targets.
    """
    receivers = [ receiver for receiver in message.receivers if receiver.player.user.email ]
    subject = message.header
    body = message.message
    if not (receivers):
        return

    msg = MIMEMultipart('alternative')
    msg['From'] = "Winter's Oasis <[email protected]>"
    msg['Subject'] = subject
    msg['Date'] = formatdate(localtime=True)

    # HTML email part.
    html_part = MIMEText('text', 'html')
    html_source = Template(HTML_TEMPLATE)
    value_map = {
        'from' : ', '.join([ sender.name for sender in message.senders ]),
        'message' : escape(unicode(body)).replace('\n', '<br />'),
        'recipients' : ', '.join([ receiver.name for receiver in message.receivers ]) }
    html_part.set_payload(html_source.substitute(value_map))

    value_map['message'] = unicode(body)
    text_source = Template(TEXT_TEMPLATE)
    body = text_source.substitute(value_map)
    text_part = MIMEText(unicode(body), 'plain', 'utf-8')
    msg.attach(text_part)
    msg.attach(html_part)

    for receiver in receivers:
        msg['To'] = receiver.db.email
        sendmail(SMTP_HOST, MAIL_FROM, receiver.player.user.email, msg.as_string())
开发者ID:Kelketek,项目名称:wintersoasis,代码行数:34,代码来源:mail.py

示例3: email

def email(subject, msgtxt):
    msg = MIMEText(msgtxt)
    msg['Subject'] = subject
    msg['From'] = global_config.smtpfrom
    msg['To'] = ', '.join(global_config.smtpto)

    sendmail(global_config.smtphost, global_config.smtpfrom, global_config.smtpto, msg.as_string())
开发者ID:acspike,项目名称:MasterClock,代码行数:7,代码来源:MasterClock.py

示例4: email_error

def email_error(exp, message):
    """
    Helper function to generate error emails when necessary and hopefully
    not flood!
    @param exp A string or perhaps a traceback object
    @param message A string of more information to pass along in the email
    """
    # Always log a message about our fun
    cstr = StringIO.StringIO()
    traceback.print_exc(file=cstr)
    cstr.seek(0)
    tbstr = cstr.read()
    log.err( exp )
    log.msg( message )

    # Prevent a parser from sending tons of spam
    if int(os.environ.get('EMAILS', 10)) < 0:
        return
    os.environ['EMAILS'] = str( int(os.environ.get("EMAILS",10)) - 1 )

    msg = MIMEText("""
Emails Left: %s  Host: %s

Exception:
%s
%s

Message:
%s""" % (os.environ["EMAILS"], socket.gethostname(), tbstr, exp, message))
    # Send the email already!
    msg['subject'] = '%s Traceback' % (sys.argv[0],)
    msg['From'] = settings.get('pywwa_errors_from', '[email protected]')
    msg['To'] = settings.get('pywwa_errors_to', '[email protected]')
    smtp.sendmail("smtp", msg["From"], msg["To"], msg)
开发者ID:scollis,项目名称:pyWWA,代码行数:34,代码来源:common.py

示例5: send_mail

    def send_mail(self, message, subject=None, to_address=None, to_nickname=None):
        msg = MIMEText(message, _charset='utf-8')
        msg['Subject'] = subject
        msg['From'] = self.from_address
        if to_nickname is not None:
            msg['To'] = '%s <%s>' % (to_nickname, to_address)
        else:
            msg['To'] = to_address

        smtp.sendmail("localhost", self.from_address, to_address, msg.as_string())
开发者ID:Mrkebubun,项目名称:sputnik,代码行数:10,代码来源:sendmail.py

示例6: handle_error

    def handle_error(self, error):
        traceback.print_exc()
        #g_logger.error("%s: %s" % (type(error), error))
        if isinstance(error, InitializationError):
            sys.exit(1)

        # send an email
        from twisted.mail.smtp import sendmail
        sendmail("smtp.gmail.com", "[email protected]", "[email protected]",
                 "Exception occurs in ICM Desktop Agent", "gmail.com")
开发者ID:gkso,项目名称:openmonitor-desktop-agent,代码行数:10,代码来源:Errors.py

示例7: do_test

        def do_test():
            smtp = smtplib.SMTP('localhost', self.port, timeout=1)
            self.addCleanup(threads.deferToThread, smtp.quit)
            
            # check that validate_to and _from results in smtp errors
            self.assertRaises(smtplib.SMTPSenderRefused, smtp.sendmail, '[email protected]', '[email protected]', 'Hello')
            self.assertRaises(smtplib.SMTPSenderRefused, smtp.sendmail, '[email protected]', '[email protected]', 'Hello')
            self.assertRaises(smtplib.SMTPRecipientsRefused, smtp.sendmail, '[email protected]', '[email protected]', 'Hello')

            smtp.sendmail('[email protected]', '[email protected]', 'Hello')
开发者ID:alexbrasetvik,项目名称:Piped,代码行数:10,代码来源:test_smtp_provider.py

示例8: do_test_without_tls

        def do_test_without_tls():
            smtp = smtplib.SMTP('localhost', self.port, timeout=1)
            self.addCleanup(threads.deferToThread, smtp.quit)

            # a plaintext login is not allowed
            self.assertSMTPErrorCode(530, smtp.login, 'username', 'password')

            # tls is not configured
            self.assertRaises(smtplib.SMTPException, smtp.starttls)

            # we configured a checker that accepts anonymous access, so sending should work
            smtp.sendmail('[email protected]', '[email protected]', 'Hello')
开发者ID:alexbrasetvik,项目名称:Piped,代码行数:12,代码来源:test_smtp_provider.py

示例9: sendmailfun

def sendmailfun( name, loginname, emailid, email, mailinfo, sendnum  ):

	print "Send:", email
	def error ( msg ):
		reactor.callLater(0, sqldb.setResult, emailid,  str(msg),  loginname , 0 )
	
	def finish( msg ):
		reactor.callLater(0, sqldb.setResult, emailid,  str(msg),  loginname , 1 )

	sender = mailinfo['sender']
	subject = mailinfo['subject']
	omsg = mailinfo['msg']
	body = Template(omsg).safe_substitute( mailinfo )
	cbuf = create_string_buffer('\000' * 100 )

	# domin
	domain = ""
	try:
		username, domain = email.split("@")
	except:
		domain = email
	domain = domain.strip(" >")
	if 0==qmx.QueryMX( c_char_p(domain) , cbuf ):
		return error( "Query MX for %s Failed" % domain )
	
	try:
		smtp = smtplib.SMTP(cbuf.value)
		if DEBUG:
			smtp.set_debuglevel(1)
		smtp.sendmail(sender, email, buildmsg(sender, email, subject, body))
		smtp.quit()
		return finish( email )
	except Exception, err:
		code = -1
		msg = ""
		try:
			code, msg = err
		except:
			msg = str(err)
		print email, code, msg
		if int(code) in [421,451,450]:
			sendnum += 1
			sendfun = partial( sendmailfun, name= str(id), loginname=loginname, emailid=emailid, email = email, mailinfo = mailinfo , sendnum = sendnum )
			if  sendnum <= retry_count :
				tp.addtask(sendfun, random.randint( 600, 30*60 ) )
			return error("Host: %s, Retry: %d, Error: %d,%s" % ( cbuf.value, sendnum, code, err) )
		else:
			return error("Host: %s, Error: %d,%s" % ( cbuf.value, code, err) )
开发者ID:bahamut8348,项目名称:xkcode,代码行数:48,代码来源:emailsender.py

示例10: sendMailToAdmin_cb

 def sendMailToAdmin_cb(self, unused, template_variables):
     template_variables['my_fqdn'] = '%s.%s' % (
         template_variables['my_hostname'],
         template_variables['my_domain'])
     jinja_env = jinja.Environment()
     template = jinja_env.from_string(self.body_template)
     rendered_body = unicode(template.render(**template_variables))
     msg = MIMEText(rendered_body.encode('utf-8'), 'plain', 'utf-8')
     msg['Subject'] = u'[EW4 %s] %s' % (
         template_variables['my_hostname'],
         unicode(template_variables['subject']))
     sender = self.config.sender_mail
     if check_mail(sender):
         msg['From'] = sender
     else:
         raise NuConfError(CONTACT_INVALID_SENDER,
                           tr("'sender' e-mail : invalid e-mail address"))
     recipient = self.config.admin_mail
     if check_mail(recipient):
         msg['To'] = recipient
     else:
         raise NuConfError(CONTACT_INVALID_RECIPIENT,
                 tr("'recipient' e-mail : invalid e-mail address"))
     defer = sendmail('127.0.0.1', sender, recipient, msg.as_string())
     defer.addCallback(self.logSuccess)
     return defer
开发者ID:maximerobin,项目名称:Ufwi,代码行数:26,代码来源:contact.py

示例11: _query_error

    def _query_error(self, error, query, sender, recipient):
        """
        Handle failed API queries.
        
        Send out email notifications to admins.

        """
        # TODO: Move constants to external preferences
        # Send Email on error
        host = config.SMTP_HOST
        from_addr = config.EMAIL_FROM
        to_addrs = config.EMAIL_TO

        text = "Query: '%s'." % query
        msg = MIMEText(text.encode('utf-8'), 'plain', 'utf-8')
        msg['Subject'] = "[Molnetbot] An error occured while sending a " \
                         "search query to Molnet."
        msg['From'] = from_addr
        msg['To'] = ', '.join(to_addrs)
        deferred = sendmail(host, from_addr, to_addrs, msg.as_string())

        # Send error reply back to query sender
        reply = domish.Element((None, 'message'))
        reply['to'] = sender
        reply['from'] = recipient
        reply['type'] = 'chat'
        reply.addElement('body', content="An error occurred while "
                                         "sending your search query to "
                                         "Molnet. Please try again later.")
        self.send(reply)
开发者ID:lemonad,项目名称:molnetbot,代码行数:30,代码来源:molnetbot.py

示例12: _failure

 def _failure(failure, rb=repo_branch):
   msg = ('RepoPoller is having problems...\n\n'
          'host: %s\n'
          'repo checkout: %s\n'
          'repo url: %s\n'
          'repo branch: %s\n\n'
          '%s') % (socket.gethostname(), self.workdir, self.repo_url,
                  rb, failure)
   log.err(msg)
   self.errCount += 1
   if self.errCount % 3 == 0 and self.smtp_host and self.to_addrs:
     smtp.sendmail(smtphost=self.smtp_host,
                   from_addr=self.from_addr,
                   to_addrs=self.to_addrs,
                   msg=msg)
   return failure
开发者ID:alexmos17,项目名称:build_internal,代码行数:16,代码来源:repo_poller.py

示例13: _sendmail

def _sendmail(fromAddress, toAddress, message, host='localhost', port=0,
              user=None, password=None, callback=None, errback=None):
    """
    Connect to an SMTP server and send an email message. If username and
    password are provided, ESMTP is used to connect, otherwise a standard SMTP
    connection is used.

    @param fromAddress: The SMTP reverse path (ie, MAIL FROM)
    @param toAddress: The SMTP forward path (ie, RCPT TO)
    @param message: An L{email.message.Message} instance (such as C{MIMEText}).
    @param host: The MX host to which to connect.
    @param port: The port number to which to connect.
    @param user: The username with which to authenticate.
    @param password: The password with which to authenticate.

    @return: A Deferred which will be called back when the message has been
        sent or which will errback if it cannot be sent.
    """
    if user or password:
        fp = StringIO()
        g = Generator(fp, mangle_from_=False, maxheaderlen=60)
        g.flatten(message)
        d = Deferred()
        factory = ESMTPSenderFactory(user, password, fromAddress, toAddress,
                                     message, d)
        reactor.connectTCP(host, port, factory)
    else:
        d = sendmail(host, fromAddress, toAddress, )

    return d
开发者ID:carriercomm,项目名称:mudsling,代码行数:30,代码来源:internet.py

示例14: sendEmail

    def sendEmail(self, toAddresses, message, fromAddress=None, swallowErrors=None):
        """
        Send an email to one or more recipients.
        """

        # If toAddresses is not already a list type then make it so.
        if not isinstance(toAddresses, (list, tuple, GeneratorType)):
            toAddresses = [toAddresses]

        # Work out whether to swallow errors.
        if swallowErrors is None:
            swallowErrors = self.swallowSMTPErrors

        # Work out the from address to use.
        if fromAddress is None:
            fromAddress = self.emailFromAddress

        # Send the email
        d = smtp.sendmail(self.smtpHost, fromAddress, toAddresses, message)

        # Swallow smtp errors if requested
        if swallowErrors:
            d.addErrback(self._swallorSMTPError)

        # Remap SMTP errors
        d.addErrback(self._smtpError)

        # Return the result
        return d
开发者ID:timparkin,项目名称:into-the-light,代码行数:29,代码来源:service.py

示例15: sendmail

def sendmail(toAddr, subject, textPart, htmlPart=None, fromAddr="[email protected]", fromName="Flocked-in"):
    if textPart:
        textPart = sanitizer.unescape(textPart, {"&#58;": ":"})
    if htmlPart:
        msg = MIMEMultipart("alternative")
        msg.preamble = "This is a multi-part message in MIME format."

        msgText = MIMEText(textPart, _charset="utf8")
        msg.attach(msgText)

        msgText = MIMEText(htmlPart, "html", _charset="utf8")
        msg.attach(msgText)
    else:
        msg = MIMEText(textPart, _charset="utf8")

    msg["Subject"] = sanitizer.unescape(subject, {"&#58;": ":"})
    msg["From"] = "%s <%s>" % (fromName, fromAddr)
    msg["To"] = toAddr
    try:
        devMailId = config.get("Devel", "MailId")
        if devMailId:
            toAddr = devMailId
    except:
        pass

    message = msg.as_string()
    host = config.get("SMTP", "Host")
    yield smtp.sendmail(host, fromAddr, toAddr, message)
开发者ID:psunkari,项目名称:flocked-in,代码行数:28,代码来源:utils.py


注:本文中的twisted.mail.smtp.sendmail函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。