本文整理汇总了Python中smtplib.SMTP.docmd方法的典型用法代码示例。如果您正苦于以下问题:Python SMTP.docmd方法的具体用法?Python SMTP.docmd怎么用?Python SMTP.docmd使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类smtplib.SMTP
的用法示例。
在下文中一共展示了SMTP.docmd方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: might_work
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import docmd [as 别名]
def might_work(sender, receiver):
server = options.value("smtp_hostname", "localhost")
port = options.value("smtp_port", 25)
username = options.value("smtp_username", "")
password = options.value("smtp_password", "")
my_hostname = socket.getfqdn()
test_commands = [
('EHLO', my_hostname),
('MAIL FROM:', sender),
('RCPT TO:', receiver)
]
try:
server = SMTP(server, int(port))
if username != "" and password != "":
# The .login() function only accepts str, not unicode, so force it
server.login(str(username), str(password))
for cmd, arg in test_commands:
code, msg = server.docmd(cmd, arg)
if code == 250:
continue
raise SendEmailError('SMTP: %s was not accepted: %s' % (cmd, msg))
# do not actually send something
server.quit()
except (SMTPException, socket.error) as e:
raise SendEmailError('SMTP: %s' % (str(e), ))
示例2: MessageSender
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import docmd [as 别名]
class MessageSender(Thread):
def __init__(self, wrappers):
super().__init__()
self.wrappers = wrappers
def run(self):
if self._open_server():
for wrapper in self.wrappers:
self._send_message(wrapper.addresses, wrapper.message)
self.server.close()
def _send_message(self, addresses, message):
try:
self.server.sendmail(params['sender_email_address'], addresses, message)
except SMTPHeloError:
log.exception("Helo error sending email", exc_info=True)
except SMTPRecipientsRefused:
log.warn("Failed to send email to {}".format(addresses))
except SMTPSenderRefused:
log.warn("Sender refused for email", exc_info=True)
except SMTPDataError as exp:
log.exception("Unexpected Data error sending email")
def _open_server(self):
self.server = SMTP(params['smtp_server'], params.get("smtp_port", 587))
self.server.ehlo()
self.server.starttls()
if params.get('use_gmail_oauth2'):
auth_email, access_token = _get_oauth_info()
auth_string = b'user=' + bytes(params['sender_email_address'],
'ascii') + b'\1auth=Bearer ' + access_token + b'\1\1'
log.info(auth_string)
code, msg = self.server.docmd('AUTH', 'XOAUTH2 ' + (base64.b64encode(auth_string)).decode('ascii'))
log.info("Code {} Message {}", code, base64.decodebytes(msg))
if code == 235:
return True
code, msg = self.server.docmd('')
log.info("code {}, Message {}", code, msg)
return False
try:
self.server.login(params['sender_email_address'], params['sender_password'])
return True
except SMTPAuthenticationError:
log.warn("SMTP Password Authentication Failed", ex_info=True)
return False
示例3: __init__
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import docmd [as 别名]
class SMTPConnection:
'''
Class that Handles Connection to a SMTP server and tests Username/Password on it , it is initialized with the Server and Port,
:param server : Server to connect to
:param port : Port to connect to usually 537
'''
def __init__(self,server,port):
self.server=server
self.port=port
self.smtp = SMTP()
def isConnected(self):
'''
Checks that we are still connected ( The served didnt kick us out )
'''
try:
status = self.smtp.docmd('NOOP')[0]
except: # smtplib.SMTPServerDisconnected
status = -1
return True if status == 250 else False
def Connect(self):
'''
Connect to The Server / Reconnect
'''
self.smtp = SMTP()
self.conn=self.smtp.connect(self.server, self.port)
self.smtp.starttls()
def Test_Credentials(self,user,password):
'''
The main Function, Takes username ,password , and tries to log them in the currennt connectopm
:param user : the username (email)
:param password : the password
returns True if password is correct / False if not
'''
done=False
while 1:
try:
if not self.isConnected():
self.Connect()
self.smtp.login(user, password)
self.smtp.close()
return True
except SMTPAuthenticationError:
return False
except:
continue
def Check_Server(self,server,port):
try:
_smtp=SMTP()
_smtp.connect(self.server, self.port)
return True
except:
return False
示例4: get_smtp_client
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import docmd [as 别名]
def get_smtp_client(stor):
host = stor['host']
port = stor['port']
user = stor['user']
passwd = stor['pass']
debuglevel = stor['debuglevel']
login = stor['login']
starttls = stor['starttls']
s = SMTP(host, port)
if debuglevel:
s.set_debuglevel(True)
if starttls and login:
s.ehlo()
s.starttls()
s.ehlo()
s.login(user, passwd)
elif login:
try:
s.login(user, passwd)
except SMTPAuthenticationError:
sys.stdout.write('\n------- try Auth Login again ------\n')
s = SMTP(host, port)
if debuglevel:
s.set_debuglevel(True)
s.ehlo()
(code, resp) = s.docmd('AUTH LOGIN')
if code != 334:
raise SMTPAuthenticationError(code, resp)
(code, resp) = s.docmd(encode_base64(user, eol=""))
if code != 334:
raise SMTPAuthenticationError(code, resp)
(code, resp) = s.docmd(encode_base64(passwd, eol=""))
if code != 235:
raise SMTPAuthenticationError(code, resp)
return s
示例5: test_quit_with_arg
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import docmd [as 别名]
def test_quit_with_arg(self):
client = SMTP(*self.address)
code, response = client.docmd('QUIT', 'oops')
self.assertEqual(code, 501)
self.assertEqual(response, b'Syntax: QUIT')
示例6: BadGrammarTests
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import docmd [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'))
示例7: GoodGrammarTests
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import docmd [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>'))
示例8: str
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import docmd [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"))
示例9: Gmail
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import docmd [as 别名]
class Gmail():
def __init__(self, username):
# the main username
self.username = username
self.http = httplib2.Http()
self.logger = logging.getLogger('Gmail')
# Start the OAuth flow to retrieve credentials
flow = flow_from_clientsecrets(CLIENT_SECRET_FILE,
scope=OAUTH_SCOPE)
# The storage for current user
storage = Storage(os.path.join(STORAGE_DIR, self.username))
# Try to retrieve credentials from storage
# or run the flow to generate them
self.credentials = storage.get()
if self.credentials is None or self.credentials.invalid:
# call a subprocess as workaround for stdin/stdout
# blocked by the main process, this is the main function:
def _subprocess_login():
sys.stdout = StreamToLogger(self.logger, logging.DEBUG)
sys.stderr = StreamToLogger(self.logger, logging.ERROR)
queue.put(run(flow, storage, http=self.http))
# A Queue to get the result from subprocess
queue = Queue()
p = Process(target=_subprocess_login)
self.logger.debug("start login process")
p.start()
p.join()
self.logger.debug("end login process")
# Retrieve the credentials
self.credentials = queue.get()
# Access to the Gmail APIs
self._gmail_API_login()
# Use smtp as workaround to send message, GMail API
# bugged with Content-Type: multipart/signed
self._smtp_login()
def _gmail_API_login(self):
"""
Login in Gmail APIs
"""
self._refresh_credentials()
# Authorize the httplib2.Http object with our credentials
authorized_http = self.credentials.authorize(self.http)
# Build the Gmail service from discovery
self.gmail_service = build('gmail', 'v1', http=authorized_http)
self.messages = self.gmail_service.users().messages()
self.drafts = self.gmail_service.users().drafts()
def _refresh_credentials(self):
"""Refresh credentials if needed"""
if self.credentials.access_token_expired:
self.logger.info("credentials expired - refreshing")
self.credentials.refresh(self.http)
def _smtp_login(self):
"""
Login in Gmail smtp
"""
self._refresh_credentials()
# initialize SMTP procedure
self.smtp = SMTP('smtp.gmail.com', 587)
if self.logger.getEffectiveLevel() == logging.DEBUG:
self.smtp.set_debuglevel(True)
self.smtp.starttls()
self.smtp.ehlo()
# XOATH2 authentication
smtp_auth_string = 'user={}\1auth=Bearer {}\1\1'
access_token = self.credentials.access_token
smtp_auth_string = smtp_auth_string.format(self.username,
access_token)
smpt_auth_b64 = base64.b64encode(smtp_auth_string)
# smtp login
self.smtp.docmd("AUTH", "XOAUTH2 {}".format(smpt_auth_b64))
self.smtp.send("\r\n")
def get(self, id):
"""
Get a Message from the Gmail message id (as known as X-GM-MSGID).
"""
self.logger.info('getting message {}'.format(id))
# this return a message.raw in url safe base64
message = self.messages.get(userId='me', id=id, format='raw').execute()
# decode it
message = base64.urlsafe_b64decode(str(message['raw']))
self.logger.debug('message id {}\n{}'.format(id, message))
message = email.message_from_string(message)
return message
#.........这里部分代码省略.........