Пример #1
0
def get_letters():

    # Test email with attachment
    URL = 'http://lavr.github.io/python-emails/tests/campaignmonitor-samples/sample-template/images/gallery.png'
    data = common_email_data(subject='Single attachment',
                             attachments=[
                                 emails.store.LazyHTTPFile(uri=URL),
                             ])
    yield emails.html(**data), None

    # Email with render
    yield emails.html(**common_email_data(subject='Render with name=John')), {
        'name': u'John'
    }

    # Email with several inline images
    url = 'http://lavr.github.io/python-emails/tests/campaignmonitor-samples/sample-template/template-widgets.html'
    data = common_email_data(subject='Sample html with inline images')
    del data['html']
    yield emails.loader.from_url(url=url,
                                 message_params=data,
                                 images_inline=True), None

    # Email with utf-8 "to"
    yield emails.Message(
        **common_email_data(mail_to="anaï[email protected]", subject="UTF-8 To")), None
Пример #2
0
def make_email(html, from_, subject="", attachments=None):
    """Helper function to make emails

    html (str): content
    from_ (str): address to send the email from
    subject (str): subject of email
    attachments (list) : attachments to send
    """
    message = emails.html(charset="utf-8",
                          subject=subject,
                          html=html,
                          mail_from=from_)
    soup = BeautifulSoup(html, "html.parser")

    # strip markdown links
    for item in soup.findAll("a", {"class": "anchor-link"}):
        item.decompose()

    # strip matplotlib base outs
    for item in soup.find_all(
            "div", class_="output_text output_subarea output_execute_result"):
        for c in item.contents:
            if "<matplotlib" in str(c):
                item.decompose()

    # remove dataframe table borders
    for item in soup.findAll("table", {"border": 1}):
        item["border"] = 0
        item["cellspacing"] = 0
        item["cellpadding"] = 0

    # extract imgs for outlook
    imgs = soup.find_all("img")
    imgs_to_attach = {}

    # attach main part
    for i, img in enumerate(imgs):
        if not img.get("localdata"):
            continue
        imgs_to_attach[img.get("cell_id") + "_" + str(i) +
                       ".png"] = base64.b64decode(img.get("localdata"))
        img["src"] = "cid:" + img.get("cell_id") + "_" + str(i) + ".png"
        # encoders.encode_base64(part)
        del img["localdata"]

    # assemble email soup
    soup = str(soup)
    message = emails.html(charset="utf-8",
                          subject=subject,
                          html=soup,
                          mail_from=from_)

    for img, data in imgs_to_attach.items():
        message.attach(filename=img, content_disposition="inline", data=data)

    return message
Пример #3
0
def get_letters():

    # Test email with attachment
    URL = 'http://lavr.github.io/python-emails/tests/campaignmonitor-samples/sample-template/images/gallery.png'
    data = common_email_data(subject='Single attachment', attachments=[emails.store.LazyHTTPFile(uri=URL), ])
    yield emails.html(**data), None

    # Email with render
    yield emails.html(**common_email_data(subject='Render with name=John')), {'name': u'John'}

    # Email with several inline images
    url = 'http://lavr.github.io/python-emails/tests/campaignmonitor-samples/sample-template/template-widgets.html'
    data = common_email_data(subject='Sample html with inline images')
    del data['html']
    yield emails.loader.from_url(url=url, message_params=data, images_inline=True), None
Пример #4
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
Пример #5
0
def test_exceptions():

    # IOError: [Errno 8] nodename nor servname provided, or not known
    server_params = { 'host': 'invalid-server.invalid-domain.xxx', 'port': 25 }
    sendmail_params = {'to_addrs': '*****@*****.**', 'from_addr': '*****@*****.**', 'msg': '...'}
    server = SMTPSender(**server_params)
    response = server.sendmail(**sendmail_params)
    assert response.status_code is None
    assert response.error is not None
    assert isinstance(response.error, IOError)
    print("response.error.errno=", response.error.errno)
    if HAS_INTERNET_CONNECTION:
        assert response.error.errno==8


    # Server disconnected
    message_params = {'html':'<p>Test from python-emails',
                      'mail_from': '*****@*****.**',
                      'mail_to': '*****@*****.**',
                      'subject': 'Test from python-emails'}
    server_params = { 'host': 'alt1.aspmx.l.google.com', 'port': 25, 'debug':1 }
    sendmail_params = {'to_addrs': '*****@*****.**',
                       'from_addr': '*****@*****.**',
                       'msg': emails.html(**message_params).as_string()}

    if HAS_INTERNET_CONNECTION:
        server = SMTPSender(**server_params)
        server._connect()
        server.smtpclient.sock.close()  # simulate disconnect
        response = server.sendmail(**sendmail_params)
        print(response)
    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]}
