def NewPlayerEmail(to,publicName,password, regkey,fromProduct):

    me = SUPPORTEMAIL_ADDRESS
    
    if not fromProduct:
        body = FREE_BODY%(publicName,password)

    else:
        body = PREMIUM_BODY%(publicName,password)
    
    msg = MIMEText(body)
    
    if fromProduct:
        msg['Subject'] = PREMIUM_SUBJECT
    else:
        msg['Subject'] = FREE_SUBJECT
        
    msg['From'] = me
    msg['To'] = to

    s = smtplib.SMTP(SUPPORTEMAIL_SERVER,SUPPORTEMAIL_PORT)
    #s.set_debuglevel(1)

    if SERVER_EMAIL_USE_GMAIL: 
        s.ehlo() 
        s.starttls() 
        s.ehlo()

    s.login(SUPPORTEMAIL_ACCOUNT,SUPPORTEMAIL_PASSWORD)
    s.sendmail(me, [to], msg.as_string())
    msg['To'] = SUPPORTEMAIL_ADDRESS
    s.sendmail(me, SUPPORTEMAIL_ADDRESS, msg.as_string())
    s.quit()
示例#2
0
    def GenericMail(self, toadd, msgtxt, subj='PySCeS generated email'):
        """
        GenericMail( toadd, msgtxt, subj='PySCeS generated email')

        Generate and send a text (non-mime) email message

        Arguments:
        =========
        toadd: recipient address
        msgtxt: the message body as a string
        subj [default='PySCeS generated email']: message subject line

        """
        assert type(msgtxt) == str, '\nMessage text must be a string'
        assert self.__smtp_active, 'SMTP Server not active\n'

        msgtxt = self.msgintro + msgtxt

        msgtxt += self.signature
        outer = MIMEText(msgtxt)

        outer['Subject'] = subj
        outer['To'] = toadd
        outer['From'] = self.fromhead
        outer['Date'] = email.Utils.formatdate(localtime='true')
        outer.epilogue = ' '

        if self.CheckGo():
            try:
                self.__SMTPserver.sendmail(self.fromhead,toadd,outer.as_string())
            except SMTPServerDisconnected, e:
                print e
                self.SMTPOpen()
                self.__SMTPserver.sendmail(self.fromhead,toadd,outer.as_string())
            sleep(0.2)
示例#3
0
    def send_mail(self, server, email, message, subject, mimetype="plain"):
        # [NODE: 0&44]
        details = server.credential.cred_details
        server_user_name = details["user_email"]
        server_user_psswd = details["password"]
        if server_user_name is None or server_user_name == "":
            server_user_name = tg.config.get("email_from")

        message = MIMEText(message, mimetype)
        message["Subject"] = subject
        if server.use_secure == constants.NONSECURE:
            self.send_nonsecure(server.mail_server, int(server.port), server_user_name, email, message.as_string())
        else:
            if server.use_secure == constants.TLS:
                self.send_tls(
                    server.mail_server,
                    int(server.port),
                    server_user_name,
                    server_user_psswd,
                    email,
                    message.as_string(),
                )
            else:
                self.send_ssl(
                    server.mail_server,
                    int(server.port),
                    server_user_name,
                    server_user_psswd,
                    email,
                    message.as_string(),
                )

        return None
示例#4
0
def sendmail(msg):
    msg = MIMEText(msg)
    msg["From"] = "*****@*****.**"
    msg["To"] = "*****@*****.**"
    msg["Subject"] = "o2 report moniter"
    msg['Date'] = email.Utils.formatdate(localtime=True)
    server = smtplib.SMTP("mail.cloud-88.com")
    server.login('*****@*****.**', 'o2cloud88')
    server.sendmail('*****@*****.**', '*****@*****.**', msg.as_string())
    server.sendmail('*****@*****.**', '*****@*****.**', msg.as_string())
    server.quit()
示例#5
0
def send_email(toaddrs, mail, fromaddr=EMAIL_SENDER_ADDR, subject=EMAIL_SUBJECT, cc=None):
    msg = MIMEText(mail)
    msg['From'] = fromaddr
    msg['To'] = toaddrs
    msg['Subject'] = subject
    #log(toaddrs)
    log(msg.as_string())

    server = smtplib.SMTP('remotesmtp.mot.com')
    server.set_debuglevel(1)
    server.sendmail(fromaddr, toaddrs, msg.as_string())
    server.quit()
def get_my_ips():
    stdin, stdout = os.popen2( 'ifconfig' )
    output = stdout.read()
    pi_hostname = socket.gethostname()
    snagAddrRegex = re.compile( r'inet addr:(?P<addr>\S+?) ' )
    ipaddrs = snagAddrRegex.findall( output )
    if( '127.0.0.1' in ipaddrs ):
        ipaddrs.remove( '127.0.0.1' )  # get rid of the interface we know is always there, it's just noise
    msg = MIMEText("%s has ip(s):\n    %s\n\nOutput of command:\n%s" % (pi_hostname, '\n    '.join( ipaddrs ), output))
    msg["subject"] = "Rasberry Pi: %s has ip(s): %s" % (pi_hostname, ' '.join(ipaddrs))
    msg["to"] = toWhom
    msg["from"] = fromMe
    if debug:
        print msg.as_string()
    return ipaddrs, msg
示例#7
0
    def envioDeCorreoAlerta(self):
        """
            Envia el correo de alerta al usuario especificado
        """
        # Construimos el mensaje simple
        stringDeAviso = "Aviso el servicio en la ip: %s" + \
                    " puerto: %s ha fallado %s"

        mensaje = MIMEText((stringDeAviso % (self.ip,
            self.port, str(datetime.datetime.now()))))
        mensaje['From'] = self.responsable
        mensaje['To'] = self.responsable
        mensaje['Subject'] = "ALERTA !!! Falla en el servicio"
        if(self.envio):
            # Establecemos conexion con el servidor smtp de gmail
            mailServer = smtplib.SMTP('smtp.gmail.com', 587)
            mailServer.ehlo()
            mailServer.starttls()
            mailServer.ehlo()
            # Registro de la cuenta de GMAIL
            mailServer.login("ACA TU CUENTA DE CORREO GMAIL", "TU CLAVE")
            # Envio del mensaje
            mailServer.sendmail(mensaje['From'], mensaje['To'],
                mensaje.as_string())
            # Cierre de la conexion
            mailServer.close()
            print("\t\t ...correo enviado")
