• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python smtplib.SMTP类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: send_email

def send_email(request):
    try:
        recipients = request.GET["to"].split(",")
        url = request.GET["url"]
        proto, server, path, query, frag = urlsplit(url)
        if query:
            path += "?" + query
        conn = HTTPConnection(server)
        conn.request("GET", path)
        try:  # Python 2.7+, use buffering of HTTP responses
            resp = conn.getresponse(buffering=True)
        except TypeError:  # Python 2.6 and older
            resp = conn.getresponse()
        assert resp.status == 200, "Failed HTTP response %s %s" % (resp.status, resp.reason)
        rawData = resp.read()
        conn.close()
        message = MIMEMultipart()
        message["Subject"] = "Graphite Image"
        message["To"] = ", ".join(recipients)
        message["From"] = "[email protected]%s" % gethostname()
        text = MIMEText("Image generated by the following graphite URL at %s\r\n\r\n%s" % (ctime(), url))
        image = MIMEImage(rawData)
        image.add_header("Content-Disposition", "attachment", filename="composer_" + strftime("%b%d_%I%M%p.png"))
        message.attach(text)
        message.attach(image)
        s = SMTP(settings.SMTP_SERVER)
        s.sendmail("[email protected]%s" % gethostname(), recipients, message.as_string())
        s.quit()
        return HttpResponse("OK")
    except:
        return HttpResponse(format_exc())
开发者ID:nyerup,项目名称:graphite-web,代码行数:31,代码来源:views.py


示例2: send_email

def send_email(subject, message, addr):
    try:
        if (Config.get("smtp", "port") == "0"):
            smtp = SMTP("localhost")
        else:
            smtp = SMTP(Config.get("smtp", "host"), Config.get("smtp", "port"))

        if not ((Config.get("smtp", "host") == "localhost") or (Config.get("smtp", "host") == "127.0.0.1")):
            try:
                smtp.starttls()
            except SMTPException as e:
                raise SMSError("unable to shift connection into TLS: %s" % (str(e),))

            try:
                smtp.login(Config.get("smtp", "user"), Config.get("smtp", "pass"))
            except SMTPException as e:
                raise SMSError("unable to authenticate: %s" % (str(e),))

        try:
             smtp.sendmail(Config.get("smtp", "frommail"), addr, "To:%s\nFrom:%s\nSubject:%s\n%s\n" % (addr, "\"%s\" <%s>" % (
                                                           Config.get("Connection", "nick"), Config.get("smtp", "frommail")), subject, message))
        except SMTPSenderRefused as e:
            raise SMSError("sender refused: %s" % (str(e),))
        except SMTPRecipientsRefused as e:
            raise SMSError("unable to send: %s" % (str(e),))

        smtp.quit()

    except (socket.error, SSLError, SMTPException, SMSError) as e:
        return "Error sending message: %s" % (str(e),)
开发者ID:liam-wiltshire,项目名称:merlin,代码行数:30,代码来源:string.py


示例3: sendmail

def sendmail(content=None):

    "Send email to my 163mail"

    if content is None:
        print 'content is None'
        return False
    try:
        from smtplib import SMTP
        from email.mime.text import MIMEText

        from_addr = "[email protected]"
        password = "hanks0722"
        to_addr = "[email protected]"
        email_client = SMTP(host='smtp.163.com')
        email_client.login(from_addr, password)

        #create message
        msg = MIMEText(content, _charset='utf-8')
        msg['Subject'] = "Interview Status Changed!"
        email_client.sendmail(from_addr, to_addr, msg.as_string())
        return True
    except Exception, e:
        print e
        return False
开发者ID:Hankszhang,项目名称:myDemos,代码行数:25,代码来源:query.py


示例4: deliver

    def deliver(self, subject, body, recipients=False):
        """
        sends an email using the [email protected] account
        """

        if not recipients:
            recipients = self.recipients

        recipients = recipients.split(';')

        message = MIMEText(body)
        message['Subject'] = subject
        message['From'] = self.sender
        message['To'] = ','.join(recipients)

        if self.testing:
            print('***Begin Test Email Message***')
            print(message)
            print('***End Test Email Message***')

            return

        s = SMTP(self.server, self.port)

        s.sendmail(self.sender, recipients, message.as_string())
        s.quit()

        print('email sent')