Пример #7
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]}
Пример #8
0
 def notify(self, ticket, attachment=None):
     subject = "%s - Wagon %s, miejsce %s (%s), %s" % (
         ticket.date.strftime("%H:%M"),
         ticket.carriage,
         ticket.seat,
         ticket.location,
         ticket.carriage_type,
     )
     message = emails.html(
         html="%s, %s - %s" % (ticket.date.strftime("%A, %d %b"), ticket.route_from, ticket.route_to),
         subject=subject,
         mail_from=("Tickets", self.config["EMAIL_HOST_USER"]),
     )
     if attachment:
         filename = os.path.basename(attachment.name)
         message.attach(data=attachment, filename=filename)
     message.send(
         to=self.receiver,
         smtp={
             "host": self.config["EMAIL_HOST"],
             "port": self.config["EMAIL_PORT"],
             "ssl": self.config["EMAIL_USE_TLS"],
             "user": self.config["EMAIL_HOST_USER"],
             "password": self.config["EMAIL_HOST_PASSWORD"],
         },
     )
Пример #9
0
def email_sender(sender_email: str, receiver_name: str, admin: dict):
    """
    Notify sender who's his/her receiver

    Args:
        sender_email: email address of the sender
        receiver_name: receiver's name
        admin: email settings of the administrator

    Returns:
        email response - status_code == 250 if sent successfully
    """
    subject = (admin.pop('subject', 'Your Destiny is ...').replace(
        '[receiver]', receiver_name))

    body = (admin.pop('body', '').replace('[receiver]', receiver_name))
    if (receiver_name not in body) and (receiver_name not in subject):
        body += f'<br/>{receiver_name}'

    name = admin.pop('name', 'Your Host')
    email = admin.get('user')

    return (emails.html(
        html=body,
        subject=subject,
        mail_from=(name, email),
    ).send(
        to=sender_email,
        smtp=admin,
    ))
Пример #10
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"])
Пример #11
0
    def email_results(self) -> None:
        subject = f'{self.__class__.__name__} - {self.cluster}'
        message = 'Alert(s) found:\n\n\t'
        for alert in self.failed_alerts:
            message += alert['message']
            if alert.get('remediated') is True:
                message += ' - Successfully remediated'
            elif alert.get('remediated') is False:
                message += ' - Failed remediation'
            message += '\n\t'
        msg = emails.html(subject=subject,
                          text=message,
                          mail_from='*****@*****.**',
                          mail_to='*****@*****.**')
        resp = msg.send(
            smtp={
                'host': environ.get('SMTP_HOST', 'localhost'),
                'port': environ.get('SMTP_PORT', '25'),
                'tls': environ.get('SMTP_USE_TLS', 'true') == 'true',
                'user': environ.get('SMTP_USER'),
                'password': environ.get('SMTP_PASS'),
            })

        if resp.status_code not in [250, 251, 252]:
            self.log.error(
                f'{"="*80}\n\tUnable to send email alert {subject} (ERR: {resp.error}):\n\n\t{message}\n\t{"="*80}'
            )
Пример #12
0
def test_render_message_with_template():
    TEMPLATE = JinjaTemplate('Hello, {{name}}!')
    V = dict(name='world')
    RESULT = TEMPLATE.render(**V)
    assert RESULT == 'Hello, world!'

    msg = emails.html(subject=TEMPLATE)
    msg.render(**V)
    assert msg.subject == RESULT

    msg = emails.html(html=TEMPLATE)
    msg.render(**V)
    assert msg.html_body == RESULT

    msg = emails.html(text=TEMPLATE)
    msg.render(**V)
    assert msg.text_body == RESULT