示例#8
0
def sendMail(RECIPIENT,SUBJECT,TEXT):
    import sys
    import os
    import re
    from smtplib import SMTP_SSL as SMTP       # this invokes the secure SMTP protocol (port 465, uses SSL)
    # from smtplib import SMTP                  # use this for standard SMTP protocol   (port 25, no encryption)
    from email.MIMEText import MIMEText
    SMTPserver = 'smtp.gmail.com'
    sender =     '*****@*****.**'
    destination = [RECIPIENT]

    USERNAME = "******"
    PASSWORD = "******"

    # typical values for text_subtype are plain, html, xml
    text_subtype = 'plain'

    
    try:
        msg = MIMEText(TEXT, text_subtype)
        msg['Subject']=       SUBJECT
        msg['From']   = sender # some SMTP servers will do this automatically, not all

        conn = SMTP(SMTPserver)
        conn.set_debuglevel(False)
        conn.login(USERNAME, PASSWORD)
        try:
            conn.sendmail(sender, destination, msg.as_string())
        finally:
            conn.close()
    
    except Exception, exc:
        sys.exit( "mail failed; %s" % str(exc) ) # give a error message
示例#9
0
def send_email(sender, recipient, subject, body):
   from smtplib import SMTP
   from email.MIMEText import MIMEText
   from email.Header import Header
   from email.Utils import parseaddr, formataddr
   # Header class is smart enough to try US-ASCII, then the charset we
   # provide, then fall back to UTF-8.
   header_charset = 'ISO-8859-1'
   # We must choose the body charset manually
   for body_charset in 'UTF-8', 'ISO-8859-1', 'US-ASCII'  :
      try:
         body.encode(body_charset)
      except UnicodeError:
         pass
      else:
         break
   # Split real name (which is optional) and email address parts
   sender_name, sender_addr = parseaddr(sender)
   recipient_name, recipient_addr = parseaddr(recipient)
   # We must always pass Unicode strings to Header, otherwise it will
   # use RFC 2047 encoding even on plain ASCII strings.
   sender_name = str(Header(unicode(sender_name), header_charset))
   recipient_name = str(Header(unicode(recipient_name), header_charset))
   # Make sure email addresses do not contain non-ASCII characters
   sender_addr = sender_addr.encode('ascii')
   recipient_addr = recipient_addr.encode('ascii')
   # Create the message ('plain' stands for Content-Type: text/plain)
   msg = MIMEText(body.encode(body_charset), 'plain', body_charset)
   msg['From'] = formataddr((sender_name, sender_addr))
   msg['To'] = formataddr((recipient_name, recipient_addr))
   msg['Subject'] = Header(unicode(subject), header_charset)
   # Send the message via SMTP to localhost:25
   smtp = SMTP("localhost")
   smtp.sendmail(sender, recipient, msg.as_string())
   smtp.quit()
示例#10
0
def sendEmail(to, subject, content):
    retval = 1
    if not(hasattr(to, "__iter__")):
        to = [to]
    destination = to

    text_subtype = 'plain'
    try:
        msg = MIMEText(content, text_subtype)
        msg['Subject'] = subject
        msg['From'] = sender # some SMTP servers will do this automatically, not all

        conn = SMTP(host=smtpHost, port=smtpPort)
        conn.set_debuglevel(True)
        #conn.login(smtpUsername, smtpPassword)
        try:
            if smtpUsername is not False:
                conn.ehlo()
                if smtpPort != 25:
                    conn.starttls()
                    conn.ehlo()
                if smtpUsername and smtpPassword:
                    conn.login(smtpUsername, smtpPassword)
                else:
                    print("::sendEmail > Skipping authentication information because smtpUsername: %s, smtpPassword: %s" % (smtpUsername, smtpPassword))
            conn.sendmail(sender, destination, msg.as_string())
            retval = 0
        except Exception, e:
            print("::sendEmail > Got %s %s. Showing traceback:\n%s" % (type(e), e, traceback.format_exc()))
            retval = 1
        finally:
            conn.close()
示例#11
0
def mail_feedback(search, yes_no, message):
    """ take the info, send it to INSPIRE feedback """
    if yes_no == 'true':
        yes_no = 'yes'
    elif yes_no == 'false':
        yes_no = 'no'
    message = """
    Dear INSPIRE feedback folks,
        A SPIRES user interacted with your box in SPIRES!

        They were trying the search
            %(search)s

        What they said was
            Did INSPIRE give results you expected? %(yes_no)s
            Comments: %(message)s

    """ % { 'search' : search,
            'message' : message,
            'yes_no' : yes_no }

    msg = MIMEText(message)
    msg['Subject'] = 'INSPIRE feedback originating from SPIRES:' + yes_no
    msg['To'] = FEEDBACK
    msg['From'] = CRAZYSPIRESMACHINE

    s = smtplib.SMTP('cernmx.cern.ch')
    s.sendmail(CRAZYSPIRESMACHINE, [FEEDBACK], msg.as_string())
    s.quit()

    return True
示例#12
0
def send_email(str_to_address,\
               int_email_type,\
               dict_information = {}):
    if not _obj_smtp_server:
        _build_smtp_server()
        
    #Create body
    str_body = _list_type_body[int_email_type]
    if dict_information.has_key('dut_id'):
        str_body = str_body.replace('#DUT_ID', dict_information['dut_id'])
    if dict_information.has_key('port_info'):
        str_body = str_body.replace('#PORT_INFO', dict_information['port_info'])
    
    obj_body = MIMEText(str_body,'html')
    obj_body['subject'] = _list_type_subject[int_email_type]
    obj_body['from'] = _str_from_name
    obj_body['to'] = str_to_address
    
    log('INFO', 'Sending email: : subject(%s), to(%s)' % (obj_body['subject'], str_to_address))
    try:
        _obj_smtp_server.sendmail(_str_from_address, \
                              str_to_address,\
                              obj_body.as_string())
    except:
        log('WARNING', 'Failed to send email: subject(%s), to(%s)' % (obj_body['subject'], str_to_address))
        log('ERROR', traceback.format_exc())
        _build_smtp_server()
    else:
        log('INFO', 'email sent:: subject(%s), to(%s)' % (obj_body['subject'], str_to_address))
示例#13
0
    def _send_html(self):

        mhost = component.getUtility(IMailDelivery, 'cc_engine')

        email_addr = self.request.form.get('email', '')
        license_name = self.license.name
        license_html = self.rdfa()

        message_body = u"""

Thank you for using a Creative Commons License for your work.

You have selected %s. You should include a reference to this
license on the web page that includes the work in question.

Here is the suggested HTML:

%s

Further tips for using the supplied HTML and RDF are here:
http://creativecommons.org/learn/technology/usingmarkup

Thank you!
Creative Commons Support
[email protected]
""" % (license_name, license_html)

        message = MIMEText(message_body.encode('utf-8'), 'plain', 'utf-8')
        message['Subject'] = 'Your Creative Commons License Information'
        message['From'] = '*****@*****.**'
        message['To'] = email_addr

        mhost.send('*****@*****.**', (email_addr,),
                   message.as_string())
