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


Python SMTP.close方法代码示例

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


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

示例1: run

# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import close [as 别名]
    def run(self):
        u"""Surchage de la méthode QThread.run()

        Envoit l'email et notifie les erreurs

        """
        try:
            # Pour gmail, connexion smtp_ssl avec port par défaut
            # et pas de starttls
            server = SMTP(self.__conf["serveur"], 587, "localhost",
                DEFAULT_TIMEOUT)
            server.starttls()
            server.login(self.__email['From'], self.__password)
            server.sendmail(self.__email['From'], self.__email['To'],
                self.__email.as_string())
            server.close()
            self.sentSignal.emit(MailSender.MAIL_ERROR_NONE)
        except SMTPAuthenticationError:
            self.sentSignal.emit(MailSender.MAIL_ERROR_AUTHENTICATION)
        except gaierror:
            self.sentSignal.emit(MailSender.MAIL_ERROR_CONNECTION)
        except SMTPServerDisconnected:
            self.sentSignal.emit(MailSender.MAIL_ERROR_TIMEOUT)
        except Exception, e:
            print e
            self.sentSignal.emit(MailSender.MAIL_ERROR_OTHER)
开发者ID:ncarrier,项目名称:gestion_ecole_de_musique,代码行数:28,代码来源:mail.py

示例2: send_msg_list

# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import close [as 别名]
def send_msg_list(msgs, sender=None):
    if len(msgs):
        connection = SMTP(str(settings.EMAIL_HOST), str(settings.EMAIL_PORT),
                local_hostname=DNS_NAME.get_fqdn())

        try:
            if (bool(settings.EMAIL_USE_TLS)):
                connection.ehlo()
                connection.starttls()
                connection.ehlo()

            if settings.EMAIL_HOST_USER and settings.EMAIL_HOST_PASSWORD:
                connection.login(str(settings.EMAIL_HOST_USER), str(settings.EMAIL_HOST_PASSWORD))

            if sender is None:
                sender = str(settings.DEFAULT_FROM_EMAIL)

            for email, msg in msgs:
                try:
                    connection.sendmail(sender, [email], msg)
                except Exception, e:
                    pass
            try:
                connection.quit()
            except socket.sslerror:
                connection.close()
        except Exception, e:
            pass
开发者ID:marinho,项目名称:osqa,代码行数:30,代码来源:mail.py

示例3: sendmail

# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import close [as 别名]
    def sendmail(self, destination, subject, message, attach = None):        
        try:
            msg = MIMEMultipart()

            msg['From'] = self.username
            msg['Reply-to'] = self.username
            msg['To'] = destination
            msg['Subject'] = subject

            msg.attach(MIMEText(message))

            if attach:
                part = MIMEBase('application', 'octet-stream')
                part.set_payload(open(attach, 'rb').read())
                Encoders.encode_base64(part)
                part.add_header('Content-Disposition',
                'attachment; filename="%s"' % os.path.basename(attach))
                msg.attach(part)

            mailServer = SMTP("smtp.gmail.com", 587)
            mailServer.ehlo()
            mailServer.starttls()
            mailServer.ehlo()
            try:
                mailServer.login(self.username, self.password)
                mailServer.sendmail(self.username, destination, msg.as_string())
            finally:
                mailServer.close()
        except Exception, exc:
            sys.exit("Failed to send mail; %s" % str(exc))
开发者ID:craigkerstiens,项目名称:simplerm,代码行数:32,代码来源:gmail_imap.py

示例4: run

# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import close [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()
开发者ID:postpopmail,项目名称:postpop,代码行数:27,代码来源:smtp_client.py

示例5: send_mail

# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import close [as 别名]
def send_mail(send_from, send_to, subject, text, files=[], server='smtp.typa.ru'):
	from smtplib import SMTP
	from os import path
	from email.MIMEMultipart import MIMEMultipart
	from email.MIMEBase import MIMEBase
	from email.MIMEText import MIMEText
	from email.Utils import COMMASPACE, formatdate
	from email import Encoders
	from email.header import Header

	assert type(send_to)==list
	assert type(files)==list
	msg = MIMEMultipart()
	msg['From'] = Header(send_from.decode("utf-8")).encode()
	msg['To'] = Header(COMMASPACE.join(send_to).decode("utf-8")).encode()
	msg['Date'] = formatdate(localtime=True)
	msg['Subject'] = Header(subject.decode("utf-8")).encode()
	msg.attach( MIMEText(text,'plain','UTF-8') )

	for f in files:
		part = MIMEBase('application', "octet-stream")
		part.set_payload( open(f,"rb").read() )
		Encoders.encode_base64(part)
		part.add_header('Content-Disposition', 'attachment; filename="%s"' % path.basename(f))
		msg.attach(part)
	smtp = SMTP(server, 25)
	smtp.sendmail(send_from, send_to, msg.as_string())
	smtp.close()		
开发者ID:Concord82,项目名称:Sync_Servers,代码行数:30,代码来源:sync_disk.py

示例6: __init__

# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import close [as 别名]
class Email:

    def __init__( self, name, psw ):
        self.name = name
        self.psw = psw
        self.to = raw_input('To : ')
        self.subject = 'Subject : %s\n' % raw_input('Subject : ')
        self.msg = raw_input('Msg : ')
        self.failed = {}

    def __str__( self ):
        return 'From : ' + self.name + '\nTo : ' + \
            str(self.to) + '\n' + self.subject + '\nBody : ' + self.msg
        
    def __start_server( self ):
        if SSL:
            self.server = SMTP_SSL( SERVER, PORT )
        else:
            self.server = SMTP( SERVER, PORT )
            self.server.ehlo()
            self.server.starttls()

        self.server.ehlo()

    def send( self ):
        self.__start_server()
        try:
            self.server.login( self.name, self.psw )
        except SMTPAuthenticationError:
            print('Wrong user or psw')
            sys.exit(0)
        else:
            self.failed = self.server.sendmail( self.name, self.to,
                                                self.subject + self.msg )
            self.server.close()
开发者ID:rexos,项目名称:pymail,代码行数:37,代码来源:mail.py

示例7: create_and_send_mail_messages

# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import close [as 别名]
def create_and_send_mail_messages(messages):
    if not settings.EMAIL_HOST:
        return

    sender = Header(unicode(settings.APP_SHORT_NAME), 'utf-8')
    sender.append('<%s>' % unicode(settings.DEFAULT_FROM_EMAIL))
    sender = u'%s <%s>' % (unicode(settings.APP_SHORT_NAME), unicode(settings.DEFAULT_FROM_EMAIL))

    try:
        connection = SMTP(str(settings.EMAIL_HOST), str(settings.EMAIL_PORT))
        """
        connection = SMTP(str(settings.EMAIL_HOST), str(settings.EMAIL_PORT),
                          local_hostname=DNS_NAME.get_fqdn())
        """
        
        if (bool(settings.EMAIL_USE_TLS)):
            connection.ehlo()
            connection.starttls()
            connection.ehlo()

        if settings.EMAIL_HOST_USER and settings.EMAIL_HOST_PASSWORD:
            connection.login(str(settings.EMAIL_HOST_USER), str(settings.EMAIL_HOST_PASSWORD))

        if sender is None:
            sender = str(settings.DEFAULT_FROM_EMAIL)

        for recipient, subject, html, text, media in messages:
            msgRoot = MIMEMultipart('related')

            msgRoot['Subject'] = Header(subject, 'utf-8')
            msgRoot['From'] = sender

            to = Header(recipient.username, 'utf-8')
            to.append('<%s>' % recipient.email)
            msgRoot['To'] = to

            #msgRoot.preamble = 'This is a multi-part message from %s.' % unicode(settings.APP_SHORT_NAME).encode('utf8')

            msgAlternative = MIMEMultipart('alternative')
            msgRoot.attach(msgAlternative)

            msgAlternative.attach(MIMEText(text.encode('utf-8'), _charset='utf-8'))
            msgAlternative.attach(MIMEText(html.encode('utf-8'), 'html', _charset='utf-8'))

            for alias, location in media.items():
                fp = open(location, 'rb')
                msgImage = MIMEImage(fp.read())
                fp.close()
                msgImage.add_header('Content-ID', '<'+alias+'>')
                msgRoot.attach(msgImage)

            try:
                connection.sendmail(sender, [recipient.email], msgRoot.as_string())
            except Exception, e:
                logging.error("Couldn't send mail using the sendmail method: %s" % e)

        try:
            connection.quit()
        except socket.sslerror:
            connection.close()
