本文整理汇总了Python中smtplib.SMTP.set_debuglevel方法的典型用法代码示例。如果您正苦于以下问题:Python SMTP.set_debuglevel方法的具体用法?Python SMTP.set_debuglevel怎么用?Python SMTP.set_debuglevel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类smtplib.SMTP
的用法示例。
在下文中一共展示了SMTP.set_debuglevel方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: on_modified
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import set_debuglevel [as 别名]
def on_modified(self, event):
if os.path.exists(self.log_file):
"""Cheque o tamanho do arquivo e remove se for maior que tamnho permitido"""
log_size = os.path.getsize(self.log_file)
if log_size > self.max_size:
print('##############################################')
print('log gerado: ', str(datetime.datetime.now()))
print('tamanho exedico...')
print('enviado notificação...')
""" Enviar notificação que o processo de reset do log foi realizado """
debuglevel = 0
smtp = SMTP()
smtp.set_debuglevel(debuglevel)
smtp.connect('', 587)
smtp.login('', 'mmnhbn')
from_addr = ""
to_addr = ""
date = datetime.datetime.now().strftime("%d/%m/%Y %H:%M")
message_text = "O log do squid foi removido as: {0}".format(date)
subj = "log do squid foi removido "
msg = message_text
smtp.sendmail(from_addr, to_addr, msg)
smtp.quit()
print('notificação enviada.... ')
print('arquivo deletado....')
os.remove(self.log_file)
# caso nao seja necessario crear o arquivo, descarte essas duas linhas
open(self.log_file, 'w+')
print('arquivo criando....')
示例2: _send
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import set_debuglevel [as 别名]
def _send( self ):
if not self._mailAddress:
gLogger.warn( "No mail address was provided. Mail not sent." )
return S_ERROR( "No mail address was provided. Mail not sent." )
if not self._message:
gLogger.warn( "Message body is empty" )
if not self._subject:
gLogger.warn( "Subject and body empty. Mail not sent" )
return S_ERROR ( "Subject and body empty. Mail not sent" )
mailString = "From: %s\nTo: %s\nSubject: %s\n%s\n"
addresses = self._mailAddress
if not type( self._mailAddress ) == type( [] ):
addresses = [self._mailAddress]
text = mailString % ( self._fromAddress, ', '.join( addresses ),
self._subject, self._message )
smtp = SMTP()
smtp.set_debuglevel( 0 )
try:
#smtp.connect( self._hostname )
smtp.connect()
self.sendmail( self._fromAddress, self._mailAddress, text )
except Exception, x:
gLogger.error( "Sending mail failed", str( x ) )
return S_ERROR( "Sending mail failed %s" % str( x ) )
示例3: send
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import set_debuglevel [as 别名]
def send(email_subject, email_content):
if 'DRC_SMTP_SERVER' not in os.environ:
logger.error("email variables not set!")
return 1
smtp_server = os.environ['DRC_SMTP_SERVER']
sender = os.environ['DRC_SENDER']
destination = [os.environ['DRC_DESTINATION']]
username = os.environ['DRC_USERNAME']
password = os.environ['DRC_PASSWORD']
try:
text_subtype = 'html'
msg = MIMEText(email_content, text_subtype)
msg['Subject'] = email_subject
msg['From'] = sender
conn = SMTP(smtp_server)
conn.set_debuglevel(False)
conn.login(username, password)
try:
logger.info('sending mail....')
conn.sendmail(sender, destination, msg.as_string())
finally:
conn.close()
return 0
except Exception, exc:
logger.info('sending failed: %s' % str(exc))
return 1
示例4: BaseMail
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import set_debuglevel [as 别名]
class BaseMail(object):
def __init__(self, conf):
self._message = MIMEText('')
self._message['From'] = formataddr(conf['sender'])
self._sender = conf['sender'][1]
self._recepients=[]
self._conf = conf
def __setattr__(self, key, val):
if key=='body':
self._message._payload=str(val)
elif key=='subject':
self._message['Subject']=val
else:
object.__setattr__(self, key, val)
def add_header(self, header_name, header_value):
self._message.add_header(header_name, header_value)
def add_to(self, name, email):
if name=='' or name is None:
name=False
self._recepients.append((name, email))
def send(self):
if len(self._recepients)==0:
return
emails=[email for name, email in self._recepients]
self._message['To']=", ".join([formataddr(pair)\
for pair in self._recepients])
# start server and send
conf = self._conf
self._server = SMTP(conf['smtp']['server'], conf['smtp']['port'])
if conf['smtp']['tls']: self._server.starttls()
self._server.login(conf['smtp']['user'], conf['smtp']['password'])
self._server.set_debuglevel(conf['debug_level'])
self._server.sendmail(self._sender, emails, self._message.as_string())
def __del__(self):
try:
server = self._server
except AttributeError:
pass
else:
server.quit()
示例5: send_email
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import set_debuglevel [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) = self.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, e:
print "Error sending email"
print e
print "Email message follows:"
print msg
示例6: sendErrorMail
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import set_debuglevel [as 别名]
def sendErrorMail():
from smtplib import SMTP
import datetime
import socket
localIp = socket.gethostbyname(socket.gethostname())
debuglevel = 0
smtp = SMTP()
smtp.set_debuglevel(debuglevel)
smtp.connect(smtpHost, smtpPort)
smtp.login(smtpUser, smtpPassword)
from_addr = "YES Playlist System <[email protected]>"
to_addr = smtpSendList
subj = "ERROR:Playlist file is open - SCRIPT CAN\'T RUN"
date = datetime.datetime.now().strftime("%d/%m/%Y %H:%M")
message_text = "-------------------------- ERROR -------------------------\n\n" \
"date: %s\n" \
"This is a mail from your YES playlist system.\n\n" \
"On IP: %s\n\n" \
"The file location:\n%s\n\n" \
"Is open and the Rating script can not run!\n" \
"Please close it and RUN THE SCRIPT AGAIN.\n\n" \
"-------------------------- ERROR -------------------------\n\n" \
"Thank you,\nPromotheus" % (date, localIp, playlistFile)
msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % (from_addr, to_addr, subj, date, message_text)
smtp.sendmail(from_addr, to_addr, msg)
smtp.quit()
示例7: test_email
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import set_debuglevel [as 别名]
def test_email(email_config):
subject = "Héèéè"
message_content = "Contentééééééé\r\nhûhûhhû\r\n"
msg = MIMEText(message_content.encode('utf-8'), 'plain', 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From'] = email_config["from_address"]
msg['To'] = email_config["to_test_address"]
smtp = SMTP(email_config["smtp_server"])
try:
smtp.set_debuglevel(True)
print("\rdbg smtp.noop()")
print(smtp.noop())
print("\rdbg smtp.starttls()")
print(smtp.starttls())
print("\rdbg smtp.login()")
print(smtp.login(email_config["from_username"], email_config["from_password"]))
print("\rdbg smtp.send_message()")
print(smtp.send_message(msg))
except Exception as inst:
print(inst)
print("\rdbg smtp.quit()")
print(smtp.quit())
示例8: email
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import set_debuglevel [as 别名]
def email(layout, layout_titles, output, fromaddr, toaddr, subject):
'''Send email notifications using local SMTP server'''
print '\nsending email to', toaddr
header = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n"
% (fromaddr, toaddr, subject))
header = header + 'MIME-Version: 1.0\r\n'
header = header + 'Content-Type: text/html\r\n\r\n'
body = '<pre>'
body = body + layout % layout_titles
body = body + '\n'
body = body + '='*75
body = body + '\n'
for p in output:
body = body + layout % (p[0], p[1], p[2], p[3])
body = body + '\n'
body = body + '</pre>'
msg = header + body
try:
server = SMTP('localhost')
server.set_debuglevel(0)
except error:
print "Unable to connect to SMTP server"
else:
server.sendmail(fromaddr, toaddr, msg)
server.quit()
示例9: run
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import set_debuglevel [as 别名]
def run(self):
# Serialize/flatten the message
fp = StringIO()
g = Generator(fp, mangle_from_=False)
g.flatten(self.msg)
contents = fp.getvalue()
for rcpt in self.rcpts:
rcpt = utils.find_address(rcpt)
smtp_server = self.MXLookup(rcpt)
conn = SMTP(smtp_server, timeout=30)
conn.set_debuglevel(True)
try:
conn.ehlo()
# FIXME: we should support an option to refuse to send messages
# if the server doesn't support STARTTLS.
if conn.has_extn('starttls'):
conn.starttls()
conn.ehlo()
# TODO: should catch exceptions here and either retry later or
# send a delivery report back to the author.
conn.sendmail(self.from_, rcpt, contents)
finally:
conn.close()
示例10: send_mail_exchange
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import set_debuglevel [as 别名]
def send_mail_exchange(serverInfo, fro, to, subject, text, attachments):
try:
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = fro
msg['To'] = COMMASPACE.join(to) # COMMASPACE==', ' used to display recipents in mail
msg['Date'] = formatdate(localtime=True)
print '[send_mail] attaching text...'
html_att = MIMEText(text, 'html', 'utf-8')
# att = MIMEText(attachments, 'plain', 'utf-8')
msg.attach(html_att)
# msg.attach(attachments)
for item in attachments:
part = MIMEBase('application', 'octet-stream') # 'octet-stream': binary data
# print '[send_mail] before set payload'
part.set_payload(open(item, 'rb').read())
encoders.encode_base64(part)
print '[send_mail] attaching file %s' % path.basename(item)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % path.basename(item))
msg.attach(part)
print '[send_mail] initializing smtp server...'
smtpserver = SMTP(serverInfo['name'], 25)
print '[sendmail] set debuglevel...'
smtpserver.set_debuglevel(False)
print '[send_mail] sending...'
# conn=smtpserver.connect(serverInfo['name'],25)
smtpserver.sendmail(msg['From'], [msg['To']], msg.as_string())
except Exception, e:
# you will catch a exception if tls is required
print "[send_mail] initializing mail failed; %s" % str(e) # give a error message
raise Exception(str(e))
示例11: _send
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import set_debuglevel [as 别名]
def _send( self ):
if not self._mailAddress:
gLogger.warn( "No mail address was provided. Mail not sent." )
return S_ERROR( "No mail address was provided. Mail not sent." )
if not self._message:
gLogger.warn( "Message body is empty" )
if not self._subject:
gLogger.warn( "Subject and body empty. Mail not sent" )
return S_ERROR ( "Subject and body empty. Mail not sent" )
mail = MIMEText( self._message , "plain" )
addresses = self._mailAddress
if not type( self._mailAddress ) == type( [] ):
addresses = [self._mailAddress]
mail[ "Subject" ] = self._subject
mail[ "From" ] = self._fromAddress
mail[ "To" ] = ', '.join( addresses )
smtp = SMTP()
smtp.set_debuglevel( 0 )
try:
smtp.connect()
smtp.sendmail( self._fromAddress, addresses, mail.as_string() )
except Exception, x:
return S_ERROR( "Sending mail failed %s" % str( x ) )
示例12: sendMail
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import set_debuglevel [as 别名]
def sendMail(sub,body,recipients):
global ldap
# IITB SMTP server
SMTPserver = "smtp-auth.iitb.ac.in"
# sender of the mail (Details removed)
sender = formataddr(("Placements","I AM THE SENDER (email id offcourse)"))
msg = MIMEMultipart('alternative')
msg['Subject'] = "[PB]: "+sub
msg['From'] = sender
msg['To'] = ",".join(recipients)
# Record the MIME types of both parts - text/plain and text/html.
part2 = MIMEText(body, 'html')
# 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(part2)
# Send the message via local SMTP server.
try:
conn = SMTP(SMTPserver)
conn.set_debuglevel(False)
conn.starttls()
conn.login(ldap[0],ldap[1])
try:
conn.sendmail(sender,recipients,msg.as_string())
finally:
conn.close()
except Exception, exc:
logger.error("Mail Send Failed: " + str(exc))
示例13: sendEmail
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import set_debuglevel [as 别名]
def sendEmail(to, subject, content):
retval = 1
if not(hasattr(to, "__iter__")):
to = [to]
destination = to
text_subtype = 'plain'
try:
msg = MIMEText(content, text_subtype)
msg['Subject'] = subject
msg['From'] = sender # some SMTP servers will do this automatically, not all
conn = SMTP(host=smtpHost, port=smtpPort)
conn.set_debuglevel(True)
#conn.login(smtpUsername, smtpPassword)
try:
if smtpUsername is not False:
conn.ehlo()
if smtpPort != 25:
conn.starttls()
conn.ehlo()
if smtpUsername and smtpPassword:
conn.login(smtpUsername, smtpPassword)
else:
print("::sendEmail > Skipping authentication information because smtpUsername: %s, smtpPassword: %s" % (smtpUsername, smtpPassword))
conn.sendmail(sender, destination, msg.as_string())
retval = 0
except Exception, e:
print("::sendEmail > Got %s %s. Showing traceback:\n%s" % (type(e), e, traceback.format_exc()))
retval = 1
finally:
conn.close()
示例14: SendEmail
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import set_debuglevel [as 别名]
def SendEmail(subject, msgText, to, user,password, alias, imgName, replyTo=None):
sender = alias
try:
conn = SMTP('smtp.gmail.com', 587)
msg = MIMEMultipart()
msg.attach(MIMEText(msgText, 'html'))
msg['Subject']= subject
msg['From'] = sender
msg['cc'] = to
#msg['cc'] = ', '.join(to)
if replyTo:
msg['reply-to'] = replyTo
if imgName != None:
fp = open(imgName, 'rb')
img = MIMEImage(fp.read(), _subtype="pdf")
fp.close()
img.add_header('Content-Disposition', 'attachment', filename = imgName)
msg.attach(img)
conn.ehlo()
conn.starttls()
conn.set_debuglevel(False)
conn.login(user, password)
try:
conn.sendmail(sender, to, msg.as_string())
finally:
conn.close()
except:
print "Unexpected error:", sys.exc_info()[0]
示例15: send_email
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import set_debuglevel [as 别名]
def send_email(content, destination, subject, file):
try:
msg = MIMEMultipart()
msg['Subject']= subject
msg['From'] = sender # some SMTP servers will do this automatically, not all
fp = open(file, 'rb') # Open File name "file"
img = MIMEImage(fp.read()) # Read the file.
fp.close() # Good housekeeping: close the file.
msg.attach(img) # Attach the file to the message.
conn = SMTP(SMTPserver, port = 587, timeout = 60) # timeout is critical here for long term health.
conn.ehlo()
conn.starttls()
conn.ehlo()
conn.login(USERNAME, PASSWORD)
conn.set_debuglevel(1)
try:
conn.sendmail(sender, destination, msg.as_string())
finally:
conn.close()
except Exception as exc:
# Print a message error!
print("Mail failed; %s" % str(exc))
print("Moving on!")