示例#14
0
文件: alarm.py 项目: 42qu/vps
    def send(self, subject, body):
        try:
            server = smtplib.SMTP(config_email.SMTP, config_email.SMTP_PORT)
            server.ehlo()
            server.esmtp_features['auth'] = 'LOGIN PLAIN'
            if config_email.SMTP != 'localhost':
                server.login(config_email.SMTP_USERNAME,
                             config_email.SMTP_PASSWORD)

            enc = 'utf-8'
            format = 'plain'
            msg = MIMEText(body, format, enc)
            msg['Subject'] = Header(subject, enc)

            #sender_name = str(Header(sender_name, enc))
            #msg['From'] = formataddr((sender_name, sender))
            msg['From'] = config_email.SENDER_MAIL

            #recipient_name = str(Header(recipient_name, enc))
            #msg['To'] = formataddr((recipient_name, recipient))
            recipient = ",".join(self.address_list)
            msg['To'] = recipient

            server.sendmail(config_email.SENDER_MAIL,
                            recipient, msg.as_string())
            self.logger.info("sent %s " % (subject))
        except Exception, e:
            self.logger.exception(e)
            self.logger.error("cannot send %s " % (subject))
示例#15
0
def sendmail(step=None, err_msg=None):
    from_name, to_name = _get_config()

    if step is None:
        step = ''

    if err_msg is None or '[ERROR]' not in err_msg:
        msgstr = 'Daily docs %s completed successfully' % step
        subject = "DOC: %s successful" % step
    else:
        msgstr = err_msg
        subject = "DOC: %s failed" % step

    import smtplib
    from email.MIMEText import MIMEText
    msg = MIMEText(msgstr)
    msg['Subject'] = subject
    msg['From'] = from_name
    msg['To'] = to_name

    server_str, port, login, pwd = _get_credentials()
    server = smtplib.SMTP(server_str, port)
    server.ehlo()
    server.starttls()
    server.ehlo()

    server.login(login, pwd)
    try:
        server.sendmail(from_name, to_name, msg.as_string())
    finally:
        server.close()
示例#16
0
文件: monitor.py 项目: LitpoEric/ltp
def send_server_crash_mail(h):
    # send mail to notify that the service is crash
    current_time = datetime.datetime.now().strftime("%I:%M %p on %B %d, %Y")
    subject = "{time}, LTP on host {host} is crash.".format(
            time = current_time,
            host=h["name"])
    content = mail_content_header
    content += "Report time : {time}\n".format(time = current_time)
    content += "Report host : {host}\n".format(host = h["name"])
    content += "Report content : LTP on {host} is crash.\n".format(
            host = h["name"])
    content += "\n"

    if h["case"] is not None:
        detail = "case : \"{case}\"\n".format(case = h["case"])
    else:
        detali = "case : problem case was not detected.\n"

    if h["msg"] is not None:
        detail = "message : {msg}\n".format(msg = h["msg"])
    else:
        detali = "message : no message is left.\n"

    content += detail
    content += "\n"
    content += mail_content_tail

    msg = MIMEText(content)
    msg['Subject']= subject
    msg['From'] = from_addr

    try:
        conn.sendmail(from_addr, to_addrs, msg.as_string())
    except:
        logging.warning("failed to send mail.")
示例#17
0
文件: util.py 项目: hodduc/arara
def send_mail(subject, mailto, content, subtype='html', charset='euc_kr'):
    '''
    ARA 서버에서 E-Mail을 전송하는 함수

    @type  subject: string
    @param subject: 제목
    @type  mailto: string
    @param mailto: 받는 사람
    @type  content: string
    @param content: 메일 내용
    @type  subtype: string
    @param subtype: Content-Type minor type
    @type  charset: string
    @param charset: Character Set
    '''
    from etc.arara_settings import MAIL_SENDER, MAIL_HOST

    try:
        msg = MIMEText(content, _subtype=subtype, _charset=charset)
        msg['Subject'] = subject
        msg['From'] = MAIL_SENDER
        msg['To'] = mailto

        s = smtplib.SMTP()
        s.connect(MAIL_HOST)
        s.sendmail(MAIL_SENDER, [mailto], msg.as_string())
        s.quit()
    except Exception:
        raise
示例#18
0
 def _send(to, subject, message):
     if MAIL_SERVER == 'logging':
         from gluon.tools import Mail
         mail = Mail()   
         mail.settings.server = MAIL_SERVER
         mail.settings.sender = MAIL_SENDER
         mail.settings.login = MAIL_LOGIN
         return mail.send(to=to, subject=subject, message=message)
     else:
         import smtplib
         from email.MIMEText import MIMEText
         from email.Utils import formatdate
         
         msg = MIMEText(message)
         msg['Subject'] = subject
         msg['From'] = MAIL_SENDER
         msg['To'] = to
         msg['Date'] = formatdate()
         
         s = smtplib.SMTP(MAIL_SERVER)
         try:
             s.sendmail(MAIL_SENDER, [to], msg.as_string())
             return True
         finally:
             s.close()
         return False
    def spider_closed(self, spider):
        if not self.result_check:
            me = '*****@*****.**'
            you = '*****@*****.**'
            text = u'MADELEINE_SPIDER\nНе все данные собираются с сайта (есть пустые поля), см. log.txt на сервере'
            subj = 'MADELEINE_SPIDER'

            # SMTP-сервер
            server = "smtp.gmail.com"
            port = 25
            user_name = "*****@*****.**"
            user_passwd = "madeleine78"

            # формирование сообщения
            msg = MIMEText(text, "", "utf-8")
            msg['Subject'] = subj
            msg['From'] = me
            msg['To'] = you

            # отправка
            s = smtplib.SMTP(server, port)
            s.ehlo()
            s.starttls()
            s.ehlo()
            s.login(user_name, user_passwd)
            s.sendmail(me, you, msg.as_string())
            s.quit()
示例#20
0
文件: receive2.py 项目: ryuiso/indeza
    def send_email(self, from_address, to_addresses, cc_addresses, bcc_addresses, subject, body):
        """
        Send an email

        Args:
            to_addresses: must be a list
            cc_addresses: must be a list
            bcc_addresses: must be a list
        """
        try:
            # Note: need Python 2.6.3 or more
            conn = SMTP_SSL(self.smtp_host, self.smtp_port)
            conn.login(self.user, self.password)
            msg = MIMEText(body, 'plain', self.email_default_encoding)
            msg['Subject'] = Header(subject, self.email_default_encoding)
            msg['From'] = from_address
            msg['To'] = ', '.join(to_addresses)
            if cc_addresses:
                msg['CC'] = ', '.join(cc_addresses)
            if bcc_addresses:
                msg['BCC'] = ', '.join(bcc_addresses)
            msg['Date'] = Utils.formatdate(localtime=True)
            # TODO: Attached file
            conn.sendmail(from_address, to_addresses, msg.as_string())
        except:
            raise
        finally:
            conn.close()