Пример #13
0
def _build_message() -> Message:
    with _EMAIL_TEMPLATE.open("r") as _:
        template = _.read()
    return emails.html(
        subject=params.email.subject,
        mail_from=str(params.email.sender),
        html=JinjaTemplate(template),
    )
Пример #14
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)
Пример #15
0
 def _send_single(self, name, email):
     message = emails.html(html=T(self.message), subject=self.email['subject'], mail_from=(self.email['mail_from'], self.email['mail_from_email']))
     if self.email['hasevent']:
         message.attach(data=open(self.email['calendarevent'], 'rb'), filename='Event.ics')
     response = message.send(to = (name, email), render = {'firstname': name}, smtp = self.smtp)
     if response.status_code not in [250, ]:
         print "Failed to send to: {} Error code {}".format(email, response.status_code)
     else:
         print "Email successfully sent to {} at {}".format(name, email)
def test_send_to_unknown_host():
    server = SMTPBackend(host='invalid-server.invalid-domain-42.com', port=2525)
    response = server.sendmail(to_addrs='*****@*****.**', from_addr='*****@*****.**', msg=emails.html(**SAMPLE_MESSAGE))
    server.close()
    assert response.status_code is None
    assert isinstance(response.error, IOError)
    assert not response.success
    print("response.error.errno=", response.error.errno)
    if not TRAVIS_CI:
        # IOError: [Errno 8] nodename nor servname provided, or not known
        assert response.error.errno == 8
Пример #17
0
def test_send_with_context_manager(smtp_servers):
    for _, server in smtp_servers.items():
        b = SMTPBackend(**server.params)
        with b as backend:
            for n in range(2):
                data = common_email_data(subject='context manager {0}'.format(n))
                message = emails.html(**data)
                message = server.patch_message(message)
                response = message.send(smtp=backend)
                assert response.success or response.status_code in (421, 451), 'error sending to {0}'.format(server.params)  # gmail not always like test emails
        assert b._client is None
Пример #18
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)
Пример #19
0
def test_send1():
    URL = 'http://icdn.lenta.ru/images/2013/08/07/14/20130807143836932/top7_597745dde10ef36605a1239b0771ff62.jpg'
    data = _email_data()
    data['attachments'] = [emails.store.LazyHTTPFile(uri=URL), ]
    m = emails.html(**data)
    m.render(name='Полина')
    print("m.subject=", m.subject)
    assert m.subject=='Hello, Полина'
    print(m.as_string())

    if HAS_INTERNET_CONNECTION:
        r = m.send(smtp=SMTP_DATA)
Пример #20
0
def email():
    m = emails.html(text='5781458',
                    subject='测试邮件',
                    mail_from=('Andy', '*****@*****.**'))

    r = yield m.send(to=('qq', '*****@*****.**'),
                     smtp={
                         'host': 'smtp.163.com',
                         'user': '******',
                         'password': '******'
                     })
    raise tornado.gen.Return(r.status_code)
Пример #21
0
def test_send_to_unknown_host():
    server = SMTPBackend(host='invalid-server.invalid-domain-42.com',
                         port=2525)
    response = server.sendmail(to_addrs='*****@*****.**',
                               from_addr='*****@*****.**',
                               msg=emails.html(**SAMPLE_MESSAGE))
    server.close()
    assert response.status_code is None
    assert isinstance(response.error, IOError)
    assert not response.success
    # IOError: [Errno 8] nodename nor servname provided, or not known
    assert response.error.errno == socket.EAI_NONAME
Пример #22
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
Пример #23
0
 def prepare_email(self, cfg):
     """
     Generic prepare message
     Returns:
         email message
     """
     if hasattr(cfg, 'manifest'):
         body = self._prepare_email_successs(cfg.manifest)
     else:
         body = self._prepare_email_fail()
     return emails.html(html=body,
                        subject=SUBJECT,
                        mail_from=self.send_from)
    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
