本文整理汇总了Python中smtplib.SMTP_SSL.starttls方法的典型用法代码示例。如果您正苦于以下问题:Python SMTP_SSL.starttls方法的具体用法?Python SMTP_SSL.starttls怎么用?Python SMTP_SSL.starttls使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类smtplib.SMTP_SSL
的用法示例。
在下文中一共展示了SMTP_SSL.starttls方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testsettings
# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import starttls [as 别名]
def testsettings(host, port, login, password):
host = host.encode('utf-8')
port = int(port)
login = login.encode('utf-8')
password = password.encode('utf-8')
try: # SSL
smtp = SMTP_SSL(host, port)
ret, _ = smtp.login(login, password)
smtp.quit()
if ret is 235: # 2.7.0 Authentication successful
return True
except (ssl.SSLError, SMTPException):
pass
try: # STARTTLS or plaintext
smtp = SMTP(host, port)
smtp.starttls()
smtp.ehlo()
ret, _ = smtp.login(login, password)
smtp.quit()
if ret is 235:
return True
except SMTPException:
pass
return False
示例2: _send
# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import starttls [as 别名]
def _send(self, email_addr, msg):
"""Deliver an email using SMTP
:param email_addr: recipient
:type email_addr: str.
:param msg: email text
:type msg: str.
"""
proto = self._conf["proto"]
assert proto in ("smtp", "starttls", "ssl"), "Incorrect protocol: %s" % proto
try:
if proto == "ssl":
log.debug("Setting up SSL")
session = SMTP_SSL(self._conf["fqdn"], self._conf["port"])
else:
session = SMTP(self._conf["fqdn"], self._conf["port"])
if proto == "starttls":
log.debug("Sending EHLO and STARTTLS")
session.ehlo()
session.starttls()
session.ehlo()
if self._conf["user"] is not None:
log.debug("Performing login")
session.login(self._conf["user"], self._conf["pass"])
log.debug("Sending")
session.sendmail(self.sender, email_addr, msg)
session.quit()
log.info("Email sent")
except Exception as e: # pragma: no cover
log.error("Error sending email: %s" % e, exc_info=True)
示例3: sendmail
# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import starttls [as 别名]
def sendmail(to_mails, message):
# Update settings
apply_db_settings(flask_app.flask_app)
mail = 'From: {}\nTo: {}\nSubject: {}\n\n{}'.format(
flask_app.flask_app.config.get('EMAIL_EMAIL_FROM'),
to_mails,
flask_app.flask_app.config.get('EMAIL_SUBJECT'),
message
).encode(encoding='utf-8')
server_str = '{}:{}'.format(flask_app.flask_app.config.get('EMAIL_HOST', '127.0.0.1'),
flask_app.flask_app.config.get('EMAIL_PORT', 25))
server = SMTP_SSL(server_str) if flask_app.flask_app.config.get('EMAIL_ENCRYPTION', 0) == 2 \
else SMTP(server_str)
if flask_app.flask_app.config.get('EMAIL_ENCRYPTION', 0) == 1:
server.starttls()
if flask_app.flask_app.config.get('EMAIL_AUTH', 0):
server.login(flask_app.flask_app.config.get('EMAIL_LOGIN'),
flask_app.flask_app.config.get('EMAIL_PASSWORD'))
server.sendmail(flask_app.flask_app.config.get('EMAIL_EMAIL_FROM'),
to_mails,
mail)
server.quit()
示例4: send_mail
# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import starttls [as 别名]
def send_mail( message, smtp_host, smtp_port, user = None, passwd = None,
security = None ):
'''
Sends a message to a smtp server
'''
if security == 'SSL':
if not HAS_SMTP_SSL:
raise Exception('Sorry. For SMTP_SSL support you need Python >= 2.6')
s = SMTP_SSL(smtp_host, smtp_port)
else:
s = SMTP(smtp_host, smtp_port)
# s.set_debuglevel(10)
s.ehlo()
if security == 'TLS':
s.starttls()
s.ehlo()
if user:
s.login(user.encode('utf-8'), passwd.encode('utf-8'))
to_addr_list = []
if message['To']:
to_addr_list.append(message['To'])
if message['Cc']:
to_addr_list.append(message['Cc'])
if message['Bcc']:
to_addr_list.append(message['Bcc'])
to_addr_list = ','.join(to_addr_list).split(',')
s.sendmail(message['From'], to_addr_list, message.as_string())
s.close()
示例5: connect_to_server
# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import starttls [as 别名]
def connect_to_server(self):
if self.tls == 'ssl':
connection = SMTP_SSL(local_hostname=self.local_hostname, keyfile=self.keyfile,
certfile=self.certfile, timeout=self.timeout)
else:
connection = SMTP(local_hostname=self.local_hostname, timeout=self.timeout)
log.info("Connecting to SMTP server %s:%s", self.host, self.port)
connection.set_debuglevel(self.debug)
connection.connect(self.host, self.port)
# Do TLS handshake if configured
connection.ehlo()
if self.tls in ('required', 'optional'):
if connection.has_extn('STARTTLS'):
connection.starttls(self.keyfile, self.certfile)
elif self.tls == 'required':
raise TransportException('TLS is required but not available on the server -- aborting')
# Authenticate to server if necessary
if self.username and self.password:
log.info("Authenticating as %s", self.username)
connection.login(self.username, self.password)
self.connection = connection
self.sent = 0
示例6: send_email
# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import starttls [as 别名]
def send_email(to, subject, body):
# create email
msg = MIMEMultipart()
msg['From'] = qiita_config.smtp_email
msg['To'] = to
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
# connect to smtp server, using ssl if needed
if qiita_config.smtp_ssl:
smtp = SMTP_SSL()
else:
smtp = SMTP()
smtp.set_debuglevel(False)
smtp.connect(qiita_config.smtp_host, qiita_config.smtp_port)
# try tls, if not available on server just ignore error
try:
smtp.starttls()
except SMTPException:
pass
smtp.ehlo_or_helo_if_needed()
if qiita_config.smtp_user:
smtp.login(qiita_config.smtp_user, qiita_config.smtp_password)
# send email
try:
smtp.sendmail(qiita_config.smtp_email, to, msg.as_string())
except Exception:
raise RuntimeError("Can't send email!")
finally:
smtp.close()
示例7: _send
# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import starttls [as 别名]
def _send(self, email_addrs, msg):
proto = self._conf['proto']
assert proto in ('smtp', 'starttls', 'ssl'), \
"Incorrect protocol: %s" % proto
try:
if proto == 'ssl':
session = SMTP_SSL(self._conf['fqdn'], self._conf['port'])
else:
session = SMTP(self._conf['fqdn'], self._conf['port'])
if proto == 'starttls':
session.ehlo()
session.starttls()
session.ehlo()
if self._conf['user'] is not None:
session.login(self._conf['user'], self._conf['pass'])
session.sendmail(self.sender, email_addrs, msg)
session.quit()
except Exception as e: # pragma: no cover
''' '''
print str(e)
示例8: send_msg
# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import starttls [as 别名]
def send_msg(self, msg, args):
server = SMTP_SSL(args.host, args.port) if args.ssl else SMTP(args.host, args.port)
if args.verbose:
server.set_debuglevel(1)
if args.starttls:
server.starttls()
#server.connect()
if args.user and args.password:
server.ehlo
server.login(args.user, args.password)
server.sendmail(args.from_address, ", ".join(args.to_addresses), msg.as_string().encode(super(Plugin, self).CHARSET))
server.quit()
示例9: send_mail
# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import starttls [as 别名]
def send_mail(from_, to, subject, text, html, smtp_server, username, password):
try:
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = from_
msg['To'] = to
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
conn = SMTP(smtp_server)
conn.set_debuglevel(False)
conn.login(username, password)
try:
conn.sendmail(from_, to, msg.as_string())
finally:
conn.close()
#except Exception, exc:
# sys.exit( "mail failed; %s" % str(exc) ) # give a error message
except:
return False
conn = imaplib.IMAP4(smtp_server, port = 143)
# Python 3.5
#context = ssl.create_default_context()
#conn.starttls(context=context)
conn.starttls()
r = conn.login(username, password)
if r[0] != 'OK':
return False
r = conn.select('INBOX.Sent')
if r[0] != 'OK':
return False
r = conn.append('INBOX.Sent', '', imaplib.Time2Internaldate(time.time()), msg.as_string().encode('utf-8'))
if r[0] != 'OK':
return False
return True
示例10: send_mails
# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import starttls [as 别名]
def send_mails(messages, host='localhost', port=25, user=None, password=None,
starttls=False, ssl=False, ssl_key=None, ssl_cert=None,
timeout=None):
"""
Send ``messages``.
:param Message messages: Message instance or list of Messages.
:param str host: hostname or ip of the SMTP server to use to send
the messages. Defaults to 'localhost'
:param int port: port the smtp server listens on. Defaults to 25.
Secure SMTP uses port 465, see ``ssl`` below.
:param str user: Username to authenticate with.
:param str password: Password for authentication.
:param bool starttls: If True, use STARTTLS. This is an SMTP extension
to initiate a secure connection with a SMTP server
listening on port 25.
:param bool ssl: Initialize a SSL protected connection to the
server. SSL protected SMTP typically runs on port
465. (Note that this is different then using the
``starttls`` option).
:param ssl_key str: SSL private key file, PEM format
:param ssl_cert str: SSL certificate chain file, PEM format
:param timeout int: timeout in seconds
"""
if ssl:
server = SMTP_SSL(host, port, timeout=timeout,
keyfile=ssl_key, certfile=ssl_cert)
else:
server = SMTP(host, port, timeout=timeout)
if starttls:
server.ehlo()
server.starttls()
server.ehlo()
if user and password:
server.login(user, password)
if isinstance(messages, Message):
server.sendmail(*messages.compile())
else:
for m in messages:
server.sendmail(*m.compile())
server.quit()
示例11: start_connection
# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import starttls [as 别名]
def start_connection(secure, server, port):
connection = None
if secure:
try:
connection = SMTP_SSL(server, port)
except Exception:
connection = None # SSL/TLS is not available, fallback to starttls
logging.info('Fall back to STARTTLS connection')
if connection is None:
connection = SMTP(server, port)
connection.set_debuglevel(True)
connection.starttls()
else:
connection = SMTP(server, port)
return connection
示例12: emit
# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import starttls [as 别名]
def emit(self, record: LogRecord) -> None:
"""
Emit a record.
Format the record and send it to the specified addresses.
:param record: The record to send.
:raise KeyboardInterrupt: If a keyboard interrupt occurs during mail transmission, it will be reraised.
:raise SystemExit: If a ``sys.exit()`` interrupts the mail transmission, it will be reraised.
"""
# noinspection PyBroadException
try:
port = self.mailport
if not port:
port = SMTP_SSL_PORT if self.ssl else SMTP_PORT
if self.ssl:
smtp = SMTP_SSL(self.mailhost, port, timeout=self.timeout)
else:
smtp = SMTP(self.mailhost, port, timeout=self.timeout)
msg = EmailMessage()
msg['From'] = self.fromaddr
msg['To'] = ','.join(self.toaddrs)
msg['Subject'] = self.getSubject(record)
msg['Date'] = email.utils.localtime()
msg.set_content(self.format(record))
if self.username:
if self.secure is not None:
smtp.ehlo()
smtp.starttls(*self.secure)
smtp.ehlo()
smtp.login(self.username, self.password)
smtp.send_message(msg)
smtp.quit()
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
self.handleError(record)
示例13: _sendEmail
# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import starttls [as 别名]
def _sendEmail(self , failText):
"""
Sends an email using the command line options
"""
failText = self._getEmailHeaders() + failText
s = None
if not self.opts.smtpServer:
return self._sendSendmail(failText)
if self.opts.smtpSSL:
s = SMTP_SSL()
else:
s = SMTP()
s.connect(self.opts.smtpServer , self.opts.smtpPort)
s.ehlo()
if self.opts.smtpTLS:
s.starttls()
if self.opts.smtpUser:
s.login(self.opts.smtpUser , self.opts.smtpPass)
s.sendmail(self.opts.mailFrom , self.opts.mailRecips , failText)
s.quit()
示例14: send_mail
# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import starttls [as 别名]
def send_mail(self):
smtp = random.choice(self.smtp)
print 'SMTP', smtp, self.sender
if self.smtp_ssl:
smtp = SMTP_SSL(smtp, self.smtp_port)
else:
smtp = SMTP(smtp, self.smtp_port)
if self.smtp_start_tls:
smtp.starttls()
if self.smtp_auth:
smtp.login(*self.sender)
self.subjects = []
for i in range(0, self.msg_per_connection):
msg = self.random_msg()
self.subjects.append(msg["subject"])
smtp.sendmail(self.sender[0], self.recipient[0],
msg.as_string())
self.sent += 1
示例15: send_email_alert
# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import starttls [as 别名]
def send_email_alert(content, content_type, subject, sender_email,
sender_password, sender_smtp_server, sender_port,
reciever_email, reciever_smtp_server,
receiver_port, use_ssl, use_tls):
"""
This function will send an email from the specified user to another
specified user. No smtp servers are assumed. SSL/TLS is supported.
All information needed must be specified.
"""
try:
# Setup Message
msg = MIMEText(content, content_type)
msg['Subject'] = subject
msg['From'] = sender_email
# Connect to SMTP Server
if use_ssl:
conn = SMTP_SSL(sender_smtp_server, sender_port)
Log.debug("Established connection with SMTP server")
else:
conn = SMTP(sender_smtp_server, sender_port)
Log.debug("Established connection with SMTP server")
if use_tls:
conn.ehlo()
conn.starttls()
conn.ehlo()
conn.set_debuglevel(0) # show communication with server if True
conn.login(sender_email, sender_password)
Log.debug("Logged in")
# Send Email
try:
conn.sendmail(sender_email, reciever_email, msg.as_string())
Log.debug("Sent mail")
finally:
conn.close()
except Exception, exc:
Log.error("Failed to send mail.")
Log.error("{}".format(exc))