示例#21
0
def PushwithMail(_msglist, _sendto):
    global logger
    import smtplib  
    from email.MIMEText import MIMEText  
    from email.Utils import formatdate  
    from email.Header import Header 
    smtpHost = 'smtp.qq.com'
    fromMail = username = '******'  
    password = '******'
    subject  = u'[%s] 自动推荐'%datetime.today().strftime('%Y/%m/%d')
    body     = '\n'.join(_msglist) 
    mail = MIMEText(body,'plain','utf-8')  
    mail['Subject'] = Header(subject,'utf-8')  
    mail['From'] = fromMail  
    mail['To'] = _sendto
    mail['Date'] = formatdate() 
    try:  
        smtp = smtplib.SMTP_SSL(smtpHost)  
        smtp.ehlo()  
        smtp.login(username,password)
        smtp.sendmail(fromMail,_sendto,mail.as_string())  
        smtp.close()  
        logger.warning('Push to %s successfully.'%_sendto)
    except Exception as e:  
        logger.warning(str(e) + ' when pushing the msg with Mail.')
示例#22
0
    def sendmail(self, toaddrs, mailtype):
        f = open("%s" % self.filename, 'r')
        text = f.readlines()
        f.close()
        message = ''
        if mailtype == 'ERROR':
            error_num = 0
            for line in text:
                if line.find('ERROR') >= 0:
                    message += line
                    error_num += 1
                    wx_message.append(line)

            self.subject = '%s服务异常!%s/%s' % (self.subject_prefix, error_num, len(text))
        else:
            self.subject = '%s服务检查日志: %s' % (self.subject_prefix, len(text))
            for line in text:
                message += line

        msg = MIMEText(message)
        msg['From'] = self.fromaddr
        msg['To'] = ','.join(toaddrs)
        msg['Subject'] = self.subject
        if len(message) != 0:
            try:
                server = smtplib.SMTP(mailhost)
                server.login(mailuser, mailpasswd)
                server.sendmail(self.fromaddr, toaddrs, msg.as_string())
                server.quit()
            except Exception, e:
                logger.error(e)
    def mail(self, html):
        """ Send mail as configured

        :param html is a str containing well-formed html
        """

        server = smtplib.SMTP(self.config['smtp_server'])
        
        msg = MIMEText(html, 'html')

        _s = 'Func Inventory Notifier %s' % datetime.today().isoformat(' ')
        msg['Subject'] =  _s
        _f = "'%s' <%s>" % (self.config['from_name'], self.config['from_email'])
        msg['From'] = _f

        msg['X-Generated-By'] = 'Python'
        msg['Content-Disposition'] = 'inline'

        for to_email in self.config['to_emails']:
            self.log( "Emailing %s" % to_email )
            msg['To'] = to_email
            _msg = msg.as_string()
            server.sendmail( _f, to_email, _msg )

        server.quit()
示例#24
0
def enviaemail(mensagem):
    #Usado os site abaixo como referencia
    #http://www.vivaolinux.com.br/dica/Enviando-email-com-Python-e-autenticacao-no-SMTP-pelo-Linux
    #http://rafapinheiro.wordpress.com/2009/02/22/enviando-e-mail-com-python-pelo-gmail/

    #Cria a mensagem a ser enviada
    msg1 = MIMEText("%s"% mensagem)
    #Titulo da mensagem
    msg1['Subject']='Aqui vai o titulo do e-mail Ex. Conversa no canal #OeSC-Livre'
    #Destino e destinatario    
    msg1['From']="*****@*****.**"
    msg1['To']="*****@*****.**"
    #ativando o ssl
    #O caminho SMTP é do gmail(Mas pode ser alterado para o de sua preferencia)
    smtp = smtplib.SMTP('smtp.gmail.com:587')
    #inicia a troca de dados om o servidor
    smtp.ehlo()
    #ativa o tls
    smtp.starttls()
    #reinicia a troca de dados
    smtp.ehlo()
    #Efetua o login
    smtp.login('*****@*****.**', 'senha')
    #Envia o e-mail
    smtp.sendmail('*****@*****.**','*****@*****.**',msg1.as_string())
    #Fecha a conexao
    smtp.quit()
示例#25
0
def send_email():
    try:
        from_addr = "*****@*****.**"
        passwd = "12034896@"
        to_addr = "*****@*****.**"
        stmp_server = "smtp.qq.com"
        #stmp_server = "mail.52tt.com"
        import smtplib
        server = smtplib.SMTP(stmp_server, 25)
        server.set_debuglevel(1)
        server.starttls()
        server.login(from_addr, passwd)

        from email import encoders
        from email.header import Header
        from email.utils import parseaddr, formataddr
        from email.MIMEText import MIMEText

        def _format_addr(s):
            name, addr = parseaddr(s)
            return formataddr(( \
                    Header(name, 'utf-8').encode(), \
                    addr.encode('utf-8') if isinstance(addr, unicode) else addr))

        msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')
        msg['From'] = _format_addr(u'Python爱好者 <%s>' % from_addr)
        msg['To'] = _format_addr(u'管理员 <%s>' % to_addr)
        msg['Subject'] = Header(u'来自SMTP的问候……', 'utf-8').encode()
        server.sendmail(from_addr, [to_addr], msg.as_string())
        server.quit
        return "success"
    except Exception, e:
        return traceback.format_exc()
示例#26
0
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.'
示例#27
0
文件: mail.py 项目: yangpingyu/tools
def sendEmail(mailUser, mailPass, toList , topic , htmlContent):
	'''
	toList : send to who
	topic  : the mail subject
	htmlContent : the mail content
	'''
	
	if htmlContent == '':
		print "htmlContent is null!!!"
		return False

	msg = MIMEText(htmlContent,"html","utf-8")
	msg["Subject"] = topic
	msg["From"] = sender
	msg["To"] = ";".join(toList.split(","))
	try:
		s = smtplib.SMTP()
		s.connect(mailHost,mailPort)
		s.login(mailUser,mailPass)
		s.sendmail(sender,toList.split(","),msg.as_string())
		s.close
		return True
	except Exception,e:
		print str(e)
		return False