def test_django_message_proxy(django_email_backend):

    """
    Send message via django email backend.
    `django_email_backend` defined in conftest.py
    """

    message_params = {'html': '<p>Test from python-emails',
                      'mail_from': '*****@*****.**',
                      'mail_to': '*****@*****.**',
                      'subject': 'Test from python-emails'}
    msg = emails.html(**message_params)
    django_email_backend.send_messages([emails.message.DjangoMessageProxy(msg), ])
Пример #26
0
def test_dkim():
    data = {}
    message = emails.html(html='<p>This is the end, beautiful friend<br>'\
                               'This is the end, my only friend',
                          subject='Hello, world!',
                          mail_from=('Jim', '*****@*****.**'),
                          mail_to=('Anyone <*****@*****.**>'))

    message.attach( data=StringIO('x'*1024), filename='Data.dat' )

    message.dkim( privkey=_generate_privkey(), selector='_dkim', domain='somewhere.net'   )

    return message.as_string()
Пример #27
0
def sendmail(email,name):
    html_text ='''<p><span style="color: rgb(243, 121, 52); background-color: rgb(0, 0, 0);">Hey Rowdy,'''+name+'''</span></p>
                  <p>I&apos;m Your Name&nbsp;</p>
                  <p>I like to study with lets Upgrade</p>
                  <p>There is 3 courses I&apos;m completed with lets Upgrade</p>
                  <p><strong>Regards ,</strong></p>
                  <p><strong>Your Name</strong></p>'''
    subject ="Hey Reciever"+ name+"You have EMAIL FROM Your Name"
    message = emails.html(html=html_text,
                              subject=subject ,
                              mail_from=('Your Name', '*****@*****.**'))
    mail_via_python = message.send(to=email, smtp={'host': 'smtp.gmail.com', 'timeout': 5, 'port' : 587,
                                                   'user':'******','password':'******','tls' : True})
    return mail_via_python.status_code
Пример #28
0
def test_send_with_context_manager():
    for _, server in get_servers():
        b = SMTPBackend(**server.params)
        with b as backend:
            for n in range(2):
                data = common_email_data(
                    subject='context manager {0}'.format(n))
                message = emails.html(**data)
                message = server.patch_message(message)
                response = message.send(smtp=backend)
                assert response.success or response.status_code in (
                    421, 451), 'error sending to {0}'.format(
                        server.params)  # gmail not always like test emails
        assert b._client is None
Пример #29
0
def test_send2():
    data = _email_data()
    loader = emails.loader.HTTPLoader(filestore=emails.store.MemoryFileStore())
    #loader = HTTPLoader(  )
    URL = 'http://lavr.github.io/python-emails/tests/campaignmonitor-samples/sample-template/template-widgets.html'
    loader.load_url(URL, css_inline=True, make_links_absolute=True, update_stylesheet=True)
    data['html'] = loader.html
    data['attachments'] = loader.attachments_dict
    loader.save_to_file('test_send2.html')
    m = emails.html(**data)
    m.render(name='Полина')

    if HAS_INTERNET_CONNECTION:
        r = m.send( smtp=SMTP_DATA )
        r = m.send( to='*****@*****.**', smtp=SMTP_DATA )
Пример #30
0
def test_smtp_send_with_reconnect(smtp_servers):
    """
    Check SMTPBackend.sendmail reconnect
    """
    for tag, server in smtp_servers.items():
        print("-- test_smtp_reconnect: %s" % server)
        params = server.params
        params['fail_silently'] = True
        message = server.patch_message(
            emails.html(subject='reconnect test', **SAMPLE_MESSAGE))
        backend = message.smtp_pool[params]
        backend.get_client().sock.close()  # simulate disconnect
        response = message.send(smtp=params)
        assert response.success or response.status_code in (
            421, 451)  # gmail don't like test emails
        server.sleep()
Пример #31
0
def send_email(text):
    message = emails.html(html=text,
                          subject='Julian Timehop',
                          mail_from=('Julian Timehop Emailer',
                                     '*****@*****.**'))

    password = os.environ.get('SMTP_PASSWORD')

    r = message.send(to=('R Wilson', '*****@*****.**'),
                     smtp={
                         'host': 'mail.rtwilson.com',
                         'port': 465,
                         'ssl': True,
                         'user': '******',
                         'password': password
                     })