开发者ID:agrc,项目名称:Crash-db,代码行数:28,代码来源:mailman.py


示例5: send_email

def send_email(request):
  try:
    recipients = request.GET['to'].split(',')
    url = request.GET['url']
    proto, server, path, query, frag = urlsplit(url)
    if query: path += '?' + query
    conn = HTTPConnection(server)
    conn.request('GET',path)
    resp = conn.getresponse()
    assert resp.status == 200, "Failed HTTP response %s %s" % (resp.status, resp.reason)
    rawData = resp.read()
    conn.close()
    message = MIMEMultipart()
    message['Subject'] = "Graphite Image"
    message['To'] = ', '.join(recipients)
    message['From'] = '[email protected]%s' % gethostname()
    text = MIMEText( "Image generated by the following graphite URL at %s\r\n\r\n%s" % (ctime(),url) )
    image = MIMEImage( rawData )
    image.add_header('Content-Disposition', 'attachment', filename="composer_" + strftime("%b%d_%I%M%p.png"))
    message.attach(text)
    message.attach(image)
    s = SMTP(settings.SMTP_SERVER)
    s.sendmail('[email protected]%s' % gethostname(),recipients,message.as_string())
    s.quit()
    return HttpResponse( "OK" )
  except:
    return HttpResponse( format_exc() )
开发者ID:Cue,项目名称:graphite,代码行数:27,代码来源:views.py


示例6: sendEmail

    def sendEmail(self, subject, body, toAddress=False):
        """
        sends an email using the [email protected] account
        """

        if not toAddress:
            toAddress = self.toAddress
        toAddress = toAddress.split(";")

        message = MIMEText(body)
        message["Subject"] = subject
        message["From"] = self.fromAddress
        message["To"] = ",".join(toAddress)

        if not self.testing:
            s = SMTP(self.server, self.port)

            s.sendmail(self.fromAddress, toAddress, message.as_string())
            s.quit()

            print("email sent")
        else:
            print("***Begin Test Email Message***")
            print(message)
            print("***End Test Email Message***")
开发者ID:ZachBeck,项目名称:agrc.python,代码行数:25,代码来源:messaging.py


示例7: send_email

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(prefs.get('SMTP_HOST'),
                    prefs.get('SMTP_PORT'))

        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
开发者ID:real-toster,项目名称:denyhosts,代码行数:34,代码来源:util.py


示例8: process_message

    def process_message(self, message):
        """Send emails.

        Args:
            message: dict instance containing email info.
                     Fields:
                         type [REQUIRED]: HR_ASC / HR_DESC
                         attachments [OPTIONAL]: recorded images base64 encoded
        """
        self.logger.info("Sending email to %s" % RECEIVER)
        if not message.get('type'):
            self.logger.error('Received message has no type (it should have '
                              'been one of the following: HR_ASC/HR_DESC): %r')
            return

        if not message.get('attachments'):
            message = self.compose_message_without_attachments(message)
        else:
            message = self.compose_message_with_attachments(message)

        try:
            smtpObj = SMTP('localhost')
            smtpObj.sendmail(SENDER, RECEIVER, message)      
            self.logger.info("Successfully sent email to %s", RECEIVER)
        except SMTPException as e:
            self.logger.error("Unable to send email to %s: %r", RECEIVER, e)
开发者ID:dianatatu,项目名称:amilab-basis,代码行数:26,代码来源:email_sender.py


示例9: monitor_score_rank

    def monitor_score_rank(self):
        """
        监控博客积分及排名的变化
        :return:
        """
        while True:
            self.get_blog_ranks()
            if self.score != self.his_score or self.rank != self.his_rank:
                email_client = SMTP(host = 'smtp.126.com')
                email_client.login('[email protected]','******')
                mail_title = '[e-notice]:blog-rank-changes'
                # mail_body = "[%s]time-(score,rank):old-(%s,%s),now-(%s,%s)" \
                #             % (
                #                 self.id,
                #                 self.his_score, self.his_rank,
                #                 self.score, self.rank
                #             )
                msg_body = "%s, at %s, you score: %s, rank: %s" %(self.id, time.ctime(), self.score, self.rank)
                msg = MIMEText(msg_body,_charset='utf-8')
                msg['Subject'] = mail_title
                email_client.sendmail('[email protected]','[email protected]',msg.as_string())
                self.his_score = self.score
                self.his_rank = self.rank
 
            sleep(self.gap_seconds)
