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


Python SMTP.helo方法代码示例

本文整理汇总了Python中smtplib.SMTP.helo方法的典型用法代码示例。如果您正苦于以下问题:Python SMTP.helo方法的具体用法?Python SMTP.helo怎么用?Python SMTP.helo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在smtplib.SMTP的用法示例。


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

示例1: mail_message

# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import helo [as 别名]
def mail_message(message, program):
    mail = MIMEText(message)
    mail["From"] = "[email protected]%s" % gethostname()
    mail["To"] = "Crashers"
    mail["Subject"] = "%s crashed" % program
    smtp = SMTP("smtp.looney.com")

    smtp.helo()
    smtp.starttls()
    smtp.sendmail("[email protected]", _MAIL_TO, mail.as_string())
    smtp.close()
开发者ID:BackupTheBerlios,项目名称:crashlog-svn,代码行数:13,代码来源:crashlog.py

示例2: str

# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import helo [as 别名]
import dns.resolver
import pdb
import argparse
from smtplib import SMTP

parser = argparse.ArgumentParser(description="Checks if email address is valid a la Mailtester.com")
parser.add_argument("email", help="the email address to check")
args = parser.parse_args()
domain = args.email.split("@")[1]

dig_resp = dns.resolver.query(domain, "MX")
mx_servers = []
for d in dig_resp:
    mx_servers.append((d.preference, str(d.exchange)))
mx_servers.sort()

print("Using server with lowest priority", mx_servers[0])
mailserver = SMTP(mx_servers[0][1])
helo_resp = mailserver.helo()
print(helo_resp)

if helo_resp[1].decode().find("mail.protection.outlook.com") != -1:
    print("Microsoft SMTP servers will ban this IP")
else:
    print(mailserver.docmd("MAIL", args="FROM:<[email protected]>"))
    print(mailserver.docmd("RCPT", args="TO:<" + args.email + ">"))
    print(mailserver.docmd("QUIT"))
开发者ID:randomshinichi,项目名称:utils,代码行数:29,代码来源:emailexists.py

示例3: check_conf

# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import helo [as 别名]
def check_conf(args):
	''' Using info from conf file, check JSS connection, check API privileges, and check Twitter Auth'''
	logger = logging.getLogger('capd')
	logger.debug("check_conf")
	config = ConfigParser.ConfigParser()
	config.read(Software_Repo+'/conf/JSS_Server.conf')
	
	#### check JSS connection ####
	logger.info("[+] Checking JSS Connection ...")
	try:
		r = requests.get(config.get('JSS_Server', 'jss_url'), timeout=10, verify=False)
		logger.info("[+] JSS connection is OK")
	except requests.exceptions.RequestException as e:
		logger.error("[-] JSS Server problem with following error: %s", e)
		sys.exit(1)

	#### check API Privileges ####
	logger.info("[+] Checking API Privileges ...")
	api_user_permissions = []
	try:
		url_api = config.get('JSS_Server', 'url_api')
		api_user = config.get('JSS_Server', 'api_user')
		api_pass = config.get('JSS_Server', 'api_pass')
		r = requests.get(url_api+'accounts/username/'+api_user, auth=(api_user, api_pass), verify=False, headers=headers)
	except requests.exceptions.RequestException as e:
		logger.error("[-] JSS Server problem with following error: %s", e)
		sys.exit(1)
	tree = ET.fromstring(r.content)
	for elem in tree.iterfind('./privileges/jss_objects/'):
		api_user_permissions.append(elem.text)
	if not list(set(api_account_permissions) - set(api_user_permissions)):
		logger.info("[+] API Privilegs OK")
	else:
		logger.error("[-] You appear to be missing the following API privilege(s): %s", list(set(api_account_permissions) - set(api_user_permissions)))
		sys.exit(1)

	#### check Twitter Auth ####
	logger.info("[+] Checking Twitter Auth ...")
	try:
		app_key = config.get('Twitter_Auth', 'twitter_app_key')
		if not app_key:
			logger.info("[-] No Twitter App Key provided!")
			return
		app_secret = config.get('Twitter_Auth', 'twitter_app_secret')
		oauth_token = config.get('Twitter_Auth', 'twitter_oauth_token')
		oauth_token_secret = config.get('Twitter_Auth', 'twitter_oauth_token_secret')
		twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret)
		twitter.get("https://api.twitter.com/1.1/account/verify_credentials.json")
		logger.info("[+] Twitter Auth OK")
	except TwythonError as e:
		logger.error("[-] Check twitter oauth credentials. %s", e)
		sys.exit(1)

