Example #1
0
def send_email(func, target, code):
    if func == settings.FUNCTION_REGISTER:
        content = T(u"<html><p>您正在进行用户注册操作,验证码 {{ code }},请在 15 分钟内按提示提交验证码。")
    elif func == settings.FUNCTION_UPDATE:
        content = T(u"<html><p>您正在进行手机号更新操作,验证码 {{ code }},请在 15 分钟内按提示提交验证码。")
    elif func == settings.FUNCTION_RESET:
        content = T(u"<html><p>您正在进行密码重置操作,验证码 {{ code }},请在 15 分钟内按提示提交验证码。")
    else:
        logger.warning('invalid function parameter %s' % func)
        return

    m = emails.Message(
        html=content,
        subject=T(u"随阅易手机阅读 - 验证码"),
        mail_from=(u"随阅易手机阅读", settings.SMTP_FROM),
    )
    response = m.send(
        render={
            "code": code,
        },
        to=target,
        smtp={
            "host": settings.SMTP_SERVER,
            "port": settings.SMTP_PORT,
            'ssl': True,
            'user': settings.SMTP_FROM,
            'password': settings.SMTP_PASSWORD,
        },
    )
    if response.status_code not in [250, ]:
        logger.warning('cannot send email, target=%s, code=%s. %s' % (target, code, str(response)))
        return
    logger.info('email has sent, target=%s, code=%s' % (target, code))
Example #2
0
    def send_password_reset_code(self):
        """Create a password reset code"""
        reset_token = ''.join(
            random.SystemRandom().choice(string.ascii_letters + string.digits)
            for _ in range(RESET_TOKEN_LEN))
        self._data['_reset_token'] = reset_token
        self._set_modified(True)
        self.save()
        logger.info("Password reset requested for (%s) : %s", self.email,
                    reset_token)
        with (Path(app.config.ASSETS_PATH) / 'html/recover.html').open() as html, \
                (Path(app.config.ASSETS_PATH) / 'txt/recover.txt').open() as txt, \
                (Path(app.config.ASSETS_PATH) / 'img/epmanage.png').open('rb') as logo:
            msg = Message(
                html=T(html.read()),
                text=T(txt.read()),
                subject="Account recovery for {}".format(self.email),
                mail_from=("EPManage", app.config.EMAIL_ADDRESS),
                message_id=make_msgid(domain=app.config.EMAIL_DOMAIN))
            msg.attach(filename="epmanage.png",
                       content_disposition="inline",
                       data=logo)

            msg.send(to=self.email,
                     render={
                         'USER_EMAIL':
                         self.email,
                         'URL_TO_RESET':
                         "{}/{}".format(app.config.RECOVERY_URL, reset_token)
                     })
        return True
Example #3
0
def send_email(min_data):
    '''Send an email notification with the min temp & time and a plot of the temperature forecast.

    Parameters
    ----------
    min_data : tuple
        Minimum temperature, datetime object of minimum temperature
    '''

    message = emails.html(subject=T(email_subject),
                          html=T(email_contents),
                          mail_from=(config.email["from"]["name"],
                                     config.email["from"]["email"]))

    message.attach(filename='temps_plot.png',
                   data=open('temps_plot.png', 'rb'))
    message.attachments['temps_plot.png'].is_inline = True
    message.transformer.synchronize_inline_images()
    message.transformer.save()

    render_data = {
        "temperature": min_data[0],
        "temp_time": min_data[1].strftime("%-I:%M %p on %A %b %-d"),
        "now": datetime.now().strftime("%-I:%M %p %A %b %-d %Y")
    }

    return message.send(to=(config.email["to"]["name"],
                            config.email["to"]["email"]),
                        render=render_data,
                        smtp=config.email["smtp"])