开发者ID:cotyb,项目名称:python-script,代码行数:25,代码来源:cnblogs.py


示例10: send_mail

def send_mail(subject, sender, recipient, text, server, files=[]):
    """Sends email with attachment"""

    # Create the enclosing (outer) message
    outer = MIMEMultipart()
    outer['Subject'] = subject
    outer['To'] = recipient
    outer['From'] = sender
    outer.preamble = 'You will not see this in a MIME-aware mail reader.'

    msg = MIMEText(text)
    outer.attach(msg)

    for filename in files:
        ctype = 'application/octet-stream'
        maintype, subtype = ctype.split('/', 1)
        fp = open(filename, 'rb')
        msg = MIMEBase(maintype, subtype)
        msg.set_payload(fp.read())
        fp.close()
        # Encode the payload using Base64
        encoders.encode_base64(msg)
        # Set the filename parameter
        msg.add_header('Content-Disposition', 'attachment', filename=filename)
        outer.attach(msg)

    composed = outer.as_string()
    session = SMTP('localhost')
    session.sendmail(sender, recipient, composed)
    session.quit()
开发者ID:roboslone,项目名称:RTool,代码行数:30,代码来源:__init__.py


示例11: notify

    def notify(self, seminar):
        """
        Notify seminar
        """
        import re 
        from datetime import datetime
        from smtplib import SMTP
        from email.mime.text import MIMEText
        from email.header import Header

        dt = datetime.combine(seminar.date, seminar.time)

        format_values = (seminar.title, '\n'.join(['  ' + c for c in seminar.contents]), seminar.place)
        datetime_formatter = lambda matches: dt.strftime(matches.group(0))
        datetime_pattern = re.compile('%-?[a-zA-Z]')

        message_body = datetime_pattern.sub(datetime_formatter, self.message.format(*format_values))

        message = MIMEText(message_body, _charset = 'UTF-8')
        message['Subject'] = Header(datetime_pattern.sub(datetime_formatter, self.subject.format(*format_values)), 'UTF-8').encode()
        message['From'] = self.from_
        message['To'] = ', '.join(self.to)

        smtp = SMTP(self.host, self.port)
        smtp.sendmail(self.from_, self.to, message.as_string())
        smtp.quit()
开发者ID:ukatama,项目名称:seminarnotifier,代码行数:26,代码来源:notifier.py


示例12: mailtrn

def mailtrn(trndir,fltid,lognum):
  from smtplib import SMTP
  from email.mime.text import MIMEText
  from socket import gethostname
  from getpass import getuser

  # Create a text/plain message from file.
  trnfile = str.format('{0:s}/{1:s}/ema-{1:s}-log-{2:04d}.trn',trndir,fltid,lognum)
  if options.verbose:
    print('compute trnfile: ', trnfile)
  fp = open(trnfile, 'rt')
  msg = MIMEText(fp.read())
  fp.close()

  # msg = MIMEText('New trnfile: ' + trnfile)


  host = gethostname()
  user =  getuser()

  From = '[email protected]'
  From = user+'@'+host
  To = '[email protected]'
  Reply_To = '[email protected]'

  msg['Subject'] = str.format('emarun.py {0:s} {1:04d}',fltid,lognum)
  msg['From'] = From
  msg['To'] = To
  msg.add_header('Reply-To', Reply_To)

  s = SMTP('localhost')
  s.sendmail(From, To, msg.as_string())
  s.quit()
开发者ID:jklymak,项目名称:EMAPEXLabSea15,代码行数:33,代码来源:emarun.py


示例13: sendMail

def sendMail(rcpt, subject, body, files=[]):

    send_from = "[email protected]"
    msg = MIMEMultipart()
    msg['From'] = send_from

    if rcpt is None: rcpt = admin_email


    msg['To'] = COMMASPACE.join(rcpt)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject
    
    msg.attach( MIMEText(body) )
    
    for f,b in files:
        logger.debug("SEND ATT "+f)
        part = MIMEBase('application', "octet-stream")
        part.set_payload(open(f).read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(b))
        msg.attach(part)
    

    server = SMTP(smtphost, smtpport)
    server.sendmail(send_from, rcpt, msg.as_string())
    server.close()
