Exemplo n.º 1
0
    def send(self, message, user, subject='Message from TheBot', in_reply_to=None):
        to_email = user.id

        logger = logging.getLogger('thebot.batteries.mail')
        logger.debug('Sending email to "{}" in reply to "{}"'.format(to_email, in_reply_to))

        cfg = self.bot.config

        port = int(cfg.smtp_port)
        if port == 25:
            server = smtplib.SMTP(cfg.smtp_host, port)
        else:
            server = smtplib.SMTP_SSL(cfg.smtp_host, port)

        server.login(cfg.smtp_username, cfg.smtp_password)
        #server.set_debuglevel(1)

        from_email = getattr(cfg, 'smtp_from', None)
        if from_email is None and '@' in cfg.smtp_username:
            from_email = cfg.smtp_username
        else:
            raise RuntimeError('Please, specify "--smtp-from" option.')

        response = email.message.Message()
        response['From'] = '*****@*****.**'
        response['To'] = to_email
        response['Subject'] = subject
        if in_reply_to:
            response['In-Reply-To'] = in_reply_to
        response.set_payload(message.encode('utf8'), 'utf-8')

        server.sendmail(from_email, to_email, response.as_string())
        server.quit()
Exemplo n.º 2
0
def __send_mail(email_server, email_login, email_pass, email_to, message, logfile=''):
    logging.debug("sending email")

    msg_root = MIMEMultipart('mixed')
    msg_root['To'] = email.utils.formataddr(('Recipient', ', '.join(email_to)))
    msg_root['From'] = email.utils.formataddr(('MIS auto-report logs checker', email_login))

    msg_related = MIMEMultipart('related')
    msg_root.attach(msg_related)

    msg_alternative = MIMEMultipart('alternative')
    msg_related.attach(msg_alternative)

    msg_text = MIMEText(message.encode('utf-8'), 'plain', 'utf-8')
    msg_alternative.attach(msg_text)

    msg_html = MIMEText(message.encode('utf-8'), 'html', 'utf-8')
    msg_alternative.attach(msg_html)

    subject = 'All is ok'
    with open(logfile, 'r', encoding='cp1251') as f:
        file_content = f.read()
        if "error" in file_content.lower():
            subject = 'There is some errors in logs'
            msg_attach = MIMEBase('application', 'octet-stream')
            msg_attach.set_payload(file_content.encode())
            encoders.encode_base64(msg_attach)
            msg_attach.add_header('Content-Disposition', 'attachment',
                                  filename=(Header(path.basename(logfile), 'utf-8').encode()))
            msg_root.attach(msg_attach)

    msg_root['Subject'] = subject
    try:
        server = smtplib.SMTP(email_server)
        # server.set_debuglevel(True)
        server.ehlo()

        if server.has_extn('STARTTLS'):
            server.starttls()
            server.ehlo()

        server.login(email_login, email_pass)
        server.send_message(msg_root)
        server.quit()
    except Exception as err:
        logging.error("!!! ERROR: cannot send an email: " + repr(err))
Exemplo n.º 3
0
def send_email(assunto, message, destinatarios, meu_email,
               senha):  #FUNÇÃO PARA ENVIO DE EMAIL
    # Configuração do Envio do email
    msg = email.message.Message()
    msg['From'] = meu_email
    msg['Subject'] = assunto
    msg.add_header('Content-Type', 'text/html; charset=utf-8')
    msg.add_header('Content-Disposition', 'inline')
    msg.add_header('Content-Transfer-Encoding', '8bit')
    msg.set_payload(message.encode('utf-8'))
    # Configuração do Gerenciador de Email
    server = smtplib.SMTP('outlook.office365.com: 587')
    server.starttls()
    # Fazendo Login para enviar o email
    server.login(msg['From'], senha)
    # Enviando o email
    server.sendmail(msg['From'], destinatarios, msg.as_string())
    # Trabalho feito, desconectando
    server.quit()
Exemplo n.º 4
0
    def send(self,
             message,
             user,
             subject='Message from TheBot',
             in_reply_to=None):
        to_email = user.id

        logger = logging.getLogger('thebot.batteries.mail')
        logger.debug('Sending email to "{}" in reply to "{}"'.format(
            to_email, in_reply_to))

        cfg = self.bot.config

        port = int(cfg.smtp_port)
        if port == 25:
            server = smtplib.SMTP(cfg.smtp_host, port)
        else:
            server = smtplib.SMTP_SSL(cfg.smtp_host, port)

        server.login(cfg.smtp_username, cfg.smtp_password)
        #server.set_debuglevel(1)

        from_email = getattr(cfg, 'smtp_from', None)
        if from_email is None and '@' in cfg.smtp_username:
            from_email = cfg.smtp_username
        else:
            raise RuntimeError('Please, specify "--smtp-from" option.')

        response = email.message.Message()
        response['From'] = '*****@*****.**'
        response['To'] = to_email
        response['Subject'] = subject
        if in_reply_to:
            response['In-Reply-To'] = in_reply_to
        response.set_payload(message.encode('utf8'), 'utf-8')

        server.sendmail(from_email, to_email, response.as_string())
        server.quit()
Exemplo n.º 5
0
 def _log(self, message, *args, **kwargs):# rec=0, verbosity=1):
     """
     Log a message using :mod:`syslog` as well as :attr:`sys.stdout`.
     
     :param   message: The pre-formatted log message.
     :param       rec: Optional recursion level used to indent messages.
     :param verbosity: Minimal verbosity required to display this message.
     :returns: :const:`None`
     """
     
     verbosity = kwargs.get('verbosity', 1)
     rec       = kwargs.get('rec', 0)
     
     if self._conf.verbose and self._conf.verbosity >= verbosity:
         format_args = []
         
         for a in args:
             if isinstance(a, unicode):
                 format_args.append(a.encode('UTF-8'))
             else:
                 format_args.append(a)
         
         if isinstance(message, unicode):
             message = message.encode('UTF-8')
         
         message = '{0}{1}'.format(' '*rec, message.format(*format_args))
         if verbosity < 2:
             if message.strip().startswith('!!!'):
                 self._logger.error(message)
             else:
                 self._logger.info(message)
         else:
             if message.strip().startswith('!!!'):
                 self._logger.warning(message)
             else:
                 self._logger.debug(message)
Exemplo n.º 6
0
    def _log(self, message, *args, **kwargs):  # rec=0, verbosity=1):
        """
        Log a message using :mod:`syslog` as well as :attr:`sys.stdout`.
        
        :param   message: The pre-formatted log message.
        :param       rec: Optional recursion level used to indent messages.
        :param verbosity: Minimal verbosity required to display this message.
        :returns: :const:`None`
        """

        verbosity = kwargs.get('verbosity', 1)
        rec = kwargs.get('rec', 0)

        if self._conf.verbose and self._conf.verbosity >= verbosity:
            format_args = []

            for a in args:
                if isinstance(a, unicode):
                    format_args.append(a.encode('UTF-8'))
                else:
                    format_args.append(a)

            if isinstance(message, unicode):
                message = message.encode('UTF-8')

            message = '{0}{1}'.format(' ' * rec, message.format(*format_args))
            if verbosity < 2:
                if message.strip().startswith('!!!'):
                    self._logger.error(message)
                else:
                    self._logger.info(message)
            else:
                if message.strip().startswith('!!!'):
                    self._logger.warning(message)
                else:
                    self._logger.debug(message)
Exemplo n.º 7
0
 def write_message(self, message, binary=False):
     if binary:
         self._send(2, message)
     else:
         self._send(1, message.encode('utf8'))
Exemplo n.º 8
0
 def write_message(self, message, binary=False):
     if binary:
         self._send(2, message)
     else:
         self._send(1, message.encode('utf8'))
Exemplo n.º 9
0
    def send(self, retry_count=0, recipient_list=None):
        """
        Iterate over the recipient list and send the specified email.
        """
        if config.ENCRYPT_MODE != 'none' and config.ENCRYPT_MODE != 'ssl' and config.ENCRYPT_MODE != 'starttls':
            raise Exception("Please choose a correct ENCRYPT_MODE")

        if not recipient_list:
            recipient_list = self._parse_csv()
            if retry_count:
                recipient_list = self._parse_csv(config.CSV_RETRY_FILENAME)

        # save the number of recipient and time started to the stats file
        if not retry_count:
            self._stats("TOTAL RECIPIENTS: %s" % len(recipient_list))
            self._stats("START TIME: %s" % datetime.now())

        # instantiate the number of falied recipients
        failed_recipients = 0

        for recipient_data in recipient_list:
            # instantiate the required vars to send email
            message = self._form_email(recipient_data)
            if recipient_data.get('name'):
                recipient = "%s <%s>" % (recipient_data.get('name'),
                                         recipient_data.get('email'))
            else:
                recipient = recipient_data.get('email')
            sender = "%s <%s>" % (self.from_name, self.from_email)

            for nb in range(0, self.nb_emails_per_recipient):
                print("Sending to %s..." % recipient)
                try:
                    # send the actual email

                    if config.ENCRYPT_MODE == 'ssl':
                        smtp_server = smtplib.SMTP_SSL(host=config.SMTP_HOST,
                                                       port=config.SMTP_PORT,
                                                       timeout=10)
                    else:
                        smtp_server = smtplib.SMTP(host=config.SMTP_HOST,
                                                   port=config.SMTP_PORT,
                                                   timeout=10)

                    if config.ENCRYPT_MODE != 'none':
                        smtp_server.ehlo()
                        if config.ENCRYPT_MODE == 'starttls':
                            smtp_server.starttls()
                            smtp_server.ehlo()

                    if config.SMTP_USER and config.SMTP_PASSWORD:
                        smtp_server.login(config.SMTP_USER,
                                          config.SMTP_PASSWORD)

                    smtp_server.sendmail(sender, recipient,
                                         message.encode("utf8"))
                    smtp_server.close()
                    # save the last recipient to the stats file incase the process fails
                    self._stats("LAST RECIPIENT: %s" % recipient)

                    # allow the system to sleep for .25 secs to take load off the SMTP server
                    sleep(0.25)
                except smtplib.SMTPException as e:
                    print("EXCEPTION")
                    print(repr(e))
                    logging.error(
                        "Recipient email address failed: %s\n=== Exception ===\n%s"
                        % (recipient, repr(e)))
                    self._retry_handler(recipient_data)

                    # save the number of failed recipients to the stats file
                    failed_recipients = failed_recipients + 1
                    self._stats("FAILED RECIPIENTS: %s" % failed_recipients)