开发者ID:yyaadet,项目名称:osqa-cn,代码行数:62,代码来源:mail.py

示例8: main

# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import close [as 别名]
def main(smtp_data, email_data, address):
    """
    Main function
    """
    month = datetime.now().month # Loading the current month
    text = """<p>Olá,<br>
    Vocês poderiam me enviar o boleto do aluguel do mês atual, com vencimento
    no próximo dia 10?
    Meu imóvel é o da <b>{address}</b></p>
    <p>Obrigado!</p>
    """
    subject = "Boleto de aluguel do mês {month}"

    message = MIMEText(text.format(address=address), 'html')
    message['Subject'] = subject.format(month=month)
    message['From'] = email_data['sender']
    message['To'] = email_data['receiver']
    message['Reply-To'] = email_data['reply_to']

    server = SMTP(host=smtp_data['server'], port=smtp_data['port'])
    server.ehlo()
    server.starttls()
    server.login(smtp_data['username'], smtp_data['password'])
    server.send_message(message)
    server.close()
开发者ID:fbidu,项目名称:gmailBots,代码行数:27,代码来源:imobiliaria.py

示例9: sendFildByMail

# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import close [as 别名]
def sendFildByMail(config):
    message = MIMEMultipart()
    message['from'] = config['from']
    message['to'] = config['to']
    message['Reply-To'] = config['from']
    message['Subject'] = config['subject']
    message['Date'] = time.ctime(time.time())

    message['X-Priority'] = '3'
    message['X-MSMail-Priority'] = 'Normal'
    message['X-Mailer'] = 'wendell client'
    message['X-MimeOLE'] = 'product by wendell client v1.0.00'

    # 注意这一段
    f = open(config['file'], 'rb')
    file = MIMEApplication(f.read())
    f.close()
    file.add_header('Content-Disposition', 'attachment',
                    filename = os.path.basename(config['file']))
    message.attach(file)
    smtp = SMTP(config['server'], config['port'])
    smtp.ehlo()
    smtp.starttls()
    smtp.ehlo()
    smtp.login(config['username'], config['password'])

    print 'OK'
    print 'Send ...'

    smtp.sendmail(config['from'], [config['from'], config['to']], message.as_string())

    print 'OK'
    smtp.close()
开发者ID:wendellyi,项目名称:mail-tool,代码行数:35,代码来源:mail-tool.py

示例10: flush

# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import close [as 别名]
    def flush(self):
        from smtplib import SMTP
        import settings, logging

        if not self.messages:
            return

        msg = 'To: ' + settings.to_addr + '\n'
        msg += 'From: ' + settings.from_addr + '\n'
        if len(self.messages) == 1:
            msg += 'Subject: mmonitor: ' + self.messages[0][:200] + '\n'
        else:
            msg += 'Subject: mmonitor: multiple notices\n'
        msg += '\n\n'
        msg += '\n'.join(self.messages)
        msg += '\n\n'

        logging.info('sending mail:\n%s', '\n'.join(self.messages))
        smtp = SMTP(settings.smtp_host, settings.smtp_port)
        if settings.smtp_tls:
            smtp.starttls()
        smtp.ehlo_or_helo_if_needed()
        if settings.smtp_user:
            smtp.login(settings.smtp_user, settings.smtp_password)
        smtp.sendmail(settings.from_addr, settings.to_addr, msg)
        smtp.close()
        self.messages = []
开发者ID:mixpanel,项目名称:mmonitor,代码行数:29,代码来源:mail.py