示例#28
0
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
def secureSend(self, message, mto, mfrom, subject='[No Subject]',
               mcc=None, mbcc=None, subtype='plain', charset='us-ascii',
               debug=False, **kwargs):
    """Deprecated method attempting to maintain backwards
    compatibility for code depending on the SecureMailHost API."""
    # Convert all our address list inputs
    mfrom = email_list_to_string(mfrom, charset)
    mto = email_list_to_string(mto, charset)
    mcc = email_list_to_string(mcc, charset)
    mbcc = email_list_to_string(mbcc, charset)

    # Convert to a message for adding headers.  If it's already a
    # message, copy it to be safe.
    if not isinstance(message, Message):
        if isinstance(message, unicode):
            message.encode(charset)
        message = MIMEText(message, subtype, charset)
    else:
        message = deepcopy(message)

    # Add extra headers
    _addHeaders(message, Subject=Header(subject, charset),
                To=mto, Cc=mcc, From=mfrom,
                **dict((k, Header(v, charset)) for k, v in kwargs.iteritems()))

    all_recipients = [formataddr(pair) for pair in
                      getaddresses((mto, mcc, mbcc))]

    # Convert message back to string for sending
    self._send(mfrom, all_recipients, message.as_string(), immediate=True)
示例#30
0
def mail(directory):
    subject="[ CS 260 ][ Grade ][ REVIEW ] - Homework 3 Written"
    i = 0
    for root, dirs, filenames in os.walk(directory):
        for f in filenames:
                content= open(os.path.join(root,f) ).read()
                destination = []
                rex = re.compile("(.*)hw3")
                destination.append(rex.search(f).groups()[0] + "@drexel.edu")
                print "Mailing to Destination " , rex.search(f).groups()[0]
                try:
                    msg = MIMEText(content, text_subtype)
                    msg['Subject']= subject
                    msg['From'] = "TA Nagesh<*****@*****.**>" # some SMTP servers will do this automatically, not all

                    conn = SMTP(SMTPserver)
                    conn.set_debuglevel(False)
                    conn.login(USERNAME, PASSWORD)
                    try:
                        conn.sendmail(sender, destination, msg.as_string())
                    finally:
                        conn.close()

                except Exception, exc:
                    sys.exit( "mail failed; %s" % str(exc) ) # give a error message
示例#31
0
def sendEmail(subject, body):

    dirString = ""

    smtpObject = smtplib.SMTP()
    mailMsg = MIMEText(body)
    mailMsg['From'] = '*****@*****.**'
    mailMsg['To'] = '*****@*****.**'
    mailMsg['Subject'] = subject
    #Send Message
    smtpObject.connect('mail.mvista.com')
    smtpObject.sendmail("*****@*****.**", '*****@*****.**',
                        mailMsg.as_string())
    smtpObject.close()
def send_email(subject, content):

    msg = MIMEText(content, _subtype='plain', _charset='utf-8')
    msg["Subject"] = subject
    msg["From"] = mail_from
    msg["To"] = ','.join(mail_to)

    try:
        server = smtplib.SMTP()
        server.connect(smtpserver)
        server.sendmail(mail_from, mail_to, msg.as_string())
        server.close()
    except Exception, e:
        print str(e)
示例#33
0
def MailAlarm(to_addr, subject_header, content):
    mail_server = 'mx1.qq.com'
    mail_server_port = 25
    from_addr = '*****@*****.**'
    from_header = 'From: %s\r\n' % (from_addr)
    to_header = 'To: %s\r\n\r\n' % (to_addr)
    m = MIMEText(content)
    m["To"] = to_addr
    m["From"] = from_addr
    m["Subject"] = subject_header

    s = smtplib.SMTP(mail_server, mail_server_port)
    s.sendmail(from_addr, to_addr, m.as_string())
    s.quit()
示例#34
0
def SendEmail(fromAdd, toAdd, subject, attachfile, htmlText):
    strFrom = fromAdd
    strTo = toAdd
    msg = MIMEText(htmlText)
    msg['Content-Type'] = 'Text/HTML'
    msg['Subject'] = Header(subject, 'gb2312')
    msg['To'] = strTo
    msg['Ftom'] = strFrom
    smtp = smtplib.SMTP('smtp.163.com')
    smtp.login('*****@*****.**', '123321asdA')
    try:
        smtp.sendmail(strFrom, strTo, msg.as_string())
    finally:
        smtp.close
示例#35
0
def send_email(subject, message, from_addr=GMAIL_LOGIN, to_addr=GMAIL_LOGIN):
    msg = MIMEText(message)
    msg['Subject'] = subject
    msg['From'] = from_addr
    msg['To'] = to_addr
    msg['Reply-To'] = '*****@*****.**'
                    
    server = smtplib.SMTP('smtp.gmail.com',587) #port 465 or 587
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(GMAIL_LOGIN,GMAIL_PASSWORD)
    server.sendmail(from_addr, to_addr, msg.as_string())
    server.close()
示例#36
0
    def run(self):
        try:
            msg = MIMEText(self.MAILBODY, _subtype='html', _charset='utf8')
            msg['Subject'] = Header(self.SUBJECT, 'utf8')
            msg['From'] = self.SENDER
            msg['To'] = self.RECEIVER
            s = smtp(self.SMTP_HOST)
            s.set_debuglevel(0)
            s.login(self.SMTP_USER, self.SMTP_PASSWD)
            s.sendmail(self.SENDER, self.RECEIVER, msg.as_string())

        except:
            print traceback.print_exc()
            return False
示例#37
0
def send_mail(from_addr, to_addr, message_num):
  msg = MIMEText(message[message_num]) 
  msg['Subject'] = "Smartcity: Error Notification"
  msg['From'] = from_addr
  msg['To'] = to_addr
  msg['Date'] = formatdate() 
  
  try:
    s = smtplib.SMTP('localhost') 
    print('connected to mail server') 
    s.sendmail(from_addr, [to_addr], msg.as_string()) 
    s.close() 
  except error:
    print(error) 
    print('Some bad exception occured while before sending') 
    s = smtplib.SMTP_SSL('', 465) 
    s.connect() 
    s.login('', '') 
    print('yes') 
    s.sendmail(from_addr, [to_addr], msg.as_string()) 
    s.close() 
  except:
    print('Some bad exception occured while before sending') 
示例#38
0
    def GenericMail(self, toadd, msgtxt, subj='PySCeS generated email'):
        """
        GenericMail( toadd, msgtxt, subj='PySCeS generated email')

        Generate and send a text (non-mime) email message

        Arguments:
        =========
        toadd: recipient address
        msgtxt: the message body as a string
        subj [default='PySCeS generated email']: message subject line

        """
        assert type(msgtxt) == str, '\nMessage text must be a string'
        assert self.__smtp_active, 'SMTP Server not active\n'

        msgtxt = self.msgintro + msgtxt

        msgtxt += self.signature
        outer = MIMEText(msgtxt)

        outer['Subject'] = subj
        outer['To'] = toadd
        outer['From'] = self.fromhead
        outer['Date'] = email.Utils.formatdate(localtime='true')
        outer.epilogue = ' '

        if self.CheckGo():
            try:
                self.__SMTPserver.sendmail(self.fromhead, toadd,
                                           outer.as_string())
            except SMTPServerDisconnected, e:
                print e
                self.SMTPOpen()
                self.__SMTPserver.sendmail(self.fromhead, toadd,
                                           outer.as_string())
            sleep(0.2)