Пример #32
0
def test_django_message_proxy(django_email_backend):
    """
    Send message via django email backend.
    `django_email_backend` defined in conftest.py
    """

    message_params = {
        'html': '<p>Test from python-emails',
        'mail_from': '*****@*****.**',
        'mail_to': '*****@*****.**',
        'subject': 'Test from python-emails'
    }
    msg = emails.html(**message_params)
    django_email_backend.send_messages([
        emails.message.DjangoMessageProxy(msg),
    ])
def test_smtp_send_with_reconnect(smtp_servers):
    """
    Check SMTPBackend.sendmail reconnect
    """
    for tag, server in smtp_servers.items():
        print("-- test_smtp_reconnect: %s" % server)
        params = server.params
        params['fail_silently'] = True
        message = server.patch_message(emails.html(subject='reconnect test', **SAMPLE_MESSAGE))
        message.mail_from = server.from_email
        message.mail_to = server.to_email
        backend = message.smtp_pool[params]
        backend.get_client().sock.close()  # simulate disconnect
        response = message.send(smtp=params)
        assert response.success or response.status_code in (421, 451)  # gmail don't like test emails
        server.sleep()
Пример #34
0
def main():
    message = emails.html(html=open(os.path.join('data', 'level.html')),
                          subject='Friday party',
                          mail_from=('Company Team', '*****@*****.**'))
    message.attach(data=open(os.path.join('data', 'pug.jpg'), 'rb'), filename='pug.jpg',
                   content_disposition='inline')

    r = message.send(to=('John Brown', '*****@*****.**'),
                     # render={'name': 'James Brown'},
                     smtp={'host': 'smtp.gmail.com',
                           'port': 465,
                           'ssl': True,
                           'user': '******',
                           'password': '******'})

    if r.status_code not in [250, ]:
        print('Baj van')
Пример #35
0
def send_report(config):
    log = logging.getLogger(__name__)
    email_to = map(str.strip, config.get('email.to').split(','))
    email_from_email = config.get('email.from_email')
    email_from_name = config.get('email.from_name')
    host = config.get('smtp.host')
    port = config.get('smtp.port')
    ssl = bool(config.getint('smtp.use_ssl'))
    tls = bool(config.getint('smtp.use_tls'))
    user = config.get('smtp.user')
    password = config.get('smtp.password')

    day = date.today()
    if config.get('email.day') == 'yesterday':
        day -= timedelta(days=1)
    elif config.get('email.day') != 'today':
        raise ConfigReadError(
            'email.day should be only "today" or "yesterday" ')
    storage = NettestStorage(config, read_only=True)
    data = storage.get_entries_for_date(day)
    keys = storage.keys()
    
    message = emails.html(
        html = make_html_report(keys, data),
        mail_from=(email_from_name, email_from_email),
        subject="Nettest report for %s" % day)

    message.attach(
        data=make_csv_report(keys, data),
        filename='nettest_report-%s.csv' % day.strftime('%Y-%m-%d'))
    
    for address in email_to:
        response = message.send(
            to=(address, address),
            smtp={
                'host': host,
                'port': port,
                'ssl': ssl,
                'tls': tls,
                'user': user,
                'password': password})

        if response.status_code != 250:
            log.error(
                'Cannot send email to %s. Response: %s',
                address, response)
Пример #36
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)
Пример #37
0
def register_page(request):
    """Register a new user and send them a confirmation email with password."""
    form = CreateUserForm()

    if request.method == "POST":
        form = CreateUserForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)

            user_email = form.cleaned_data.get("email")
            user_email = str(user_email)

            saved_password = form.cleaned_data.get("password1")
            saved_password = str(saved_password)

            user.save()
            #Prepare email
            message = emails.html(
                html=
                f"<h4>Contraseña: <strong>{saved_password}</strong></p></h4>",
                subject="Enviado desde Challenge App",
                mail_from=config("EMAIL_HOST_USER"))
            try:
                # Send the email
                r = message.send(
                    to=user_email,
                    smtp={
                        "host": config("EMAIL_HOST"),
                        "port": 587,
                        "timeout": 5,
                        "user": config("EMAIL_HOST_USER"),
                        "password": config("EMAIL_HOST_PASSWORD"),
                        "tls": True,
                    },
                )
            except BadHeaderError:
                return HttpResponse(f"response: {r.status_code == 250}")

            return redirect("accounts:login-page")

    context = {"title": "Página de Registro", "form": form}

    return render(request, "accounts/register.html", context)
