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


Python SMTP_SSL.connect方法代码示例

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


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

示例1: sendmail

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import connect [as 别名]
def sendmail(to_addrs, subject, text):

    server = config.get('smtp_server')
    use_tls = asbool(config.get('smtp_use_tls'))
    username = config.get('smtp_username')
    password = config.get('smtp_password')
    from_addr = config.get('admin_email_from')

    log.debug('Sending mail via %s' % server)

    if use_tls:
        s = SMTP_SSL()
    else:
        s = SMTP()
    s.connect(server)
    if username:
        s.login(username, password)
    msg = MIMEText(text, _charset='utf-8')
    msg['From'] = from_addr
    msg['Reply-To'] = from_addr
    if isinstance(to_addrs, basestring):
        msg['To'] = to_addrs
    else:
        msg['To'] = ', '.join(to_addrs)
    msg['Subject'] = subject
    s.sendmail(from_addr, to_addrs, msg.as_string())
    s.quit()
开发者ID:samsemilia7,项目名称:SAUCE,代码行数:29,代码来源:mail.py

示例2: sendMail

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import connect [as 别名]
def sendMail(emailTo, subject, msgText, fileAddr):
	filepath = fileAddr
	basename = os.path.basename(filepath)
	address = "[email protected]"

	# Compose attachment
	part = MIMEBase('application', "octet-stream")
	part.set_payload(open(filepath,"rb").read() )
	Encoders.encode_base64(part)
	part.add_header('Content-Disposition', 'attachment; filename="%s"' % basename)
	part3 = MIMEBase('application', "octet-stream")
	part3.set_payload(open(os.getcwd() + '/plan_rabot_po_saitu_na_god.xlsx',"rb").read() )
	Encoders.encode_base64(part3)
	part3.add_header('Content-Disposition', 'attachment; filename="plan_rabot_po_saitu_na_god.xlsx"')
	part2 = MIMEText(msgText, 'plain')

	# Compose message
	msg = MIMEMultipart()
	msg['From'] = 'Михаил Юрьевич Бубновский <[email protected]>'
	msg['To'] = emailTo
	msg['Subject'] = subject

	msg.attach(part2)
	msg.attach(part)
	msg.attach(part3)

	# Send mail
	smtp = SMTP_SSL()
	smtp.connect('smtp.yandex.ru')
	smtp.login(address, 'biksileev')
	smtp.sendmail(address, emailTo, msg.as_string())
	smtp.quit()
开发者ID:jz36,项目名称:megaindex-audit,代码行数:34,代码来源:tryUI.py

示例3: send_email

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

示例4: landing_customer_contacts

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import connect [as 别名]
def landing_customer_contacts(customer_email, customer_phone, customer_session):
    """
    Функция отправки контактных данных полученных с лендинга.

    :return:
    """

    msg = email.MIMEMultipart.MIMEMultipart()
    from_addr = "[email protected]"
    to_addr = "[email protected], [email protected]"

    msg['From'] = from_addr
    msg['To'] = to_addr
    text = "\tE-mail: %s \n\tТелефон: %s \n" % (customer_email, customer_phone)
    text += "\tДата и время: %s \n" % datetime.datetime.now()
    text += "Параметры сессии: \n "
    for a,b in customer_session.items():
        text += "\t%s : %s \n" % (a, b)

    msg['Subject'] = Header("Контакты с лендинга Conversation parser", "utf8")
    body = "Оставлены контакты. \n" + text
    msg.preamble = "This is a multi-part message in MIME format."
    msg.epilogue = "End of message"

    msg.attach(email.MIMEText.MIMEText(body, "plain", "UTF-8"))

    smtp = SMTP_SSL()
    smtp.connect(smtp_server)
    smtp.login(from_addr, "Cthutq123")
    text = msg.as_string()
    smtp.sendmail(from_addr, to_addr.split(","), text)
    smtp.quit()
开发者ID:jitterxx,项目名称:comparser,代码行数:34,代码来源:objects.py

示例5: sent

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import connect [as 别名]
def sent(filepath):
    from smtplib import SMTP_SSL
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    from email import Encoders
    import os
    
    #filepath = "/path/to/file"
    basename = os.path.basename(filepath)
    address = 'adr'
    address_to = "[email protected]"
    
    # Compose attachment
    part = MIMEBase('application', "octet-stream")
    part.set_payload(open(filepath,"rb").read() )
    Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % basename)
    
    # Compose message
    msg = MIMEMultipart()
    msg['From'] = address
    msg['To'] = address_to
    msg.attach(part)
    
    # Send mail
    smtp = SMTP_SSL()
    smtp.connect('smtp.yandex.ru')
    smtp.login(address, 'password')
    smtp.sendmail(address, address_to, msg.as_string())
    smtp.quit()
开发者ID:iiilia,项目名称:medinf,代码行数:32,代码来源:save_file.py

