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


Python SMTP_SSL.sendmail方法代码示例

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


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

示例1: mail_send

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import sendmail [as 别名]
  def mail_send(self, subject, emailaddr, key, msg):
    if self._limit:
      self._clean_array()
      epoch = time.time()
      if not key in self._array:
        self._array[key] = epoch
      else:
        ts = self._array.get(key)
        if epoch - ts < self._timeout:
          return self.RET_NOTAUTH
        else:
          self._array[key] = epoch

    if self.DEBUG:
      self._debug('new mail:')
      self._debug('subject: %s' % (subject))
      self._debug('addr: %s' % (emailaddr))
      self._debug('key: %s' % (key))
      self._debug('msg: %s' % (msg))

    try:
      mailserver = SMTP(self._addr)
      mailserver.set_debuglevel(self._mail_debug)
      mailserver.login(self._username, self._password)
      date = datetime.datetime.now().strftime('%a, %d %b %Y %H:%M:%S %z')
      msg = self.MAIL_MSG % (self._srcmail, emailaddr, subject, date, msg)
      mailserver.sendmail(self._srcmail, emailaddr, msg)
      mailserver.quit()
    except Exception as msg:
      self._error(str(msg))
      return self.RET_ERR
    return self.RET_SUCCESS
开发者ID:Rolinh,项目名称:pyircbot,代码行数:34,代码来源:libmail.py