Пример #38
0
def send_report(config):
    log = logging.getLogger(__name__)
    email_to = map(str.strip, config.get('email.to').split(','))
    email_from_email = config.get('email.from_email')
    email_from_name = config.get('email.from_name')
    host = config.get('smtp.host')
    port = config.get('smtp.port')
    ssl = bool(config.getint('smtp.use_ssl'))
    tls = bool(config.getint('smtp.use_tls'))
    user = config.get('smtp.user')
    password = config.get('smtp.password')

    day = date.today()
    if config.get('email.day') == 'yesterday':
        day -= timedelta(days=1)
    elif config.get('email.day') != 'today':
        raise ConfigReadError(
            'email.day should be only "today" or "yesterday" ')
    storage = NettestStorage(config, read_only=True)
    data = storage.get_entries_for_date(day)
    keys = storage.keys()

    message = emails.html(html=make_html_report(keys, data),
                          mail_from=(email_from_name, email_from_email),
                          subject="Nettest report for %s" % day)

    message.attach(data=make_csv_report(keys, data),
                   filename='nettest_report-%s.csv' % day.strftime('%Y-%m-%d'))

    for address in email_to:
        response = message.send(to=(address, address),
                                smtp={
                                    'host': host,
                                    'port': port,
                                    'ssl': ssl,
                                    'tls': tls,
                                    'user': user,
                                    'password': password
                                })

        if response.status_code != 250:
            log.error('Cannot send email to %s. Response: %s', address,
                      response)
Пример #39
0
    def send_email(self, this, email, subject, content):
        # 忽略掉发邮件的部分
        pass
        # from collipa.libs.tornadomail.message import EmailMessage
        # message = EmailMessage(subject, content, config.smtp_user,
        #                        [email], connection=self.mail_connection)
        # message.send()
        import emails
        message = emails.html(html=content,
                              subject=subject,
                              mail_from=("Collipa", config.smtp_user))

        response = message.send(to=email,
                                smtp={
                                    "host": config.smtp_host,
                                    "port": config.smtp_port,
                                    "ssl": config.smtp_ssl,
                                    "user": config.smtp_user,
                                    "password": config.smtp_pass,
                                })
Пример #40
0
def send_email(email_from, email_to, title, content, host, port, user,
               password):
    message = emails.html(
        html=content,
        subject=title,
        mail_from=email_from,
    )

    resp = message.send(
        to=email_to,
        smtp={
            "host": host,
            "port": port,
            "timeout": TIMEOUT,
            "user": user,
            "password": password,
            "tls": True,
        },
    )
    return resp
Пример #41
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)
Пример #42
0
def test_dkim_error():

    m = emails.html(**common_email_data())

    # No key
    with pytest.raises(TypeError):
        m.dkim(selector='_dkim',
               domain='somewhere.net',
               ignore_sign_errors=False)


    # Error in invalid key
    invalid_key = 'X'
    with pytest.raises(DKIMException):
        m.dkim(key=invalid_key,
               selector='_dkim',
               domain='somewhere.net',
               ignore_sign_errors=False)

    # Error on invalid dkim parameters

    m.dkim(key=PRIV_KEY,
           selector='_dkim',
           domain='somewhere.net',
           include_headers=['To'])

    with pytest.raises(DKIMException):
        # include_heades must contain 'From'
        m.as_string()

    # Skip error on ignore_sign_errors=True
    m.dkim(key=PRIV_KEY,
           selector='_dkim',
           domain='somewhere.net',
           ignore_sign_errors=True,
           include_headers=['To'])

    m.as_string()
    m.as_message()