开发者ID:juanurquijo,项目名称:SF,代码行数:27,代码来源:mailer.py


示例14: send

    def send(self, msg):
        if len(msg['text']) > 32:
            teaser = msg['text'][:32] + '...'
        else:
            teaser = msg['text']
        msg = '''From: %s
To: %s
Subject: %s

%s''' % (self.config['mail']['from_address'], self.config['mail']['to_address'], '[foobox] %s: %s' % (msg['src'], teaser), msg['text'])

        host = self.config['mail']['smtp_server']
        if host.rfind(':') != -1:
            host, port = host.rsplit(':', 1)
        else:
            port = 25
        port = int(port)
        logging.debug('Sending mail via %s:%s' % (host, port))

        try:
            server = SMTP(host, port)
            server.sendmail(self.config['mail']['from_address'], self.config['mail']['to_address'], msg)
            server.quit()
            logging.info('Sent email to %s' % self.config['mail']['to_address'])
        except:
            logging.error('Error sending mail: %s' % format_exc())
开发者ID:JeremyGrosser,项目名称:foobox,代码行数:26,代码来源:mail.py


示例15: response

    def response(self, nick, args, kwargs):
        try:
            sendto, reason = args
            email = self.learn.lookup(u'email', sendto)
            if email is None:
                return u"%s: I don't know the email for %s" % (nick, sendto)

            # just make all this shit ASCII, email is best that way...
            email = email.encode('ascii', 'replace')
            if reason:
                reason = reason.encode('ascii', 'replace')
            anick = nick.encode('ascii', 'replace')

            body = 'To: %s <%s>\n' % (sendto.encode('ascii', 'replace'), email)
            body += 'From: %s\n' % (self.config.smtp.sender)
            body += 'Subject: Summon from %s' % anick
            body += '\n'
            body += 'You were summoned by %s. Reason: %s' % (anick, reason)

            smtp = SMTP(self.config.smtp.server)
            if len(self.config.smtp.user):
                smtp.login(self.config.smtp.user, self.config.smtp.password)
            smtp.sendmail(self.config.smtp.sender, [email], body)

            return u"%s: summoned %s" % (nick, sendto)

        except Exception, error:
            log.warn(u'error in module %s' % self.__module__)
            log.exception(error)
            return u"%s: I couldn't make that summon: %s" % (nick, error)
开发者ID:compbrain,项目名称:madcow,代码行数:30,代码来源:summon.py


示例16: sendmail

    def sendmail(self, to, subject, content):
        '''Shortcut method to send a simple mail.

        Args
        ----
        - to      : A list of addresses to send this mail to. A bare string will
                    be treated as a list with 1 address.
        - subject : Mail subject
        - content : Mail body. treated as pure text

        Example
        -------
        >>> from pyrcp.gsmtplib import GSMTP
        >>> s = GSMTP('your_google_account', 'your_google_password')
        >>> s.sendmail('[email protected]',
        ...            'Hello world!',
        ...            'This is a message sent by gsmtplib'))
        >>> s.quit()

        '''
        mail = MIMEText(content)
        mail['subject'] = subject
        mail['from'] = self.account
        mail['to'] = to

        SMTP.sendmail(self, self.account, to, mail.as_string())
开发者ID:snow,项目名称:pyrcp,代码行数:26,代码来源:gsmtplib.py


示例17: send

    def send(self, message, recipients=None):
        """Send an email.

        The email is sent to `recipient', which must be a list of
        RFC2822 compliant mailboxes and groups.

        If recipients is not specified, it is extracted from the
        'To', 'Cc' and 'Bcc' headers of the message.

        The return value is a list of failed email addresses. If
        not a single email could be sent, an exception is raised.
        """
        if not isinstance(message, Message):
            raise TypeError, 'Expecting "Message" instance.'
        if recipients is None:
            recipients = message.recipients()
            recipients += message.cc_recipients()
            recipients += message.bcc_recipients()
        message.del_header('Bcc')
        smtp = SMTP()
        try:
            smtp.connect(self.m_smtp_server, self.m_smtp_port)
            ret = smtp.sendmail(self.m_sender, recipients, message.dump())
        except SMTPException, err:
            m = 'Could not send email: %s' % str(err)
            raise SendmailError, m