示例6: connect_to_server

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import connect [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
开发者ID:ormsbee,项目名称:marrow.mailer,代码行数:28,代码来源:smtp.py

示例7: notify

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import connect [as 别名]
    def notify(self):
        
        message = "From:%s\r\n\r\nTo:\r\n\r\nIteration:%d\n\nOutput:\n\n%s" % (self.sender, self.iteration, self.crash)
	session = SMTP_SSL()
	session.connect(smtpserver, smtppport)
        session.sendmail(sender, recipients, message)
        session.quit()
        
        return
开发者ID:ksmaheshkumar,项目名称:PyFuzz,代码行数:11,代码来源:exec.py

示例8: send_email

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import connect [as 别名]
def send_email(to_addr, subject, message):
    # Формируем сообщение
    msg = "From: {}\nTo: {}\nSubject: {}\n\n{}".format(
        settings.FROM_EMAIL, to_addr,subject, message)

    # Отправляем сообщение
    smtp = SMTP_SSL()
    smtp.connect(settings.SMTP)
    smtp.login(settings.FROM_EMAIL_LOGIN, settings.FROM_EMAIL_PASSWORD)
    smtp.sendmail(settings.FROM_EMAIL, to_addr, msg)
    smtp.quit()
开发者ID:AJleksei,项目名称:LigthIt_TZ,代码行数:13,代码来源:views.py

示例9: send_email

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import connect [as 别名]
def send_email(category, orig_msg, msg_uuid):
    """
    Отправка оповещений на адрес отправителя с результатами классификации.

    :return:
    """

    msg = email.MIMEMultipart.MIMEMultipart()
    from_addr = "[email protected]"
    to_addr = orig_msg.sender

    orig_text = "\n\n---------------- Исходное сообщение -------------------\n"
    orig_text += "От кого: %s (%s)\n" % (orig_msg.sender_name, orig_msg.sender)
    orig_text += "Кому: %s (%s) \n" % (orig_msg.recipients_name, orig_msg.recipients)
    orig_text += "Тема: %s" % orig_msg.message_title
    orig_text += "%s" % orig_msg.message_text
    orig_text += "\n------------------------------------------------------\n"

    text = "Результат: \n"
    cat, val = category[0]
    if val != 0:
        text += "\t %s - %.2f%% \n" % (CATEGORY[cat].category, val*100)
    else:
        text += "\t Затрудняюсь определить. \n"

    links_block = """\n
    Независимо от результата, укажите пожалуйста правильный вариант.
    Для этого перейдите по одной из ссылок: \n
        %s - %s
        %s - %s
    \n
    Ваш ответ будет использован для повышения точности анализа.
    \n
    Спасибо за участие,
    команда Conversation Parser.
    \n""" % (CATEGORY["edible"].category, main_link + "%s/%s" % (msg_uuid, CATEGORY["edible"].code),
             CATEGORY["inedible"].category, main_link + "%s/%s" % (msg_uuid, CATEGORY["inedible"].code))

    msg['From'] = from_addr
    msg['To'] = to_addr
    msg['Subject'] = Header("Сообщение от Conversation parser", "utf8")
    body = "Отправленное вами описание было проанализовано. \n" + text + links_block + orig_text
    msg.preamble = "This is a multi-part message in MIME format."
    msg.epilogue = "End of message"

    msg.attach(email.MIMEText.MIMEText(body, "plain", "UTF-8"))

    smtp = SMTP_SSL()
    smtp.connect(smtp_server)
    smtp.login(from_addr, smtp_pass)
    text = msg.as_string()
    smtp.sendmail(from_addr, to_addr, text)
    smtp.quit()
开发者ID:jitterxx,项目名称:comparser,代码行数:55,代码来源:notificater.py

示例10: send_alarm_email

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import connect [as 别名]
def send_alarm_email(alarms):
    """Assemble and build a email for given alarm data."""
    email_host = config.get_email_host()
    email_port = config.get_email_port()
    email_username = config.get_email_username()
    email_password = config.get_email_password()
    email_sender = config.get_email_sender()
    email_receivers = config.get_email_receivers()

    # This example is of an email with text and html alternatives.
    multipart = MIMEMultipart('alternative')

    # We need to use Header objects here instead of just assigning the strings
    # in order to get our headers properly encoded (with QP).
    # You may want to avoid this if your headers are already ASCII, just so
    # people can read the raw message without getting a headache.
    # multipart['To'] = Header(email_receivers.encode('utf-8'), 'UTF-8').encode()
    commaspace = ', '
    multipart['To'] = Header(commaspace.join(email_receivers), 'UTF-8').encode()
    multipart['From'] = Header(email_sender.encode('utf-8'), 'UTF-8').encode()

    alarms_count = alarms.count_come()
    email_subject_prefix = config.get_email_subject_prefix()
    email_subject = email_subject_prefix
    email_subject += u" %s new alarms" % alarms_count
    multipart['Subject'] = Header(email_subject.encode('utf-8'), 'UTF-8').encode()
    # email_text = email_header_template.format(email_sender=email_sender,
    #                                           email_receivers=email_receivers,
    #                                           email_subject=email_subject)
    html_part = make_email_body(alarms)
    html_part = MIMEText(html_part.encode('utf-8'), 'html', 'UTF-8')
    multipart.attach(html_part)

    text_part = unicode(alarms)
    text_part = MIMEText(text_part.encode('utf-8'), 'plain', 'UTF-8')
    multipart.attach(text_part)
    # email_text = MIMEText(email_text.encode('utf-8'), 'html','utf-8')
    io = StringIO()
    g = Generator(io, False)
    g.flatten(multipart)
    email_text = io.getvalue()

    try:
        smtp_obj = SMTP()
        smtp_obj.connect(email_host, email_port)
        smtp_obj.login(email_username, email_password)
        smtp_obj.sendmail(email_sender, email_receivers, email_text)
        smtp_obj.quit()
        logging.info("Successfully sent email")
    except SMTPException:
        logging.warning("Unable to send email!")
开发者ID:idefux,项目名称:wincc_alarmer,代码行数:53,代码来源:mailer.py

示例11: email

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import connect [as 别名]
def email(recipient, message):
    #setup from and to addr
    from_addr = '[email protected]'
    to_addr = recipient

    #setup connection
    s = SMTP_SSL()
    s.connect('smtp.webfaction.com',465)
    s.login(mailbox,pwd)

    #setup message
    msg = 'Subject: %s\n\n%s' % ('Flight update from FlyteShare', message)
    try:
        s.sendmail(from_addr,to_addr,msg)
    except:
        print "Didn't work"
    return
开发者ID:akshairajendran,项目名称:FlightTest,代码行数:19,代码来源:flight_dispatch.py

示例12: _sendEmail

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import connect [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()
开发者ID:crustymonkey,项目名称:cron-wrap,代码行数:22,代码来源:cwrap.py

示例13: send_release_email

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import connect [as 别名]
def send_release_email(version, url, blender_version='2.6', additional_text=''):
	content="""\
Hi,

Blendigo-2.5 version %(VER)s has been packaged and uploaded to:
%(URL)s

This exporter requires Blender version %(BL_VER)s

%(AT)s

Regards,
The Blendigo Release Robot
""" % {'VER':version, 'URL':url, 'BL_VER':blender_version, 'AT':additional_text}

	try:
		msg = MIMEText(content, 'plain')
		msg['Subject'] = "Blendigo-2.5 v%s Release Notification" % version
		msg['From'] = sender # some SMTP servers will do this automatically, not all
		
		conn = SMTP()
		conn.set_debuglevel(False)
		conn.connect(SMTPserver, 465)
		conn.ehlo()
		conn.login(USERNAME, PASSWORD)
		
		try:
			conn.sendmail(
				sender,
				[
					'[email protected]',
					'[email protected]'
				],
				msg.as_string()
			)
		finally:
			conn.close()
	
	except Exception as exc:
		sys.exit( "mail failed; %s" % str(exc) ) # give a error message
		raise exc
开发者ID:Zurkdahool,项目名称:blendigo,代码行数:43,代码来源:send_release_email.py

示例14: send_mail

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import connect [as 别名]
    def send_mail(self, content):
        from smtplib import SMTP_SSL as SMTP
        from email.mime.text import MIMEText

        me = "QQSpider<{_user}@{_postfix}>".format(_user=self.mail_info['mail_user'],
                                                   _postfix=self.mail_info['mail_postfix'])
        msg = MIMEText("<h5>QQSpider Error: Number is {0}</h5><br /><span>by jackliu</span>".format(content),
                       _subtype='html', _charset='utf8')
        msg['Subject'] = "QQSpider Warning"
        msg['From'] = me
        msg['To'] = ";".join(self.mail_info['mail_to_list'].split(','))
        try:
            smtp = SMTP()
            smtp.connect(self.mail_info['mail_host'], self.mail_info['mail_port'])
            smtp.login("{0}@{1}".format(self.mail_info['mail_user'],
                       self.mail_info['mail_postfix']), self.mail_info['mail_pass'])

            smtp.sendmail(me, self.mail_info['mail_to_list'].split(','), msg.as_string())
            smtp.close()
        except Exception as e:
            print(e)
            exit(128)
开发者ID:itchenyi,项目名称:QQSpider,代码行数:24,代码来源:qq.py

示例15: send_message_smtp

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import connect [as 别名]
def send_message_smtp(account, to_field, msg):
    """
    Функция отправки сообщения.

    :param account: содежит объект класса Account для отправки письма
    :param to_field: адреса на которые будет произведена отправка сообщения
    :param msg: сформированное сообщение. Объект класса email.MIMEMultipart.MIMEMultipart

    :return: статус отправки
    """

    server = "smtp." + re.split('\.',account.server,1)[1]

    # Send mail
    try:
        smtp = SMTP_SSL()
        smtp.connect(server)
        smtp.login(account.login, account.password)
        smtp.sendmail(account.login, to_field, msg.as_string())
        smtp.quit()
    except Exception as e:
        return [False,str(e)]
    else:
        return [True,"OK"]
开发者ID:jitterxx,项目名称:rework,代码行数:26,代码来源:prototype1_email_module.py


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