Пример #43
0
def sendMail(driver, subject, content, shouldAddDebugScreenshot, options={}):
    #destruct options
    FROM = withDefault(options, 'mail_from', '*****@*****.**')
    TO = withDefault(options, 'mail_receiver', '')
    SUBJECT = subject
    CONTENT = content
    USERNAME = withDefault(options, 'mail_username', '')
    PASSWORD = withDefault(options, 'mail_password', '')

    # create html email
    html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" '
    html += '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">'
    html += '<body style="font-size:12px;font-family:Verdana"><p>'
    html += str(CONTENT)
    html += '</p>'
    html += "</body></html>"
    message = emails.html(html=html,
                          subject=SUBJECT,
                          mail_from=('Bot notifications', FROM))

    if shouldAddDebugScreenshot:
        screenshotName = buildScreenshotWithTimestamp(driver,
                                                      {'name': 'debugging'})
        message.attach(data=open(screenshotName, 'rb'),
                       filename=screenshotName)

    try:
        response = message.send(to=('Jup someone', TO),
                                smtp={
                                    'host': 'smtp.gmail.com',
                                    'port': 465,
                                    'ssl': True,
                                    'user': USERNAME,
                                    'password': PASSWORD
                                })
        print(response)
    except Exception as error:
        print(error)
        print("failed to send mail")
Пример #44
0
def test_send_inline_images():
    data = _email_data()
    loader = emails.loader.HTTPLoader(filestore=emails.store.MemoryFileStore())
    URL = 'http://lavr.github.io/python-emails/tests/campaignmonitor-samples/sample-template/template-widgets.html'
    loader.load_url(URL, css_inline=True, make_links_absolute=True, update_stylesheet=True)
    for img in loader.iter_image_links():
        link = img.link
        file = loader.filestore.by_uri(link, img.link_history)
        img.link = "cid:%s" % file.filename
    for file in loader.filestore:
        file.content_disposition = 'inline'
    data['html'] = loader.html
    data['attachments'] = loader.attachments_dict
    #loader.save_to_file('test_send_inline_images.html')
    #print loader.html
    m = emails.html(**data)
    m.render(name='Полина')


    if HAS_INTERNET_CONNECTION:
        r = m.send( smtp=SMTP_DATA )
        if r.status_code != 250:
            logging.error("Error sending email, response=%s" % r)
Пример #45
0
def send_email(subject, template, render, to):
    # Grab template
    with open(template) as t: html = t.read()

    message = emails.html(
        subject=subject,
        html=T(html),
        mail_from=('RapidDev', '*****@*****.**')
    )

    response = message.send(
        to=to,
        render=render,
        smtp={
            'host': STMP['host'],
            'ssl': STMP['ssl'],
            'port': STMP['port'],
            'user': STMP['user'],
            'password': STMP['pass']
        }
    )

    return response.status_code
Пример #46
0
import time 
from time import sleep, strftime, gmtime, localtime
import picamera 
import emails
from usernamedetails import Und
import os

FPS_IN = 10
FPS_OUT = 24

details = Und()

message = emails.html(html="<p>Hi!<br>Here is your image...",
                       subject="Image",
                       mail_from=('Ian', details.email))

counter = 0

with picamera.PiCamera() as camera:
    camera.start_preview()
    sleep(2)
    for thefilename in camera.capture_continuous('img{counter:03d}.jpg'):
        print(strftime("%H",localtime()))
        print('Captured %s' % thefilename)
        # message.attach(data=open(thefilename), filename=thefilename)
	counter += 1
        if counter > 3:
            #r = message.send(to=details.email, smtp={"host": "smtp.gmail.com", "port": 465, "ssl": True, "user": details.user, "password": details.password, "timeout": 5})
            #assert r.status_code == 250
            break   
        sleep(30) 