开发者ID:geertj,项目名称:draco2,代码行数:26,代码来源:sendmail.py


示例18: send_email

 def send_email(self, user, receiver, public_text, email, message):
     try:
         if (Config.get("smtp", "port") == "0"):
             smtp = SMTP("localhost")
         else:
             smtp = SMTP(Config.get("smtp", "host"), Config.get("smtp", "port"))
         
         if not ((Config.get("smtp", "host") == "localhost") or (Config.get("smtp", "host") == "127.0.0.1")): 
             try:
                 smtp.starttls()
             except SMTPException as e:
                 raise SMSError("unable to shift connection into TLS: %s" % (str(e),))
             
             try:
                 smtp.login(Config.get("smtp", "user"), Config.get("smtp", "pass"))
             except SMTPException as e:
                 raise SMSError("unable to authenticate: %s" % (str(e),))
         
         try:
              smtp.sendmail(Config.get("smtp", "frommail"), email, 
                           "To:%s\nFrom:%s\nSubject:%s\n\n%s\n" % (email,
                                                                 Config.get("smtp", "frommail"),
                                                                 Config.get("Alliance", "name"),
                                                                 message,))
         except SMTPSenderRefused as e:
             raise SMSError("sender refused: %s" % (str(e),))
         except SMTPRecipientsRefused as e:
             raise SMSError("unable to send: %s" % (str(e),))
         
         smtp.quit()
         self.log_message(user, receiver, email, public_text, "email")
         
     except (socket.error, SSLError, SMTPException, SMSError) as e:
         return "Error sending message: %s" % (str(e),)
开发者ID:davesherratt,项目名称:merlin,代码行数:34,代码来源:sms.py


示例19: send_email

def send_email(from_, to, cc, subject, content):
    """
    @param from_ (str)
    @param to (list - str)
    @param cc (list - str)
    @param content (str)
    """
    msg = MIMEText(content, _charset='utf-8')
    msg['Subject'] = subject
    msg['From'] = from_
    assert type(to) is list
    assert type(cc) is list
    msg['To'] = ",".join(to)
    msg['Cc'] = ",".join(cc)

    email_is_sent = False
    try:
        email_server = SMTP('smtp')
        try:
            email_server.sendmail(from_, to + cc, msg.as_string())
            email_is_sent = True
        except:
            logging.error("*** Failed to send the email")
        email_server.quit()
    except:
        logging.error("*** Can't connect to the SMTP server")

    return email_is_sent
开发者ID:pombredanne,项目名称:serveronduty,代码行数:28,代码来源:sendemail.py


示例20: mailtest

def mailtest():
	from smtplib import SMTP
	from poplib import POP3
	from time import sleep

	smtpsvr = 'xxxxx'
	pop3svr = 'xxxxx'

	user = '[email protected]'
	body = '''\
	From: %(who)s
	To: %(who)s
	Subject: TEST msg
	HELLO World!
	''' % ('who':user)

	sendsvr = SMTP(smtpsvr)
	errs = sendsvr.sendmail(user,[user],origMsg)
	sendsvr.quit()

	assert len(errs) == 0,errs
	sleep(10)

	recvsvr = POP3(pop3svr)
	recvsvr.user('xxx')
	recvsvr.pass_('xxxx')
	rsp,msg,siz = recvsvr.retr(recvsvr.stat()[0]) #登录成功后通过stat()方法得到可用消息列表,通过[0]获取第一条消息

	sep = msg.index('')
	recvbody = msg[sep+1:]

	assert origbody == recvbody

#IMAP4 互联网邮件访问协议,该模块定义了三个类 IMAP4 IMAP4_SSL IMAP4_stream
	"""
开发者ID:weady,项目名称:shell,代码行数:35,代码来源:python.pop3.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python smtplib.SMTP_SSL类代码示例发布时间:2022-05-27
下一篇:
Python smtplib.quoteaddr函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap