本文整理汇总了Python中smtplib.SMTP.connect方法的典型用法代码示例。如果您正苦于以下问题:Python SMTP.connect方法的具体用法?Python SMTP.connect怎么用?Python SMTP.connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类smtplib.SMTP
的用法示例。
在下文中一共展示了SMTP.connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: EmailService
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import connect [as 别名]
class EmailService(object):
def __init__(self):
config = services.get(Config)
self._smtp = SMTP()
self._host = config.get(self.config_section, "host", "localhost")
self._port = config.get(self.config_section, "port", SMTP_PORT)
@property
def config_section(self):
return type(self).__name__
def sendemail(self, email):
"""
:type email: nxtools.hooks.entities.mail.Email
"""
mail = MIMEText(email.body, "plain", "UTF-8")
mail.add_header("From", email.sender)
mail.add_header("To", email.to)
mail.add_header("Reply-To", email.reply_to)
mail.add_header("Subject", email.subject)
self._smtp.connect(self._host, self._port)
self._smtp.sendmail(email.sender, email.to, mail.as_string())
self._smtp.quit()
示例2: sendEmail
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import connect [as 别名]
def sendEmail(self, botid, jobid, cmd, arg='', attachment=[]):
if (botid is None) or (jobid is None):
sys.exit("[-] You must specify a client id (-id) and a jobid (-job-id)")
sub_header = 'gdog:{}:{}'.format(botid, jobid)
msg = MIMEMultipart()
msg['From'] = sub_header
msg['To'] = gmail_user
msg['Subject'] = sub_header
msgtext = json.dumps({'cmd': cmd, 'arg': arg})
msg.attach(MIMEText(str(infoSec.Encrypt(msgtext))))
for attach in attachment:
if os.path.exists(attach) == True:
part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="{}"'.format(os.path.basename(attach)))
msg.attach(part)
mailServer = SMTP()
mailServer.connect(server, server_port)
mailServer.starttls()
mailServer.login(gmail_user,gmail_pwd)
mailServer.sendmail(gmail_user, gmail_user, msg.as_string())
mailServer.quit()
print "[*] Command sent successfully with jobid: {}".format(jobid)
示例3: generate_email_alerter
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import connect [as 别名]
def generate_email_alerter(to_addrs, from_addr=None, use_gmail=False,
username=None, password=None, hostname=None, port=25):
if not from_addr:
from_addr = getuser() + "@" + gethostname()
if use_gmail:
if username and password:
server = SMTP('smtp.gmail.com', 587)
server.starttls()
else:
raise OptionValueError('You must provide a username and password to use GMail')
else:
if hostname:
server = SMTP(hostname, port)
else:
server = SMTP()
server.connect()
if username and password:
server.login(username, password)
def email_alerter(message, subject='SiteWatcher: You have an alert!'):
server.sendmail(from_addr, to_addrs, 'To: %s\r\nFrom: %s\r\nSubject: %s\r\n\r\n%s' % (", ".join(to_addrs), from_addr, subject, message))
return email_alerter, server.quit
示例4: reply_mail
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import connect [as 别名]
def reply_mail(mail_obj, is_success=True, body=None):
print "begin to reply email to [%s] " %(mail_obj["From"] or mail_obj["Reply-To"])
original = mail_obj
config = dict(load_config().items("smtp"))
smtp = SMTP()
smtp.connect('smtp.gmail.com', 587)
smtp.starttls()
smtp.login(config["user"], config["pass"])
from_addr = "[email protected]"
to_addr = original["Reply-To"] or parse_base64_mail_mime(original["From"])
subject, encoding = decode_header(original["Subject"])[0]
if encoding:
subject = subject.decode(encoding)
subj = u"Re: " + subject
else:
subj = u"Re: " + subject
date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )
message_text = "Hello\nThis is a mail from your server\n\nBye\n"
if body is not None:
msg = u"From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, body.replace('\\n','\n') )
else:
msg = u"From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( from_addr, to_addr, subj, date, is_success.replace('\\n','\n') )
smtp.sendmail(from_addr, to_addr, unicode(msg))
smtp.quit()
print "replied email to [%s] " %(parse_base64_mail_mime(mail_obj["From"]) or mail_obj["Reply-To"])
示例5: _send
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import connect [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 ) )
示例6: send_email
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import connect [as 别名]
def send_email(to_email,subject,message):
# send the message
smtp = SMTP()
smtp.connect('smtp.mandrillapp.com', 587)
smtp.login(os.environ.get('MANDRILL_USERNAME'), os.environ.get('MANDRILL_APIKEY'))
from_addr = "Tindfell <[email protected]>"
to_addr = [to_email]
date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )
Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')
msg = MIMEMultipart("alternative")
msg['From'] = Header(from_addr.encode('utf-8'), 'UTF-8').encode()
msg['To'] = Header(', '.join(to_addr).encode('utf-8'), 'UTF-8').encode()
msg['Subject'] = Header(subject.encode('utf-8'), 'UTF-8').encode()
msg.attach(MIMEText(message.encode('utf-8'),'plain','utf-8'))
#msg.attach(MIMEText(message.encode('utf-8'),'html','utf-8'))
io = StringIO()
g = Generator(io, False) # second argument means "should I mangle From?"
g.flatten(msg)
# For Degubbing
#print io.getvalue()
# send the message!
smtp.sendmail(from_addr, to_addr, io.getvalue())
smtp.quit()
return
示例7: on_modified
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import connect [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....')
示例8: _emailer
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import connect [as 别名]
def _emailer(self, subject, text):
#Function to email list on startup of ganga (following restart by cronjob)
from email.MIMEText import MIMEText
from smtplib import SMTP
emailcfg = Ganga.Utility.Config.getConfig('Robot')
host = emailcfg['FileEmailer_Host']
from_ = emailcfg['FileEmailer_From']
recipients = [recepient.strip() for recepient in \
emailcfg['FileEmailer_Recipients'].split(',') \
if recepient.strip()]
subject = "Ganga - TestRobot automatic restart by crontab"
if not recipients:
logger.warn('No recpients specified - email will not be sent')
return
logger.info("emailing files to %s." %(recipients))
text = "GangaTestRobot restarted on: %s" %(datetime.datetime.now().strftime("%H:%M:%S %d %b %Y"))
msg = MIMEText(text)
msg['Subject'] = subject
msg['From'] = from_
msg['To'] = ', '.join(recipients)
#send message
session = SMTP()
try:
session.connect(host)
session.sendmail(from_, recipients, msg.as_string())
session.quit()
except:
logger.error("Failed to send notification of start-up")
session.close()
示例9: _send
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import connect [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 ) )
示例10: Check_Server
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import connect [as 别名]
def Check_Server(self,server,port):
try:
_smtp=SMTP()
_smtp.connect(self.server, self.port)
return True
except:
return False
示例11: send_email
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import connect [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
示例12: execute
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import connect [as 别名]
def execute(self, runid):
"""Send files as an email.
Keyword arguments:
runid -- A UTC ID string which identifies the run.
The following parameters are loaded from the Robot configuration:
FileEmailer_Host e.g. localhost or localhost:25
FileEmailer_Type e.g. text or html
FileEmailer_From e.g. [email protected]
FileEmailer_Recipients e.g. [email protected], [email protected]
FileEmailer_Subject e.g. Report ${runid}.
FileEmailer_TextFile e.g. ~/gangadir/robot/report/${runid}.txt
FileEmailer_HtmlFile e.g. ~/gangadir/robot/report/${runid}.html
If Recipients are not specified then no email is sent.
In Subject, TextFile and HtmlFile the token ${runid} is replaced by the
runid argument.
If Type is text, then TextFile is sent.
If Type is html, then HtmlFile is sent, or if TextFile is also specified
then a multipart message is sent containing TextFile and HtmlFile.
"""
# get configuration properties
host = self.getoption('FileEmailer_Host')
type = self.getoption('FileEmailer_Type')
from_ = self.getoption('FileEmailer_From')
# extract recipients ignoring blank entries
recipients = [recipient.strip() for recipient in \
self.getoption('FileEmailer_Recipients').split(',') \
if recipient.strip()]
subject = Utility.expand(self.getoption('FileEmailer_Subject'), runid = runid)
textfilename = Utility.expand(self.getoption('FileEmailer_TextFile'), runid = runid)
htmlfilename = Utility.expand(self.getoption('FileEmailer_HtmlFile'), runid = runid)
if not recipients:
logger.warn('No recipients specified. Email will not be sent.')
return
logger.info('Emailing files to %s.', recipients)
# build message
if type == 'html':
msg = self._gethtmlmsg(textfilename, htmlfilename)
else:
msg = self._gettextmsg(textfilename)
msg['Subject'] = subject
msg['From'] = from_
msg['To'] = ', '.join(recipients)
# send message
session = SMTP()
try:
session.connect(host)
session.sendmail(from_, recipients, msg.as_string())
session.quit()
finally:
session.close()
logger.info('Files emailed.')
示例13: _connect
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import connect [as 别名]
def _connect(self, tracker):
server = SMTP()
if self._auth_type=='POP_BEFORE_SMTP':
tracker.update(_('Authenticating...'))
try:
self._pop_account.auth_and_quit()
except POPError:
tracker.error(_('Error authenticating using POP'))
return None
try:
tracker.update(_('Connecting to server...'))
server.connect(self._host, self._port)
except:
tracker.error(_('Error connecting to %s:%d' % (self._host, self._port)))
return None
if self._auth_type=='SSL':
try:
tracker.update(_('Authenticating...'))
server.ehlo()
server.starttls()
server.ehlo()
server.login(self._username, self._password)
except:
tracker.error(_('Error authenticating %s' % self._username))
return None
return server
示例14: sendErrorMail
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import connect [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()
示例15: myMessage
# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import connect [as 别名]
def myMessage(request):
form = MessageForm(request.POST or None)
context = {'form':form}
template = 'message/monMessage.html'
if form.is_valid():
# print(form.cleaned_data)
titre = form.cleaned_data['titre']
auteur = form.cleaned_data['auteur']
contenu = form.cleaned_data['contenu']
sujet = form.cleaned_data['sujet']
email = form.cleaned_data['mail']
form.save()
from_addr = '[email protected]'
to_addrs = ['[email protected]']
msg = "Vous avez recu un nouveau message : \n" + "auteur : " + auteur + "\n" + "titre : " \
+ titre + "\n" + "sujet : " + sujet + "\n" + "contenu : " + contenu + "\n"
msg.encode('utf-8')
s = SMTP()
s.connect('smtp.webfaction.com')
s.login('istarosel','igor1975staroseltsev')
s.sendmail(from_addr, to_addrs, msg)
messages.success(request, 'Votre mail a été envoyé')
return render(request,template,context)