Пример #47
0
    def UserProgramableTest1Process(self, rec):
        global measure
        global tm
        global fr
        global to
        global name
        global worksheet
        global workbook
        global forced
        global range
        global format
        global graph
        global rate
        global wanted_temp
        global inp
        global outp
        global slot
        global zip_name
        global mail_to
        root.option_add("*background", "orange")
        root.configure(background="orange")
        z_name = zip_name.get().rstrip()
        process = open('process_que.txt', 'r')
        processNumber = 0
        if z_name != '':
            z = zipfile.ZipFile("Output_Files/" + z_name + '.zip', 'w')
            z.close()
            z = zipfile.ZipFile("Output_Files/" + z_name + '.zip', 'a')
        while processNumber < count:
            self.destroy()
            Frame.__init__(self)
            self.grid()
            measure = process.readline()
            forced = process.readline()
            range = process.readline()
            tm = process.readline()
            fr = process.readline()
            to = process.readline()
            name = process.readline()
            graph = process.readline()
            rate = process.readline()
            wanted_temp = process.readline()
            outp = process.readline()
            inp = process.readline()
            slot = process.readline()
            processNumber += 1
            print (name.rstrip() != '')
            if name.rstrip() != '':
                if z_name != "":
                    workbook = xlsxwriter.Workbook(str(name).rstrip() + '.xlsx')
                else:
                    workbook = xlsxwriter.Workbook("Output_Files/" + str(name).rstrip() + '.xlsx')
                format = workbook.add_format()
                format.set_text_wrap()
                worksheet = workbook.add_worksheet()
            Label(self, text='Currently Running: ' + measure).grid()
            Label(self, text=str((count - processNumber)) + ' More process(s) to go').grid()
            self.AutoMeasure()
            workbook.close()

            if z_name != '':
                z.write(str(name).rstrip() + '.xlsx')
                os.remove(str(name).rstrip() + '.xlsx')

        if mail_to.get() != '':
            if z_name != '':
                z.close()
                time_completed = str(datetime.datetime.now())[11:-10]
                date_completed = str(datetime.datetime.now())[:-16]
                contact = open("Email_Settings/" + mail_to.get() + ".txt", 'r')[18:]
                email_address = contact.readline().rstrip()
                contact_name = contact.readline().rstrip()
                contact.close()
                message = emails.html(
                    html="<p> Greetings: " + contact_name + ",</p>" + "<p>Here are your measurement results, they were completed on " + date_completed + " at " + time_completed + ".</p> <p> War Eagle! </p>",
                    subject=z_name + " Results",
                                      mail_from=("Auburn Cryo Measurement System", "*****@*****.**"))
                message.attach(data=open("Output_Files/" + z_name + ".zip", 'rb'), filename=z_name + ".zip")
                r = message.send(to=(mail_to.get().rstrip(), email_address), render={"name": "Auburn Cryo"},
                                 smtp={"host": "smtp.gmail.com", "port": 465, "ssl": True,
                                       "user": "******", "password": "******", "timeout": 5})
                assert r.status_code == 250
        winsound.PlaySound('Sounds/beep-01.wav', winsound.SND_FILENAME)
        self.AutomationMenu()
Пример #48
0
                        folder = data['folder']
                        timeformat = "%Y-%m-%d_%H:%M:%S"
                        filename = "%s.wav" % datetime.datetime.today().strftime(timeformat)
                        with open(new_cut.get_path(), 'rb') as fh:
                            requests.put('%s/%s/%s' % (baseURL, folder, filename),
                                         auth=auth, data=fh.read())
                        download = "%s/download?path=%%2F&files=%s" % (data['share_link'],
                                                                       filename)
                        notification_data['owncloud']['download_url'] = download
                if "email" in recorded_carts[cart_str]:
                    from_address = config['email']['from']
                    if type(from_address) == list:
                        from_address = tuple(from_address)
                    to_address = recorded_carts[cart_str]['email']
                    template = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                            "email.html")
                    if "template" in config['email']:
                        template = config['email']['template']
                    if type(to_address) == list:
                        to_address = tuple(to_address)
                    smtp = None
                    if "smtp" in config['email']:
                        smtp = config['email']['smtp']
                    message = emails.html(subject=JinjaTemplate(config['email']['subject']),
                                          html=JinjaTemplate(open(template).read()),
                                          mail_from=from_address)
                    message.send(to=to_address, render=notification_data)
            # TODO: Other processing (e.g. converting to MP3, etc)
    except Exception:
        sentry.captureException()