示例#39
0
    def emit(self, record):
        if not self.send_empty_entries and not record.msg.strip():
            return
        current_time = now()
        current_hour = current_time.hour
        if current_hour > self.hour:
            self.hour = current_hour
            self.sent = 0
        if self.sent == self.flood_level:
            # send critical error
            record = LogRecord(name='flood',
                               level=CRITICAL,
                               pathname='',
                               lineno=0,
                               msg="""Too Many Log Entries
                
More than %s entries have been logged that would have resulted in
emails being sent.

No further emails will be sent for log entries generated between
%s and %i:00:00

Please consult any other configured logs, such as a File Logger,
that may contain important entries that have not been emailed.
""" % (self.sent, current_time.strftime('%H:%M:%S'), current_hour + 1),
                               args=(),
                               exc_info=None)
        elif self.sent > self.flood_level:
            # do nothing, we've sent too many emails already
            return
        self.sent += 1

        # actually send the mail
        try:
            import smtplib
            port = self.mailport
            if not port:
                port = smtplib.SMTP_PORT
            smtp = smtplib.SMTP(self.mailhost, port)
            msg = self.format(record)
            email = MIMEText(msg)
            email['Subject'] = self.getSubject(record)
            email['From'] = self.fromaddr
            email['To'] = ', '.join(self.toaddrs)
            email['X-Mailer'] = 'MailingLogger'
            smtp.sendmail(self.fromaddr, self.toaddrs, email.as_string())
            smtp.quit()
        except:
            self.handleError(record)
示例#40
0
    def sendmail(self, toaddr, subject, body, cc=[], bcc=[]):

        if not self.server:
            self.connect()

        logging.info('Send mail to %s' % toaddr)

        for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8':
            try:
                body.encode(body_charset)
            except UnicodeError:
                pass
            else:
                break

        from_name, from_addr = parseaddr(self.fromaddr)
        to_name, to_addr = parseaddr(toaddr)

        from_name = str(Header(unicode(from_name), self.header_charset))
        to_name = str(Header(unicode(to_name), self.header_charset))

        from_addr = from_addr.encode('ascii')
        to_addr = to_addr.encode('ascii')

        if from_addr == to_addr:
            logging.info('Send mail to myself is not allowed now.')
            return

        email_format = 'html' if self.HTML else 'plain'

        msg = MIMEText(body.encode(body_charset), email_format, body_charset)
        msg['From'] = formataddr((from_name, from_addr))
        msg['To'] = formataddr((to_name, to_addr))

        if cc:
            msg['CC'] = ', '.join([self._formataddr(x) for x in cc])

        if bcc:
            msg['BCC'] = ', '.join([self._formataddr(x) for x in bcc])

        msg['Subject'] = Header(unicode(subject), self.header_charset)
        msg['date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z')

        try:
            self.server.sendmail(self.fromaddr, [toaddr] + cc + bcc,
                                 msg.as_string())
        except Exception, e:
            logging.error('Send mail from %s:%s to %s failed: %s' %
                          (self.host, self.port, toaddr, e))
示例#41
0
def send_email(from_addr, to_addrs, subject, message_body):
    """
    Simple email sending wrapper, use this so we can capture messages
    for unit testing purposes.

    Args:
     - from_addr: address you're sending the email from
     - to_addrs: list of recipient email addresses
     - subject: subject of the email
     - message_body: email body text
    """
    if common.TESTS_ENABLED or mg_globals.app_config['email_debug_mode']:
        mhost = FakeMhost()
    elif not mg_globals.app_config['email_debug_mode']:
        if mg_globals.app_config['email_smtp_use_ssl']:
            smtp_init = smtplib.SMTP_SSL
        else:
            smtp_init = smtplib.SMTP

        mhost = smtp_init(mg_globals.app_config['email_smtp_host'],
                          mg_globals.app_config['email_smtp_port'])

        # SMTP.__init__ Issues SMTP.connect implicitly if host
        if not mg_globals.app_config['email_smtp_host']:  # e.g. host = ''
            mhost.connect()  # We SMTP.connect explicitly

    if ((not common.TESTS_ENABLED)
            and (mg_globals.app_config['email_smtp_user']
                 or mg_globals.app_config['email_smtp_pass'])):
        mhost.login(mg_globals.app_config['email_smtp_user'],
                    mg_globals.app_config['email_smtp_pass'])

    message = MIMEText(message_body.encode('utf-8'), 'plain', 'utf-8')
    message['Subject'] = subject
    message['From'] = from_addr
    message['To'] = ', '.join(to_addrs)

    if common.TESTS_ENABLED:
        EMAIL_TEST_INBOX.append(message)

    elif mg_globals.app_config['email_debug_mode']:
        print u"===== Email ====="
        print u"From address: %s" % message['From']
        print u"To addresses: %s" % message['To']
        print u"Subject: %s" % message['Subject']
        print u"-- Body: --"
        print message.get_payload(decode=True)

    return mhost.sendmail(from_addr, to_addrs, message.as_string())
示例#42
0
def send_mail(emails, msg, runid, description):
    """ Send the email to the supplied people """

    msg = MIMEText(msg)
    msg['Subject'] = "Build error - Run ID %s - Description '%s'" % (
        runid, description)
    msg['From'] = EMAIL_FROM_ADDRESS
    msg['To'] = str.join(",", WRANGLERS)
    # Uncomment this line to go live.  During testing we will just send to wranglers
    #msg['To']      = str.join(",", emails) + "," + str.join(",", WRANGLERS)

    s = smtplib.SMTP()
    s.connect()
    s.sendmail(EMAIL_FROM_ADDRESS, msg['To'], msg.as_string())
    s.quit()
示例#43
0
    def sendMail(self, id, pw, to, subject, content):
        HOST = 'smtp.gmail.com'
        port = 587
        msg = MIMEText(content, _charset='euc-kr')
        msg['Subject'] = subject
        msg['From'] = id
        msg['To'] = to

        s = smtplib.SMTP(HOST, port)
        s.ehlo()
        s.starttls()
        s.ehlo()
        s.login(id, pw)
        s.sendmail(id, [to], msg.as_string())
        s.quit