Example #4
0
def send_email():
    message = emails.html(subject=T('测试邮件'),
                          html=T('<p>详情见附件<br><br>'),
                          mail_from=('auto-reporter', USERNAME))
    message.attach(data=open('../log/2020-01-16 10-50-03.xlsx', 'rb'),
                   filename="2020-01-16 10-50-03.xlsx")
    r = message.send(to=USERNAME, smtp=smtp_conf)
    print(r)
Example #5
0
def send_email():
    message = emails.html(subject=T('Html email Testing'),
                        html=T(open('email_tmpl.html').read()),
                        mail_from=('auto-reporter', USERNAME))
    message.attach(data=open('readme.md', 'r'), filename="readme.txt")
    message.attach(filename="test.png", content_disposition="inline", data=open("test.png", "rb"))
    r = message.send(to=('Orangleliu', USERNAME),
                    render={'name': 'ALL', 'img_name': "test.png"},
                    smtp={'host': SMTP})
    
    print(r.status_code)
Example #6
0
def send_email(username, password, receiver, receiver_email):
    message = emails.html(subject=T('MICL Cluster Password'),
                          html=T(
                              '<p>Server IP: <b>155.69.146.213</b>'
                              '<p>Your username is <b>{{username}}</b>'
                              '<p>Your password is <b>{{password}}</b>'
    ),
        mail_from=('auto-reporter', USERNAME))
    r = message.send(to=(receiver, receiver_email), render={
        'username': username,
        'password': password}, smtp=smtp_conf)

    return r
    def send_eamil(self, sender_nick_name, receivers, subject, content):
        user_name = self.smpt['user']
        message = emails.html(subject=T(subject),
                          html=T(content),
                          mail_from=(sender_nick_name, user_name)) 

        logs = []
        for receiver in receivers:
            print('发送中:' + receiver + '.....')
            history = message.send(to=(None, receiver), smtp=self.smpt)
            logs.append(history)

        return logs
Example #8
0
    def invite(data: dict):
        """
        Create a Client object ready for registration
        :return: the registration_token to be used for registration
        """
        max_agents = data.pop('max_agents')
        if max_agents > app.config.INVITE_MAX_AGENTS:
            raise AuthException("Please set a maximum of {} agents".format(app.config.INVITE_MAX_AGENTS))
        max_users = data.pop('max_users')
        if max_users > app.config.INVITE_MAX_USERS:
            raise AuthException("Please set a maximum of {} users".format(app.config.INVITE_MAX_USERS))
        client = epmanage.lib.client.Client()
        client.invitation_email = data.pop('email')
        client.max_agents = max_agents
        client.max_users = max_users
        client.token = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.digits) for _ in range(32))
        client.registration_token = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.digits)
                                            for _ in range(20))
        client.database_settings = dict(
            DBNAME='{}_corp'.format(client.token)
        )
        client.save()
        client.insert_default_data()

        sender = AuthController.get_current_identity().get_user()
        user_name = "{} {}".format(sender.firstname, sender.lastname)
        user_email = sender.email

        with (Path(app.config.ASSETS_PATH) / 'html/invite.html').open() as html, \
                (Path(app.config.ASSETS_PATH) / 'txt/invite.txt').open() as txt, \
                (Path(app.config.ASSETS_PATH) / 'img/rocket.png').open('rb') as rocket, \
                (Path(app.config.ASSETS_PATH) / 'img/epmanage.png').open('rb') as logo:
            msg = Message(
                html=T(html.read()),
                text=T(txt.read()),
                subject="Invitation to the EPManage",
                mail_from=(user_name, user_email),
                message_id=make_msgid(domain=app.config.EMAIL_DOMAIN))
            msg.attach(filename="rocket.png", content_disposition="inline", data=rocket)
            msg.attach(filename="epmanage.png", content_disposition="inline", data=logo)

            msg.send(to=client.invitation_email, render={
                'USER_NAME': user_name,
                'USER_EMAIL': user_email,
                'URL_TO_JOIN': "{}/{}".format(app.config.REGISTRATION_URL, client.registration_token)
            })

        return client.registration_token