示例11: _emailer

# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import close [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()
开发者ID:Erni1619,项目名称:ganga,代码行数:35,代码来源:Checker.py

示例12: send_mail

# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import close [as 别名]
    def send_mail(self):
        """Used to send the email."""
    
        # Set up the message basics
        msg = MIMEMultipart()
        msg['From'] = self.from_email
        msg['To'] = ', '.join(self.mailing_list)
        msg['Subject'] = self.subject
    
        print msg
        # Set the message body
        msg.attach(MIMEText(self.body))
    
        # Process attachments
        for filename in self.attachments:
            with open(filename, "rb") as f:
                msg.attach(MIMEApplication(
                    f.read(),
                    Content_Disposition='attachment; filename="%s"' % basename(filename),
                    Name=basename(filename)
                ))
    

        # Configure and send the mail
        s = SMTP('localhost')
        s.sendmail(self.from_email, self.mailing_list,  msg.as_string())
        s.close()
开发者ID:geraintanderson,项目名称:Snippets,代码行数:29,代码来源:mailer.py

示例13: send_mail

# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import close [as 别名]
def send_mail(email, senha, receber, mensagem, vezes):
    try:
        from smtplib import SMTP
        import time

        x = 1
        gmail = SMTP('smtp.gmail.com:587')
        gmail.ehlo()
        gmail.starttls()
        gmail.login(email, senha)
        while x <= vezes:
            gmail.sendmail(email, receber, mensagem)
            print("[%d]Enviado!" % x)
            x += 1

        gmail.close()
        time.sleep(2)


    except KeyboardInterrupt:
        print("\n\n[!] Interrompendo o envio de emails!")
        time.sleep(3)

    except ImportError:
        print("[!] Erro de importação, biblioteca: smtplib,time")

    except:
        print("\n[!] Erro de Autenticação! (Logins externos não estão permitidos no seu gmail ou Login incorreto ou Rementente não encontrado")
        print("\nEspere 10 segundos")
        time.sleep(10)
开发者ID:ISyther,项目名称:FSCSPAMMER,代码行数:32,代码来源:FSCSPAMMER.py

示例14: execute

# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import close [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.')
开发者ID:Erni1619,项目名称:ganga,代码行数:62,代码来源:FileEmailer.py

示例15: email_facture

# 需要导入模块: from smtplib import SMTP [as 别名]
# 或者: from smtplib.SMTP import close [as 别名]
def email_facture():
    msg = MIMEMultipart()
    enc = 'latin-1'
    msg['Subject'] = request.form['subject'].encode(enc)
    msg['From'] = u'Société Roucet <[email protected]>'.encode(enc)
    to_list = re.split('[ ,;:\t\n]+', request.form['email_addresses'])
    msg['To'] = COMMASPACE.join(to_list)
    msg['Reply-to'] = '[email protected]'
    try:
        msg.attach(MIMEText(request.form['msg'].encode(enc), 'plain', enc))
    except:
        msg.attach(MIMEText(request.form['msg'].encode('utf8'), 'plain', 'utf8'))
    if 'include_pdf' in request.form:
        out_fn = _generate_facture(g, request.form['no_commande_facture'])
        part = MIMEApplication(open(out_fn, "rb").read())
        part.add_header('Content-Disposition', 'attachment', filename="facture_roucet.pdf")
        msg.attach(part)
    mailer = SMTP('mail.roucet.com', 587)
    mailer.login('[email protected]', SMTP_PW)
    mailer.sendmail(msg['From'], to_list, msg.as_string())
    mailer.close()
    # if user is admin, set facture_est_envoyee to True, if repr, this will
    # be done in the next ajax call (to /representant/set_facture_est_envoyee)
    if not current_user.u['representant_id']:
        pg.update(g.db.cursor(), 'commande', set={'facture_est_envoyee': True},
                  where={'no_commande_facture': request.form['no_commande_facture']})
        g.db.commit()
    return {'success': True}
开发者ID:cjauvin,项目名称:vinum,代码行数:30,代码来源:commande.py


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