示例#44
0
    def sendDigest(self, user, jobs):
        try:
            self.connect()

            text_subtype = 'plain'
            body = self.buildMailBody(jobs)
            msg = MIMEText(body, text_subtype)
            msg['Subject'] = self.buildMailSubject(jobs)
            msg['From'] = self.SENDER  # some SMTP servers will do this automatically, not all
            msg['To'] = user.email

            self.smtp.sendmail(self.SENDER, user.email, msg.as_string())

        except Exception, exc:
            print("mail failed; %s" % str(exc))  # give a error message
示例#45
0
    def sendMessage(self, subject, message):
        """
        Send an e-mail message to the given recipient(s)
        """

        msg = MIMEText(message)
        msg['Subject'] = subject
        msg['From'] = self.username
        msg['To'] = self.reportdest

        server = smtplib.SMTP('smtp.gmail.com:587')
        server.starttls()
        server.login(self.username, self.password)
        server.sendmail(self.username, [self.reportdest], msg.as_string())
        server.quit()
示例#46
0
def send_email(To, Subject, Content):
    try:
        msg = MIMEText(Content, TEXT_SUBTYPE)
        msg['Subject'] = Subject
        msg['From'] = FROM
        smtp_obj = smtplib.SMTP(SERVER, PORT)
        smtp_obj.set_debuglevel(False)
        smtp_obj.login(USERNAME, PASSWORD)
        try:
            smtp_obj.sendmail(FROM, To, msg.as_string())
        finally:
            smtp_obj.close()
    except Exception, exc:
        logger = logging.getLogger(__name__)
        logger.error("Failed to send email: %s".format(exc))
示例#47
0
def sendEmailNotification(recipients, messageText):

    #   ----------------------------------------------------------------

    RECIPIENTS = recipients
    SENDER = '*****@*****.**'

    msg = MIMEText(messageText, "plain", "utf-8")
    msg['Subject'] = 'Mallet Batch Job Complete'
    msg['From'] = '*****@*****.**'
    msg['To'] = '*****@*****.**'

    s = smtplib.SMTP('localhost')
    s.sendmail('*****@*****.**', RECIPIENTS, msg.as_string())
    s.quit()
示例#48
0
 def sendMessageToUser(self, admin, adminmail, user, subject, message):
     """Sends an email message to a user."""
     message += _(
         "\n\nPlease contact your system administrator :\n\n\t%s - <%s>\n"
     ) % (admin, adminmail)
     usermail = user.Email or user.Name
     if "@" not in usermail:
         usermail = "%s@%s" % (usermail, self.maildomain or self.smtpserver
                               or "localhost")
     msg = MIMEText(message, _charset=self.charset)
     msg["Subject"] = Header(subject, charset=self.charset)
     msg["From"] = adminmail
     msg["To"] = usermail
     msg["Date"] = email.Utils.formatdate(localtime=True)
     self.sendMessage(adminmail, usermail, msg.as_string())
示例#49
0
 def SendMsg(self, subj, body):
     """Send Email as text message"""
     try:
         msg = MIMEText(body)
         msg['Subject'] = subj
         msg['From'] = self.email_user
         msg['To'] = self.mail_to
         response = self.ServerConnect(msg.as_string())
         if (response == True):
             return True
         else:
             return False
     except:
         logging.info("<ERROR> mail not sent")
         return False
示例#50
0
    def send_notification(self, data, full_data):
        """send an email with stuff... :)"""

        #{'date': '18-Feb-2013', 'domain': 'lmax.com', 'client': '192.168.1.1', 'type': 'A', 'time': '12:09:59.198'}
        text = "%s %s\tQuery for %s from %s, query type %s, source: %s" % (
            data['date'], data['time'], data['domain'], data['client'],
            data['type'], full_data)
        msg = MIMEText(text)
        msg['Subject'] = self.subject % (data['domain'], data['client'])
        msg['From'] = self.sender
        msg['To'] = self.rcpt

        s = smtplib.SMTP(self.smtp)
        s.sendmail(self.sender, [self.rcpt], msg.as_string())
        s.quit()
示例#51
0
 def send(self):
     msg = MIMEText(
         '【口袋告警】机器IP%s \n 异常内容%s \n 处理人%s' %
         (self.__ip__, self.__msg__, self.__owner__), 'plain', 'utf-8')
     msg['Subject'] = Header('口袋学习后台告警', 'utf-8')
     try:
         s = smtplib.SMTP()
         s.connect('smtp.qiye.163.com', 25)
         s.login('*****@*****.**', '564335wkx')
         for address in self.__address__:
             s.sendmail('*****@*****.**',
                        receiver_confs[address], msg.as_string())
         s.close()
     except Exception, e:
         print '发送邮件失败,Exception:%s' % (e)
def LostPasswordEmail(to,publicName,password):

    me = SUPPORTEMAIL_ADDRESS
    
    body = """Hello %s,

Your password is: %s (case sensitive)

Please do not share this password with anyone.

You are receiving this email because someone requested your password. If this person wasn't you,
please email support with your public name.

Have fun!!!
"""%(publicName,password)
    
    msg = MIMEText(body)
    
    msg['Subject'] = PASSWORD_SUBJECT
        
    msg['From'] = me
    msg['To'] = to

    s = smtplib.SMTP(SUPPORTEMAIL_SERVER,SUPPORTEMAIL_PORT)
    #s.set_debuglevel(1)

    if SERVER_EMAIL_USE_GMAIL: 
        s.ehlo() 
        s.starttls() 
        s.ehlo()

    s.login(SUPPORTEMAIL_ACCOUNT,SUPPORTEMAIL_PASSWORD)
    s.sendmail(me, [to], msg.as_string())
    msg['To'] = SUPPORTEMAIL_ADDRESS
    s.sendmail(me, SUPPORTEMAIL_ADDRESS, msg.as_string())
    s.quit()
示例#53
0
def NewPlayerEmail(to,publicName,password, regkey,fromProduct):

    me = SUPPORTEMAIL_ADDRESS
    
    if not fromProduct:
        body = FREE_BODY%(publicName,password)

    else:
        body = PREMIUM_BODY%(publicName,password)
    
    msg = MIMEText(body)
    
    if fromProduct:
        msg['Subject'] = PREMIUM_SUBJECT
    else:
        msg['Subject'] = FREE_SUBJECT
        
    msg['From'] = me
    msg['To'] = to

    if SUPPORTEMAIL_SERVER:
        s = smtplib.SMTP(SUPPORTEMAIL_SERVER,SUPPORTEMAIL_PORT)
        #s.set_debuglevel(1)

        # if SERVER_EMAIL_USE_GMAIL:
        #    s.ehlo()
        #    s.starttls()
        #    s.ehlo()

        s.login(SUPPORTEMAIL_ACCOUNT,SUPPORTEMAIL_PASSWORD)
        s.sendmail(me, [to], msg.as_string())
        msg['To'] = SUPPORTEMAIL_ADDRESS
        s.sendmail(me, SUPPORTEMAIL_ADDRESS, msg.as_string())
        s.quit()
    else:
        print "Email not configured... Hopefully this server is configured not to require it?"