Example #9
0
    def notify_recipient(self, sites: List[settings.Site],
                         addresses: List = []) -> None:
        """
        Method sends notification to recipients
        & updates self.sent_report with results.
        """

        if not sites:
            print("There are no sites with expiring SSL certificates")

        if not addresses:
            addresses = self.recipients

        message = emails.html(
            mail_from=("ITS Certificate Automate Checker", "*****@*****.**"),
            html=T(open("letter.html").read()),
            subject="To admins & engineers",
        )

        for addr in addresses:
            r = message.send(
                to=("To admins & engineers ", addr),
                render={"sites": sites},
                smtp=settings.smtp_config._asdict()
            )

            self.sent_report[addr] = r.status_code == 250
Example #10
0
    def _get_message(self):

        options = self.options

        if options.message_id_domain:
            message_id = emails.MessageID(domain=options.message_id_domain)
        else:
            message_id = None

        args = dict(images_inline=options.inline_images,
                    message_params=dict(
                        headers=self._headers_from_command_line(),
                        mail_from=(options.from_name, options.from_email),
                        subject=T(unicode(options.subject, 'utf-8')),
                        message_id=message_id),
                    template_cls=T)
        if options.url:
            message = emails.loader.from_url(url=options.url, **args)
        elif options.from_directory:
            message = emails.loader.from_directory(options.from_directory,
                                                   **args)
        elif options.from_file:
            message = emails.loader.from_file(options.from_file, **args)
        elif options.from_zipfile:
            message = emails.loader.from_zip(options.from_zipfile, **args)
        else:
            logging.error('No message source specified.')
            sys.exit(1)

        return message
    async def _send(self, body: dict, template: str) -> dict:
        subject = body.get('subject', '')
        message = emails.html(subject=subject,
                              html=T(template),
                              mail_from=('Ardas Inc', self.email_address))
        response = message.send(
            to=body['to_addr'],
            render={
                'to_name': body['to_name'],
                'linc': body['linc']
            },
            smtp={
                'host': self.smtp_server,
                'port': self.smtp_port,
                'tls': True,
                'user': self.login,
                'password': self.password
            },
        )
        status = response.status_code
        text = response.status_text.decode('utf-8')

        if status != 250:
            return {'success': False, 'error': text}

        return {'success': True, 'transaction_id': text.split()[1]}
Example #12
0
async def email_sender(body: dict,
                       template: str,
                       config: dict,
                       subject='None'):

    message = emails.html(subject=subject,
                          html=T(template),
                          mail_from=('Ardas Inc', config['EMAIL_ADDRESS']))
    response = message.send(
        to=body['to_addr'],
        render={
            'to_name': body['to_name'],
            'linc': body['linc']
        },
        smtp={
            'host': config['SMTP_SERVER'],
            'port': config['SMTP_PORT'],
            'tls': True,
            'user': config['LOGIN'],
            'password': config['PASSWORD']
        },
    )
    status = response.status_code
    text = response.status_text.decode('utf-8')

    if status != 250:
        raise web.HTTPUnprocessableEntity(content_type='application/json',
                                          body=json.dumps({
                                              'success': False,
                                              'error': text
                                          }))

    return {'success': True, 'transaction_id': text.split()[1]}
Example #13
0
def send_email(
        email_to: str,
        subject_template: str = "",
        html_template: str = "",
        environment=None,
) -> None:
    """
    send email to some mail address
    :param email_to: send to this email
    :param subject_template: email subject
    :param html_template: email content
    :param environment: template params
    :return: email send response
    """
    if environment is None:
        environment = {}

    assert settings.EMAILS_ENABLED, "no provided configuration for email variables"

    # email message
    message = emails.Message(
        subject=T(subject_template),
        html=T(html_template),
        mail_from=(settings.EMAILS_FROM_NAME, settings.EMAILS_FROM_EMAIL),
    )

    # smtp server
    smtp_options = {"host": settings.SMTP_HOST, "port": settings.SMTP_PORT}
    if settings.SMTP_SSL:
        smtp_options["ssl"] = True
    if settings.SMTP_USER:
        smtp_options["user"] = settings.SMTP_USER
    if settings.SMTP_PASSWORD:
        smtp_options["password"] = settings.SMTP_PASSWORD

    # send
    response = message.send(to=email_to, render=environment, smtp=smtp_options)

    if response.status_code not in [
        250,
    ]:
        logger.info(f"send email failed {response}")

    else:
        logger.info(f"send email to {email_to} successfully")
Example #14
0
def send_email():
    message = emails.html(
        subject=T('Payment Receipt No.{{ billno }}'),
        html=T('<p>Dear {{ name }}! This is a receipt...<br><br>'),
        mail_from=('auto-reporter', USERNAME))
    message.attach(data=open('readme.md', 'r'), filename="readme.txt")
    r = message.send(to=('Orangleliu', USERNAME),
                     render={
                         'name': 'Orangleliu',
                         'billno': '141051906163'
                     },
                     smtp={
                         'host': SMTP,
                         'user': USERNAME,
                         'password': PASSWORD
                     })

    print(r.status_code)
Example #15
0
    def _create_message_from_template(self, mail_to, subject, template_path, cc, bcc, templates_encoding):
        mail_from = self.smtp_settings.sender

        full_template_path = path.join(self.templates_path, template_path)
        with io.open(full_template_path, 'r', encoding=templates_encoding) as file:
            template_content = file.read()
            file.close()

        message = emails.Message(
            mail_from=mail_from, mail_to=mail_to, cc=cc, bcc=bcc, subject=T(subject), html=T(template_content))
        return message
Example #16
0
def send_email(to_email):

    html = """
    <html>  
    <head></head>  
    <body>  
        <p>Hi!<br>  
        How are you?<br>  
        Here is the <a href="http://www.baidu.com">link</a> you wanted.<br> 
        </p> 
        <img src="https://img-blog.csdnimg.cn/20200813165242761.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxNTk2NzM0,size_16,color_FFFFFF,t_70#pic_center" alt="在这里插入图片描述">
    </body>  
    </html>  
    """
    message = emails.html(subject=T('测试邮件'),
                          html=T(html),
                          mail_from=('Jack.Wu', USERNAME))
    # message.attach(data=open('readme.md', 'r'), filename="readme.txt")
    r = message.send(to=(to_email), smtp=smtp_conf)
    print(r)
Example #17
0
def send_email(to: tuple,
               message_type: str,
               attachment: str,
               mail_from: tuple = ('Infra Provisioner',
                                   '*****@*****.**')):
    gpg = gnupg.GPG(gnupghome=GPG_HOME)

    filename = f"terraform-{message_type}-output.txt.asc"

    to_emails, recipient_keys = zip(*to)

    encrypted_ascii_data = gpg.encrypt(attachment,
                                       recipient_keys,
                                       always_trust=True)

    assert encrypted_ascii_data.ok is True, f"Invalid GPG Key {encrypted_ascii_data.stderr} recipients {to}"

    subject = EMAIL_DATA.get(message_type).get('subject')
    body = EMAIL_DATA.get(message_type).get('message')

    message = emails.html(text=T(body),
                          subject=T(subject),
                          mail_from=MAIL_FROM)

    message.attach(data=bytes(str(encrypted_ascii_data).encode('utf8')),
                   filename=filename)
    message.send(to=to_emails,
                 render={
                     'stderr': encrypted_ascii_data.stderr,
                     'to': to
                 },
                 smtp={
                     'host': SMTP_SERVER,
                     'port': SMTP_PORT,
                     'ssl': SMTP_SSL,
                     'user': SMTP_USERNAME,
                     'password': SMTP_PASSWORD
                 })
Example #18
0
import emails
from emails.template import JinjaTemplate as T


message = emails.html(
    subject=T('Payment Receipt No.{{ billno }}'),
    html=T('<p>Dear {{ name }}! This is a receipt...'),
    mail_from=('Dj Huj', '*****@*****.**')
)

res = message.send(
    to=('Yuru Danilin', '*****@*****.**'),
    render={'name': 'John Brown', 'billno': '141051906163'},
    smtp={
        'host': 'smtp.yandex.ru',
        'port': 465,
        'ssl': True,
        'user': '******',
        'password': '******'
    }
)

print(f"Sending status code: {res.status_code}")
Example #19
0
def process(terrayaml: str, metadata: dict, logger: KopfObjectLogger) -> str:
    #
    # User input YAML
    #
    env = jinja2.Environment()
    env.filters['random_password'] = random_password
    env.filters['random_name'] = random_name

    template = T(template_text=terrayaml, environment=env).render(**metadata)

    provision = yaml.load(template, Loader=yaml.FullLoader)
    logger.info(f"provision this template {provision}")
    # print(provision)

    #
    # Start terraform
    #
    meta = provision.pop('meta', {})
    team = meta.get('team', 'oss')
    profile = meta.get('profile', PROFILE)
    environment = meta.get('environment', 'testing')
    application = meta.get('application', 'wurkflow')
    statefile_region = meta.get('statefile_region', 'eu-west-1')

    ts = Terrascript()
    ts += Terraform(required_version=">= 0.12.7").backend(
        "s3",
        bucket=REMOTE_STATE_S3_BUCKET,
        key=
        f"k8/terrayaml-operator/{team}/{environment}/{application}-terraform.tfstate",
        region=statefile_region,
        profile=ROOT_PROFILE)

    #
    # Extract the notify component
    #
    notify = provision.pop('notify')
    if notify:
        # tuple of email, key
        recipient_emails = notify.get('email', [])
        # append out infra provisioner email
        recipient_emails.append('*****@*****.**')
        recipients = get_recipients_from_pgp(recipient_emails=recipient_emails)
        logger.info(f"notify these emails: {recipient_emails}")

    #
    # Parse the yaml
    #
    for provider in provision:
        #print(f"----- output for provider: {provider.upper()} -----")
        for resource, data in provision.get(provider).items():
            #print(f"----- output for resource: {resource} -----")
            for item in data.get('items', []):
                api = TF_YAML_MAP.get(resource)
                outputs = item.pop('outputs', [])
                item_name = item.pop('name', random_name(value=resource))
                tf_resource = api(item_name, **item)
                ts.add(tf_resource)

                # handle terraform outputs
                for opt in outputs:
                    assert getattr(
                        tf_resource, opt.get('value')
                    ), f"{tf_resource} has no attribute {opt.get('value')}"
                    ts.add(
                        Output(opt.get('name'),
                               value=getattr(tf_resource, opt.get('value'))))

    # Add a provider (+= syntax)
    ts += Provider('aws',
                   skip_metadata_api_check=True,
                   profile=profile,
                   region=REGION)
    data = ts.dump()

    # Plan
    working_dir = tempfile.mkdtemp(dir='./runs')
    crd_api = kubernetes.client.CustomObjectsApi()
    selfLink = metadata.get('selfLink').split('/')
    # update with planId
    logger.info(f"planId: {working_dir}")
    crd_api.patch_namespaced_custom_object(
        group=selfLink[2],
        version=selfLink[3],
        name=selfLink[7],
        namespace=selfLink[5],
        plural=selfLink[6],
        body={"spec": {
            "planId": working_dir
        }})

    tf_response, tf_code = terraform(working_dir=working_dir,
                                     data=data,
                                     logger=logger)
    logger.info(f"Terraform Plan result: {tf_response}")

    if recipients:
        logger.info(f"Send email to {recipients}")
        send_email(to=recipients,
                   attachment=tf_response,
                   message_type='success' if tf_code != 1 else 'error')
    else:
        logger.info('No recipients defined')
    logger.info(f"PlanId is {working_dir}")
    return f"{working_dir}"