示例2: send_email

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import sendmail [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,代码来源:

示例3: sendEmail

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import sendmail [as 别名]
def sendEmail(text, email_class, identity_dict, email_dict, state, solved_pq = False):
	retries, count = 3, 0
	while count < retries:
		try:
			message = composeMessage(text, email_class, identity_dict, email_dict, state, solved_pq)
			own_addr = identity_dict['Email']
			own_name = ' '.join([identity_dict['First_name'], identity_dict['Last_name']])
			destination_addr = email_dict['Reply-To']
			text_subtype = 'plain'
			mime_msg = MIMEText(message, text_subtype)
			mime_msg['Subject'] = composeSubject(email_dict)
			mime_msg['From'] = own_name + '<' + own_addr + '>'
			if destination_addr in getIdentityEmails():
				break
			mime_msg['To'] = destination_addr
			server_addr = identity_dict['SMTP']
			conn = SMTP_SSL(server_addr)
			conn.set_debuglevel(False)
			conn.login(identity_dict['Username'], identity_dict['Password'])
			try:
				conn.sendmail(own_addr, destination_addr, mime_msg.as_string())
			finally:
				print "Send email!"
				conn.close()
				syncGuardian(mime_msg, identity_dict)
		except Exception:
			count += 1
			continue
		pq_status, pq_result = hasPQ(text), None
		if pq_status:
			pq_result = hasPQ(text).values()[0]
		return {'Date': time.ctime(), 'Sender': own_addr, 'Receiver': destination_addr, 'Subject': composeSubject(email_dict), 'Body': message, 'First_name': identity_dict['First_name'], 'Last_name': identity_dict['Last_name'], 'Origin': 'SYSTEM', 'PQ': pq_result}
	return None
开发者ID:419eaterbot,项目名称:bot,代码行数:35,代码来源:responder.py

示例4: emailFile

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import sendmail [as 别名]
def emailFile( textfile, subject):
	if not config.SEND_EMAIL:
		return
		
	try:
		fp 			= open(textfile, 'rb')
		msg 		= MIMEText(fp.read())
		fp.close()
		
		me			= os.environ['FASTMAIL_USER']
		password 	= os.environ['FASTMAIL_PASSWORD']
		smtp		= os.environ['FASTMAIL_SMTP']
		
		msg['Subject'] 	= subject
		msg['From'] 	= me
		msg['To'] 		= me
		if verbose:
			print "sending email to ", me
		# Send the message via our own SMTP server, but don't include the envelope header.
		s = SMTP(smtp)
		s.login(me, password)
		s.sendmail(me, [me], msg.as_string())
		s.quit()
	except Exception as e:
		print "exception sending email exception", e
开发者ID:joseamidesfigueroa,项目名称:ojo-bot,代码行数:27,代码来源:process_all.py

示例5: sendmail

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import sendmail [as 别名]
def sendmail(to, app, attach0=False, attach1=False):

    from smtplib import SMTP_SSL as SMTP
    from email.MIMEText import MIMEText

    destination = [to]

    # read attach
    contentattach = ''
    if attach0 and not os.stat("%s" % attach0).st_size == 0: 
        fp = open(attach0,'rb')
        contentattach += '------------------ Error begin\n\n'
        contentattach += fp.read()
        contentattach += '\n------------------ Error end'
        fp.close()

    if attach1 and not os.stat("%s" % attach1).st_size == 0: 
        fp = open(attach1,'rb')
        contentattach += '\n\n------------------ Success begin\n\n'
        contentattach += fp.read()
        contentattach += '\n------------------ Success end'
        fp.close()

    msg = MIMEText(contentattach, 'plain')
    msg['Subject'] = "Mr.Script %s" % app
    msg['From'] = sender
                    
    try:
        conn = SMTP(smtpserver)
        conn.set_debuglevel(False)
        conn.login(username, password)
        conn.sendmail(sender, destination, msg.as_string())
        conn.close()
    except:
        print '    *** Error trying send a mail. Check settings.'
开发者ID:teagom,项目名称:mr-robot,代码行数:37,代码来源:external.py

示例6: landing_customer_contacts

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import sendmail [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

示例7: send_email

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import sendmail [as 别名]
def send_email(to_email, from_email, password, subject, content, smtp_address, smtp_port):
    msg = MIMEMultipart()
    msg['From'] = 'OmniPy'
    msg['To'] = to_email
    msg['Subject'] = subject
    msg.attach(MIMEText(content))

    server_connected = False
    try:
        smtp_server = SMTP(smtp_address, smtp_port)
        smtp_server.login(from_email, password)
        server_connected = True
    except SMTPHeloError as e:
        print("Server did not reply")
    except SMTPAuthenticationError as e:
        print("Incorrect username/password combination. \nIf you are using Gmail, you need to use an app password: "
              "https://myaccount.google.com/apppasswords")
    except SMTPException as e:
        print("Authentication failed")

    if server_connected:
        try:
            smtp_server.sendmail(from_email, to_email, msg.as_string())
            print("Successfully sent email")
        except SMTPException as e:
            print("Error: unable to send email", e)
        finally:
            smtp_server.close()
开发者ID:oskogstad,项目名称:OmniPy,代码行数:30,代码来源:email_client.py

示例8: send_mail

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import sendmail [as 别名]
def send_mail(receivers, subject, content, attachment=None, filename=None):
    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = config.FROM_EMAIL
    msg['To'] = receivers

    if config.DEV_ENV:
        msg['To'] = config.TEST_TO_EMAIL

    msg.preamble = 'Multipart message.\n'

    part = MIMEText(content)
    msg.attach(part)

    if attachment:
        part = MIMEApplication(open(attachment, "rb").read())
        part.add_header('Content-Disposition', 'attachment', filename=filename)
        msg.attach(part)

    mailer = SMTP_SSL(config.SMTP_SERVER, config.SMTP_PORT)
    # mailer.ehlo()
    # mailer.starttls()
    mailer.login(config.USERNAME, config.PASSWORD)
    mailer.set_debuglevel(1)
    mailer.sendmail(msg['From'], msg['To'].split(', '), msg.as_string())
    mailer.close()
开发者ID:ankitjain87,项目名称:anyclean,代码行数:28,代码来源:util.py

示例9: render_POST

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import sendmail [as 别名]
    def render_POST(self, request):
        message = ast.literal_eval(request.content.read())
        if message['subject']=='QUESTION':
            txt='\r\n'+'NAME: '+message['name']+'\r\n'+'\r\n'+'EMAIL: '+message['email']+'\r\n'+'\r\n'+'QUESTION: '+message['question']+'\r\n'  
        elif message['subject']=='ORDER':
            txt='\r\n'+'NAME: '+message['name']+'\r\n'+'\r\n'+'EMAIL: '+message['email']+'\r\n'+'\r\n'+ \
			     'ENTIRE LANGUAGE: '+message['entire_language']+'\r\n'+'CAPTION LANGUAGE: '+message['caption_language']+ \
				 '\r\n'+'VIDEO DURATION: '+message['duration']+'\r\n'+'TIME LIMIT: '+message['time_limit']+ \
				 '\r\n'+'VOICE OVER: '+message['voice_over']+'\r\n'+'DISCOUNT: '+message['discount']+'\r\n'+ \
				 'VIDEO LINK:'+message['videolink']+'\r\n'+'SPECIAL: '+message['special']
        elif message['subject']=='CUSTOM ORDER':
            txt='\r\n'+'NAME: '+message['name']+'\r\n'+'\r\n'+'EMAIL: '+message['email']+'\r\n'+'\r\n'+'COMPANY: '+ \
			     message['company']+'\r\n'+'REQUIREMENTS: '+message['requirements']
        elif message['subject']=='FREE MINUTE':
            txt='\r\n'+'EMAIL: '+message['email']+'\r\n'
		
        msg=MIMEText(txt)
        msg['Subject']=message['subject']
        msg['From']=message['email']
        msg['To']=self.addr		
        
        request.setHeader("Access-Control-Allow-Origin", "*")
        smtp = SMTP_SSL(self.hst)
        smtp.login(self.addr,self.psswd)
        smtp.sendmail(self.addr,self.addr,msg.as_string())
        return 'Your mail sent.' 
开发者ID:girinvader,项目名称:SubtitleMe,代码行数:28,代码来源:yandex_smtp.py

示例10: sendmail

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import sendmail [as 别名]
def sendmail(to_mails, message):
    # Update settings
    apply_db_settings(flask_app.flask_app)

    mail = 'From: {}\nTo: {}\nSubject: {}\n\n{}'.format(
        flask_app.flask_app.config.get('EMAIL_EMAIL_FROM'),
        to_mails,
        flask_app.flask_app.config.get('EMAIL_SUBJECT'),
        message
    ).encode(encoding='utf-8')

    server_str = '{}:{}'.format(flask_app.flask_app.config.get('EMAIL_HOST', '127.0.0.1'),
                                flask_app.flask_app.config.get('EMAIL_PORT', 25))
    server = SMTP_SSL(server_str) if flask_app.flask_app.config.get('EMAIL_ENCRYPTION', 0) == 2 \
        else SMTP(server_str)

    if flask_app.flask_app.config.get('EMAIL_ENCRYPTION', 0) == 1:
        server.starttls()

    if flask_app.flask_app.config.get('EMAIL_AUTH', 0):
        server.login(flask_app.flask_app.config.get('EMAIL_LOGIN'),
                     flask_app.flask_app.config.get('EMAIL_PASSWORD'))
    server.sendmail(flask_app.flask_app.config.get('EMAIL_EMAIL_FROM'),
                    to_mails,
                    mail)
    server.quit()
开发者ID:Emercoin,项目名称:emcweb,代码行数:28,代码来源:tasks.py

示例11: sendSMS

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import sendmail [as 别名]
def sendSMS(tresc):
    text_subtype = "plain"  # plain, html, xml
    charset = "utf-8"  # utf-8 dla polskich znakow
    domena = ""
    usePrefix = False
    if config.siec == "plus":
        usePrefix = True
        domena = "@text.plusgsm.pl"
    elif config.siec == "orange":
        domena = "@sms.orange.pl"  # TODO: Tworzenie maila do wyslania smsm, moze cos lepszego niz if/elif?
    else:
        domena = "@text.plusgsm.pl"  # by nie bylo jakis nieporozumien

    try:
        msg = MIMEText(tresc, text_subtype, charset)
        msg["Subject"] = "Info"  # temat wiadomosci
        if usePrefix == True:
            msg["To"] += config.prefix

        msg["To"] += config.numer + domena  # TODO: konfiguracja serwera sms
        msg["From"] = config.emails[config.server][1][0]  # nawet nie dziala ale musi byc

        conn = SMTP_SSL("smtp." + config.emails[config.server][0], config.smtp_port)
        conn.login(config.emails[config.server][1][0], config.emails[config.server][1][1])
        try:
            conn.sendmail(config.emails[config.server][1][0], msg["To"], msg.as_string())
        finally:
            conn.close()
    except Exception, exc:
        ekg.command("gg:msg %s SMS Failed: %s" % (config.admin, str(exc)))  # give a error message
开发者ID:Huczu,项目名称:kerberon-pymailergg,代码行数:32,代码来源:mailer.py

示例12: send_mail

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import sendmail [as 别名]
def send_mail( message,  smtp_host, smtp_port, user = None, passwd = None,
    security = None ):
    '''
    Sends a message to a smtp server
    '''
    if security == 'SSL':
        if not HAS_SMTP_SSL:
            raise Exception('Sorry. For SMTP_SSL support you need Python >= 2.6')
        s = SMTP_SSL(smtp_host, smtp_port)
    else:
        s = SMTP(smtp_host, smtp_port)
    # s.set_debuglevel(10)
    s.ehlo()

    if security == 'TLS':
        s.starttls()
        s.ehlo()
    if user:
        s.login(user.encode('utf-8'), passwd.encode('utf-8'))

    to_addr_list = []

    if message['To']:
        to_addr_list.append(message['To'])
    if message['Cc']:
        to_addr_list.append(message['Cc'])
    if message['Bcc']:
        to_addr_list.append(message['Bcc'])

    to_addr_list = ','.join(to_addr_list).split(',')

    s.sendmail(message['From'], to_addr_list, message.as_string())
    s.close()
开发者ID:jadolg,项目名称:webpymail,代码行数:35,代码来源:mail_utils.py

示例13: send_reminder_email

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


    to = ['[email protected]', '[email protected]']
    text_subtype = 'plain'

    try:
        msg = MIMEText(content.encode('utf-8'), text_subtype)
        msg.set_charset('utf-8')

        msg['Subject']  = subject
        msg['From']     = smtp_conf['from']
        msg['To']       = ','.join(to)
        msg['Reply-To'] = smtp_conf['reply-to']

        conn = SMTP(smtp_conf['server'], 465)
        conn.set_debuglevel(False)
        conn.login(smtp_conf['user'], smtp_conf['pass'])
        try:
            conn.sendmail(smtp_conf['from'], to, msg.as_string())
        finally:
            conn.close()

    except Exception, exc:
        sys.exit( "mail failed; %s" % str(exc) ) # give a error message
开发者ID:rdalverny,项目名称:teamreport,代码行数:27,代码来源:reminder_email.py

示例14: sm

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import sendmail [as 别名]
    def sm(self, to_addr="", subject="", text="", attachments=""):
        msg = MIMEMultipart()

        if isinstance(to_addr, str):
            to_addr = [to_addr]

        msg["From"] = self.gaccount
        msg["To"] = ", ".join(to_addr)
        msg["Date"] = formatdate(localtime=True)
        msg["Subject"] = subject
        msg.attach(MIMEText(text, "html"))

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

        try:
            conn = SMTP("smtp.gmail.com")
            conn.login(self.gaccount, self.gpass)
            conn.sendmail(self.gaccount, to_addr, msg.as_string())
        except Exception as exc:
            sys.exit("Mail failed: {}".format(exc))
        finally:
            conn.close()
开发者ID:kindlychung,项目名称:pygmail,代码行数:32,代码来源:Pygmail.py

示例15: run

# 需要导入模块: from smtplib import SMTP_SSL [as 别名]
# 或者: from smtplib.SMTP_SSL import sendmail [as 别名]
    def run(self):

        if self.getSender() and \
           self.getRecipient() and \
           self.getSubject() and \
           self.getContent():

            try:
                message = MIMEText(self.getContent(), self.getTextSubtype())
                message['Subject'] = self.getSubject()
                message['From'] = self.getSender()

                connection = SMTP(self.getSmtpServer(), self.getPort())
                connection.set_debuglevel(False)
                connection.login(self.getUsername(), self.getPasswd())

                try:
                    connection.sendmail(self.getSender(),
                                        self.getRecipient(),
                                        message.as_string())
                finally:
                    connection.close()
            except Exception, e:
                print "Message to {0} failed: {1}".format(
                                                self.getRecipient(), e)
开发者ID:iamjohnnym,项目名称:RemoteSendMail,代码行数:27,代码来源:remotesendmail.py


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