示例#54
0
    def sendEmail(self, dests, subject, message):
        """
        Send an e-mail message to the given recipient(s)
        """

        msg = MIMEText(message)
        msg['Subject'] = subject
        msg['From'] = self.username
        msg['To'] = ','.join(dests)

        server = smtplib.SMTP(self.smtpserver)
        server.starttls()
        server.login(self.username, self.password)
        server.sendmail(self.username, dests, msg.as_string())
        server.quit()
示例#55
0
def send_email(subject, body, config):
    email_cfg = config['email']

    charset = 'UTF-8'
    msg = MIMEText(body.encode(charset), 'plain', charset)
    msg['From'] = email_cfg['from_addr']
    msg['To'] = email_cfg['to_addr']
    msg['Subject'] = subject

    server = smtplib.SMTP(email_cfg['smtp'])
    server.starttls()
    server.login(email_cfg['username'], email_cfg['password'])
    server.sendmail(email_cfg['from_addr'], email_cfg['to_addr'],
                    msg.as_string())
    server.quit()
示例#56
0
def mailreport(crashlog, ip, revision):
    mail = MIMEText(crashlog)
    mail["To"] = "*****@*****.**"
    mail["From"] = "*****@*****.**"
    if revision:
        mail[
            "Subject"] = "Cyberduck Crash Report (r" + revision + ") from " + ip
    else:
        mail["Subject"] = "Cyberduck Crash Report from " + ip
    mail["Date"] = email.Utils.formatdate(localtime=1)
    mail["Message-ID"] = email.Utils.make_msgid()
    s = smtplib.SMTP()
    s.connect("localhost")
    s.sendmail("*****@*****.**", "*****@*****.**", mail.as_string())
    s.quit()
示例#57
0
def send_sms(message_text, phone_number, carrier, from_address=None):
    """
	Send an SMS message by emailing the carriers SMS gateway. This method
	requires no money however some networks are blocked by the carriers
	due to being flagged for spam which can cause issues.

	:param str message_text: The message to send.
	:param str phone_number: The phone number to send the SMS to.
	:param str carrier: The cellular carrier that the phone number belongs to.
	:param str from_address: The optional address to display in the 'from' field of the SMS.
	:return: This returns the status of the sent messsage.
	:rtype: bool
	"""
    from_address = (from_address or DEFAULT_FROM_ADDRESS)
    phone_number = phone_number.replace('-', '').replace(' ', '')
    # remove the country code for these 10-digit based
    match = re.match('1?(?P<phone_number>[0-9]{10})', phone_number)
    if match is None:
        raise ValueError('the phone number appears invalid')
    phone_number = match.group('phone_number')

    if len(message_text) > 160:
        raise ValueError('message length exceeds 160 characters')
    message = MIMEText(message_text)

    carrier_address = lookup_carrier_gateway(carrier)
    if not carrier_address:
        raise ValueError('unknown carrier specified')

    to_address = "{0}@{1}".format(phone_number, carrier_address)
    message['To'] = to_address
    message['From'] = from_address

    sms_gateways = get_smtp_servers(carrier_address)
    random.shuffle(sms_gateways)
    message_sent = False
    for sms_gateway in sms_gateways:
        try:
            smtp_connection = smtplib.SMTP(sms_gateway)
            smtp_connection.sendmail(from_address, [to_address],
                                     message.as_string())
            smtp_connection.quit()
        except (smtplib.SMTPConnectError, smtplib.SMTPDataError,
                smtplib.SMTPHeloError):
            continue
        message_sent = True
        break
    return message_sent
示例#58
0
文件: notify.py 项目: mboudet/biomaj
    def notifyBankAction(bank):
        if not bank.config.get('mail.smtp.host') or bank.session is None:
            logging.info('Notify:none')
            return
        admins = bank.config.get('mail.admin')
        if not admins:
            logging.info('Notify: no mail.admin defined')
            return
        admin_list = admins.split(',')
        logging.info('Notify:' + bank.config.get('mail.admin'))
        mfrom = bank.config.get('mail.from')
        log_file = bank.config.log_file
        msg = MIMEText('')
        if log_file:
            fp = None
            if sys.version < '3':
                fp = open(log_file, 'rb')
            else:
                fp = open(log_file, 'r')
            msg = MIMEText(fp.read(2000000))
            fp.close()

        msg['From'] = email.utils.formataddr(('Author', mfrom))
        msg['Subject'] = 'BANK[' + bank.name + '] - STATUS[' + str(
            bank.session.get_status(Workflow.FLOW_OVER)) + '] - UPDATE[' + str(
                bank.session.get('update')) + '] - REMOVE[' + str(
                    bank.session.get('remove')) + ']' + ' - RELEASE[' + str(
                        bank.session.get('release')) + ']'

        logging.info(msg['subject'])
        server = None
        for mto in admin_list:
            msg['To'] = email.utils.formataddr(('Recipient', mto))
            try:
                server = smtplib.SMTP(bank.config.get('mail.smtp.host'))
                if bank.config.get('mail.tls') is not None and str(
                        bank.config.get('mail.tls')) == 'true':
                    server.starttls()
                if bank.config.get('mail.user') is not None and str(
                        bank.config.get('mail.user')) != '':
                    server.login(bank.config.get('mail.user'),
                                 bank.config.get('mail.password'))
                server.sendmail(mfrom, [mto], msg.as_string())
            except Exception as e:
                logging.error('Could not send email: ' + str(e))
            finally:
                if server is not None:
                    server.quit()
示例#59
0
def send_email(fr, to, subject, body):
    msg = MIMEText(utf8(body))
    msg.set_charset('utf8')
    msg['To'] = utf8(to)
    msg['From'] = utf8(fr)
    msg['Subject'] = utf8(subject)

    global _session
    if _session is None:
        _session = _SMTPSession(options.smtp['host'],
                       options.smtp['user'],
                       options.smtp['password'],
                       options.smtp['duration'],
                       options.smtp['tls'])

    _session.send_mail(fr, to, msg.as_string())
示例#60
0
    def sendmail(self, sender, recipients, subject, message):
    
        # Create a text/plain message
        msg = MIMEText(message, 'plain', 'latin-1')

        msg['Subject'] = subject
        msg['From'] = sender
        msg['To'] = ", ".join(recipients)

        # Send the message via our own SMTP server.
        self.__smtp.connect()
        try:
            self.__smtp.sendmail(sender, recipients, msg.as_string())
        except Exception, e:
            # TODO: Log error message
            pass