#### check Mail Server ####
	logger.info("Checking connection to Mailserver ...")
	mailserver = config.get('Mail', 'mailserver')
	if not mailserver:
		logger.info("[-] No Mailserver configured!")
		return
	try:
		connect_to_mailserver = SMTP(mailserver, timeout=10)
		mailserver_status, mailserver_message = connect_to_mailserver.helo()
		if mailserver_status == 250:
			logger.info("[+] Mailserver connection OK")
	except socket.error as e:
		logger.error("[-] Mailserver connection error: %s", e)
		sys.exit(1)
	except SMTPException as e:
		logger.error("[-] Mailserver connection error: %s", e)
		sys.exit(1)

	#### clear apps and screenshots folder ####
	logger.info("[+] Cleaning out apps folder ...")
	shutil.rmtree(Software_Repo+'/apps/')
	shutil.rmtree(Software_Repo+'/logs/screenshots/')
	os.mkdir(Software_Repo+'/apps')
	os.mkdir(Software_Repo+'/logs/screenshots')
开发者ID:shaidar,项目名称:Casper,代码行数:79,代码来源:check_conf.py

示例4: BadGrammarTests

# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import helo [as 别名]
class BadGrammarTests(unittest.TestCase):
    """Collection of tests of invalid SMTP grammar (most should produce 5XX error codes)"""
    
    def setUp(self):
        self.smtp = SMTP('localhost', 1025)

    def tearDown(self):
        self.smtp.quit()
        self.smtp.close()
        self.smtp = None
  
    def testUnimplementedEhlo(self):
        """Unknown commands are ignored and the self.smtp informed."""
        self.assertEqual(self.smtp.ehlo(), (502, 'Error: command "EHLO" not implemented'))
        
    def testIllegalHelo(self):
        """HELO takes a single argument."""
        self.assertEqual(self.smtp.docmd('HELO'), (501, 'Syntax: HELO hostname'))
        
    def testMultipleHelo(self):
        """Only a single HELO command is allowed per connection."""
        self.smtp.helo()
        self.assertEqual(self.smtp.helo(), (503, 'Duplicate HELO/EHLO'))
    
    def testIllegalNoop(self):
        """The NOOP command fails if any argument is passed."""
        response = self.smtp.docmd('NOOP', 'something else here')
        self.assertEqual(response, (501, 'Syntax: NOOP'))
        
    def testIllegalRset(self):
        """The RSET command fails if any argument is passed."""
        response = self.smtp.docmd('RSET', 'now')
        self.assertEqual(response, (501, 'Syntax: RSET'))
        
    def testMailNoFrom(self):
        """The MAIL command requires FROM: to follow it."""
        self.assertEqual(self.smtp.docmd('MAIL'), (501, 'Syntax: MAIL FROM:<address>'))
    
    def testMailInvalidFrom(self):
        """The MAIL command requires FROM: to contain an email address."""
        self.assertEqual(self.smtp.docmd('MAIL FROM:'), (501, 'Syntax: MAIL FROM:<address>'))
    
    def testDuplicateMailCommand(self):
        """Nested MAIL commands are not allowed."""
        self.assertEqual(self.smtp.docmd('MAIL FROM:<[email protected]>'), (250, 'Ok'))
        self.assertEqual(self.smtp.docmd('MAIL FROM:<[email protected]>'), (503, 'Error: nested MAIL command'))
        
    def testRcptWithoutMail(self):
        """The RCPT command must be preceded by the MAIL command."""
        self.assertEqual(self.smtp.docmd('RCPT TO:<[email protected]>'), (503, 'Error: need MAIL command'))
        
    def testRcptWithoutTo(self):
        """The RCPT command must contain TO:<address> as the argument."""
        self.assertEqual(self.smtp.docmd('MAIL FROM:<[email protected]>'), (250, 'Ok'))
        self.assertEqual(self.smtp.docmd('RCPT'), (501, 'Syntax: RCPT TO: <address>'))
    
    def testRcptEmptyTo(self):
        """The RCPT command cannot have an empty TO:."""
        self.assertEqual(self.smtp.docmd('MAIL FROM:<[email protected]>'), (250, 'Ok'))
        self.assertEqual(self.smtp.docmd('RCPT TO:'), (501, 'Syntax: RCPT TO: <address>'))

    def testRcptInvalidTo(self):
        """The RCPT command TO: argument must be a valid address."""
        self.assertEqual(self.smtp.docmd('MAIL FROM:<[email protected]>'), (250, 'Ok'))
        self.assertEqual(self.smtp.docmd('RCPT TO:<[email protected]>'), (553, 'Mailbox name invalid'))
        
    def testDataWithoutRcpt(self):
        """The DATA command must be preceded by the RCPT TO: command."""
        self.assertEqual(self.smtp.docmd('DATA'), (503, 'Error: need RCPT command'))
    
    def testDataIllegalArgument(self):
        """The DATA command does not take any arguments."""
        self.assertEqual(self.smtp.docmd('MAIL', 'FROM:<[email protected]>') , (250, 'Ok'))
        self.assertEqual(self.smtp.docmd('RCPT', 'TO:<[email protected]>') , (250, 'Ok'))
        self.assertEqual(self.smtp.docmd('DATA', 'some data here') , (501, 'Syntax: DATA'))
开发者ID:femto113,项目名称:node-smtpevent,代码行数:77,代码来源:grammar.py

示例5: GoodGrammarTests

# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import helo [as 别名]
class GoodGrammarTests(unittest.TestCase):
    """Collection of tests of valid SMTP grammar (i.e. they should not generate any error responses from server)"""
    
    addrs = [
        '[email protected]', '[email protected]', '[email protected]',
        '[email protected]', '[email protected]'
        ]

    def setUp(self):
        self.smtp = SMTP('localhost', 1025)

    def tearDown(self):
        # self.smtp.quit()
        self.smtp.close()
        self.smtp = None

    def assertOk(self, result):
      self.assertEqual(result, (250, 'Ok'))

    def testConnect(self):
        """On connecting the server sends a 220 response with a welcome message."""
        smtp = SMTP();
        self.assertEqual(smtp.connect('localhost', 1025), (220, 'test node.js smtpevent server 0.0.2'))
        smtp.quit();
        smtp.close()
        
    def testHelo(self):
        """The server responds to a valid HELO command."""
        self.assertEqual(self.smtp.helo('example.com'), (250, 'test Hello 127.0.0.1'))

    def testNoop(self):
        """The NOOP command takes no arguments."""
        self.assertOk(self.smtp.noop())
        
    def testQuit(self):
        """The QUIT command works without an argument"""
        self.assertEqual(self.smtp.quit(), (221, 'test closing connection'))

    def testQuitWithArgument(self):
        """The QUIT command works with an argument"""
        self.assertEqual(self.smtp.docmd('QUIT', 'See you later'), (221, 'test closing connection'))
        
    def testRset(self):
        """The RSET command takes no arguments."""
        self.assertOk(self.smtp.rset())
        
    def testMailFrom(self):
        """The MAIL command will extract the email address from the FROM:."""
        self.assertEqual(self.smtp.mail('[email protected]'), (250, 'Ok'))
        
    def testMailFromEmpty(self):
        """The MAIL command handles empty addresses"""
        self.assertEqual(self.smtp.mail('<>'), (250, 'Ok'))
    
    def testMultipleRcpts(self):
        """Multiple RCPT commands can be issued to add recipients."""
        self.assertOk(self.smtp.docmd('MAIL', 'FROM:<[email protected]>'))
        for rcpt in self.addrs:
            self.assertOk(self.smtp.docmd('RCPT', 'TO:<%s>' % rcpt))
    
    def testDataResponse(self):
        """The DATA instructs the self.smtp to end the message with <CR><LF>.<CR><LF>."""
        self.assertOk(self.smtp.mail('[email protected]'))
        self.assertOk(self.smtp.rcpt('[email protected]'))
        self.assertEqual(self.smtp.docmd('DATA'), (354, 'End data with <CR><LF>.<CR><LF>'))
开发者ID:femto113,项目名称:node-smtpevent,代码行数:67,代码来源:grammar.py

示例6: send_email

# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import helo [as 别名]
def send_email(prefs, report_str):
    recipients = prefs['ADMIN_EMAIL'].split(',')

    msg = dedent("""
        From: %s
        To: %s
        Subject: %s
        Date: %s

        """).lstrip() % (
            prefs.get('SMTP_FROM'),
            prefs.get('ADMIN_EMAIL'),
            prefs.get('SMTP_SUBJECT'),
            time.strftime(prefs.get('SMTP_DATE_FORMAT')
        )
    )

    msg += report_str
    try:
        smtp = SMTP()

        if logging.getLogger().isEnabledFor(logging.DEBUG):
            smtp.set_debuglevel(1)

        smtp.connect(prefs.get('SMTP_HOST'),
            prefs.get('SMTP_PORT'))

        # If the server supports ESMTP and TLS, then convert the message exchange to TLS via the
        # STARTTLS command.
        if smtp.ehlo()[0] == 250:
            if smtp.has_extn('starttls'):
                (code, resp) = smtp.starttls()
                if code != 220:
                    raise SMTPResponseException(code, resp)
                (code, resp) = smtp.ehlo()
                if code != 250:
                    raise SMTPResponseException(code, resp)
        else:
            # The server does not support esmtp.

            # The Python library SMTP class handles executing HELO/EHLO commands inside
            # login/sendmail methods when neither helo()/ehlo() methods have been
            # previously called.  Because we have already called ehlo() above, we must
            # manually fallback to calling helo() here.

            (code, resp) = smtp.helo()
            if not (200 <= code <= 299):
                raise SMTPHeloError(code, resp)

        username = prefs.get('SMTP_USERNAME')
        password = prefs.get('SMTP_PASSWORD')

        if username and password:
            smtp.login(username, password)

        smtp.sendmail(prefs.get('SMTP_FROM'),
                      recipients,
                      msg)
        debug("sent email to: %s" % prefs.get("ADMIN_EMAIL"))
    except Exception as e:
        print("Error sending email")
        print(e)
        print("Email message follows:")
        print(msg)

    try:
        smtp.quit()
    except Exception:
        pass
开发者ID:KyonCN,项目名称:denyhosts,代码行数:71,代码来源:util.py


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