Example #1
0
def split_emails(text, fileids):
    emails = []
    reg_header = r'<.*?@.*?>\nType'
    headers = re.findall(reg_header, text)
    ind = 0

    for i in range(0, len(headers) - 1):
        start_h = text.find(headers[i])
        end_h = text.find('Abstract')
        header = text[start_h:end_h]

        start_b = end_h
        end_b = text.find(headers[i + 1])
        body = text[start_b:end_b]

        emails.append(Email(header.strip(), body.strip(), fileids[ind]))

        text = text[end_b:]
        ind += 1

    end_h = text.find('Abstract')
    header = text[:end_h]
    body = text[end_h:]
    emails.append(Email(header, body, fileids[ind]))

    return emails
 def SendSnapshot(self, send_option):
     """Send snapshot /tmp/snapshot.jpg 
     send options are:
         1   ...	Telegram bot
         2   ...	Email"""
     if send_option == 1:
         try:
             bot = MyTelegramBot()
             response = bot.send_photo(
                 "%s/data/plugins/synology/snapshot.jpg" %
                 self.installfolder)
             if response == True:
                 logging.info("<INFO> Photo sent to Telegram!")
                 return True
             else:
                 logging.info("<ERROR> Photo NOT sent to Telegram!")
                 return False
         except:
             return False
     elif send_option == 2:
         try:
             m = Email()
             m.SendAttachment(
                 "Snapshot", "Greetings from your Loxberry",
                 "%s/data/plugins/synology/snapshot.jpg" %
                 self.installfolder)
         except:
             logging.info("<INFO> sending email not implemented yet")
             return False
     else:
         logging.info("<ERROR> no valid send option!")
         return False
Example #3
0
    def run(self):
        """Run device and agent checks"""

        # Main loop
        devices = self.api.get_devices()
        for device in devices:

            # Begin
            device = Device(device, self.results)
            logger.debug('---- Device: %s ----', device.name)

            # Device checks
            if device.is_inactive():
                logger.debug('    Device is archived or paused')
                continue
            device.run_device_checks()
            if device.is_offline:
                logger.debug(
                    '    Device is offline; skipping remaining checks')
                continue

            # Agent checks
            asset_details = self.api.get_asset_details(device.serial_number)
            for agent in asset_details:
                agent = Agent(self.api, agent, device, self.results,
                              self.include_unprotected)
                logger.debug('    ---- Agent: %s ----', agent.name)
                if agent.is_inactive():
                    logger.debug(' ' * 8 + 'Agent is archived or paused')
                    continue
                agent.run_agent_checks()
        self.api.session_close()
        logger.info('All checks complete')

        # Main loop done; send report
        if config.EMAIL_TO:
            mailer = Email()

            d = datetime.today()
            subject = 'Daily Datto Check: {}'.format(d.strftime('%m/%d/%Y'))

            report = mailer.build_html_report(self.results.results)
            mailer.send_email(config.EMAIL_TO, config.EMAIL_FROM, subject,
                              report, config.EMAIL_CC)
def tag_time(email):
  header = email.header
  body = email.body

  reg_time = r'\[0-9]+:[0-9][0-9]|[0-9]+:[0-9][0-9] +[APap]\.?[mM]'
  reg_line = r'Time.*\n'

  # Tag header

  times = []
  times_tag = []

  try:
    # Get line which contains time info
    line = re.findall(reg_line, header)[0]
    times = re.findall(reg_time, line)

    if len(times) == 1:
      times_tag.append('<stime>' + times[0] + '</stime>')
    else:
      times_tag.append('<stime>' + times[0] + '</stime>')
      times_tag.append('<etime>' + times[1] + '</etime>')

    for i in range(0, len(times)):
      line = re.sub(times[i], times_tag[i], line)

    header = re.sub(reg_line, line, header)
  except:
    pass

  # Tag times in body

  if len(times) > 0:
    # Strip times from header to contain only digits
    for i in range(0, len(times)):
      times[i] = re.findall(r'[0-9]+:[0-9][0-9]', times[i])[0]

    # Get all times from body
    times_b = re.findall(reg_time, body)
    times_b_tag = list(times_b)

    # Tag the times from body based on header time tags
    for i in range(0, len(times_b)):
      if times[0] in times_b[i]:
        times_b_tag[i] = '<stime>' + times_b[i] + '</stime>'

    if len(times) > 1:
      for i in range(0, len(times_b)):
        if times[1] in times_b[i]:
          times_b_tag[i] = '<etime>' + times_b[i] + '</etime>'

    # Put tagged times in body
    for i in range(0, len(times_b)):
      body = re.sub(times_b[i], times_b_tag[i], body)

  return Email(header, body, email.fileid)
Example #5
0
 def add(cls, title, description, email, image_url, visible):
     content_tag = tags.analyze_entities(title)
     p = Poll(title=title,
              description=description,
              email=email,
              image_url=image_url,
              delete_key=str(uuid.uuid4()),
              tag=content_tag,
              visible=visible)
     p.put()  # Add to datastore
     # don't check hidden polls
     if visible:
         # add a job to a task queue that will check the poll for bad language
         taskqueue.add(queue_name='filter-queue',
                       url='/admin/worker/checkpoll',
                       params={'poll': p.get_id()})
     if email:
         Email.send_mail(email, p.get_id(), p.delete_key, title, image_url)
     events.poll_created_event(p)
     return p
Example #6
0
def main():
    sensor = 16 #PIR sensor set at GPIO pin 16
    sensorState = 0 #sensorState refers to signal sent from 
    videoDevice = 0 #0 is the default videoDevice
    fps = 30 #fps of video device

    print("preparing sensor")

    #setup Pi's GPIO
    GPIO.setmode(GPIO.BOARD) #sets up GPIO's pin numbering to BOARD
    GPIO.setup(sensor, GPIO.IN) #inits pin of sensor as input

    print("preparing webcam")

    cam = Webcam(videoDevice, fps)

    print("preparing email")

    #setup email, see "mail.py" for more information
    myEmail = Email("myemail", "mypassword") #return an email object
    myEmail.initSMTP("smtp.gmail.com", 587) #connect to gmail's SMTP on port 587
    subject = "Intruder Alert"
    recipient = "recipient@email"

    #image file path for webcam screen capture
    imgPath = "images/intruder.jpg"

    print("listening to sensor...")

    try:
        while True:
            time.sleep(2)
            sensorState = GPIO.input(sensor)
            print(sensorState)
            if sensorState == GPIO.HIGH: #check if sensor sends a signal
                date = time.strftime("Date: %x Time(24Hour): %X")
                print("taking pic")
                cam.takePicture(imgPath)
                print("sending email")
                myEmail.sendEmail(recipient, subject, date, imgPath)
                print("sent")
                time.sleep(60) 

    except KeyboardInterrupt:
        pass
    finally:
        print("exiting...")
        GPIO.cleanup() #exit GPIO cleanly
        cam.closeWebcam()
        myEmail.closeSMTP() #close connection to SMTP server
Example #7
0
 def listen(self) -> NoReturn:
     """Continuously loop while checking for due plans and unread email."""
     while True:
         # Check Plans
         plans = self.db.read()
         for plan in plans:
             if plan.due_date <= arrow.utcnow():
                 self.db.write(filter(lambda p: plan != p, plans))
                 Notification.toast('Butler', f'{plan.name} is due.')
         
         # Check Messages
         for mail in Email.get(self.username, self.password):
             Notification.toast(mail.subject, mail.body)
Example #8
0
def tag_sents(email):
    # Remove the 'Abstract:' part
    body = email.body[9:]

    body_sents = sent_tokenize(body)
    body_sents = [re.sub(r'\n', '', b) for b in body_sents]

    body = email.body
    for s in body_sents:
        if (not s.startswith(' ')) and s[0].isalnum():
            ns = '<sentence>' + s + ' </sentence>'
            body = body.replace(s, ns)

    return Email(email.header, body, email.fileid)
Example #9
0
    def __init__(self):
        '''
        Initialising the detectron2 model and setting computation to GPU.

        Returns
        -------
        None.

        '''
        self.comp = 'cuda' if (torch.cuda.is_available()) else 'cpu'
        self.cfg = get_cfg()
        self.cfg.MODEL.DEVICE=self.comp
        self.cfg.merge_from_file(model_zoo.get_config_file("COCO-Detection/faster_rcnn_R_50_C4_3x.yaml"))
        self.cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.9  # set threshold for this model
        
        self.cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-Detection/faster_rcnn_R_50_C4_3x.yaml")
        self.predictor = DefaultPredictor(self.cfg)
        self.num_processes = 6
        self.db = database.DataBase()
        self.email = Email()
        tz = pytz.timezone('Asia/Kolkata')
        tz = datetime.now(tz)
        self.date = str(tz.strftime('%Y-%m-%d_%H:%M'))
Example #10
0
def dict_to_email(d):
    msgid = d['mid']
    author_email = d[GMAIL.AUTHOR][-1]['email_addr']

    author_name = decode(d[GMAIL.AUTHOR][-1].get('from_text', ''))
    subject = decode(d[GMAIL.SUBJECT][-1])
    snippet = decode(d[GMAIL.SNIPPET][-1])
    attachments = [Storage(name=a) for a in d[GMAIL.ATTACHMENTS]]
    labels = [decode(l) for l in d[GMAIL.LABELS] if not l.startswith('^')]

    return Email(id=('%x' % msgid),
                 fromname=author_name,
                 fromemail=author_email,
                 sendtime=datetime.fromtimestamp(d["time"] // 1000),
                 subject=subject,
                 content=snippet,
                 attachments=attachments,
                 labels=labels)
Example #11
0
      'Corn':'CHRIS/CME_C1',
      'Dax':'CHRIS/EUREX_FDAX1',
      'FTSE100':'CHRIS/LIFFE_Z1',
      'Eurodollar':'CHRIS/CME_ED1',
      'Euro':'CHRIS/CME_EC1',
      'GBP':'CHRIS/CME_BP1',
      'Gold':'CHRIS/CME_EC1'
      }

data_index=pd.DataFrame()
for m in mkts.keys():
    try:
        data_index[m]=quandl.get(mkts[m],authtoken=token).Last
    except:
        data_index[m]=quandl.get(mkts[m],authtoken=token).Settle
data_pct=data_index.dropna().pct_change()
data=data_pct.dropna()
number=data.count().iloc[1]

window=20
results=pd.DataFrame()
for i in range(window+1,number):
    pca = PCA(n_components=5)
    pca.fit(data[i-window:i])
    results[data.iloc[i].name]=pd.Series(pca.explained_variance_)**.5

results.T['2018':].plot(kind='area',colormap='magma',title='Vol Explained').get_figure().savefig('vol_explained.png')

e=Email(subject='Morning Update: Volatility explained by compoents')
e.add_attachment('vol_explained.png')
e.send()
Example #12
0
sys.path.insert(0, PATH + '/module')

from getpass import getpass, getuser
from checker import Checker
from mail import Email

name = os.environ.get('PYMAIL_ADR')
if not name:
    name = raw_input('User : '******'Sorry .. retry')
        psw = getpass()
    e = Email(name, psw)
    try:
        e.send()
    except:
        print('\nSomething went wrong, retry')
    else:
        if e.failed:
            print('Failed sending to ' + str(e.failed))
        else:
            print('Sent')
except KeyboardInterrupt:
    print('\nTerminated')
    sys.exit(0)
}
data_index = pd.DataFrame()
for i in indices.keys():
    file = 'https://wholesale.banking.societegenerale.com/fileadmin/indices_feeds/' + indices[
        i]
    data_index[i] = pd.read_csv(file,
                                sep='\t',
                                index_col=0,
                                parse_dates=[0],
                                usecols=[0, 1]).ix[:, 0]

data_pct = data_index.pct_change()

ax1 = data_pct['2019':].cumsum().ffill().plot(colormap='jet')
ax1.set_xlabel("")
ax1.get_figure().savefig('socgen.png')
plt.show()
plt.gcf().clear()

df = pd.DataFrame()
df['CTA'] = data_index.CTA
df['SP500'] = quandl.get('CHRIS/CME_SP1', authtoken=token).Last
df = df.dropna().pct_change()
ax2 = pd.ewmcorr(df.CTA, df['SP500'], 20)['2019':].plot(
    colormap='jet', title='20 Day Rolling Correlation: CTA index to S&P 500')
ax2.set_xlabel("")
ax2.get_figure().savefig('socgen_corr.png')

e = Email(subject='Morning Update: Soc Gen Indices')
e.add_attachments(['socgen.png', 'socgen_corr.png'])
e.send()
Example #14
0
    'GBP': 'CHRIS/CME_BP1',
    #'Gold':'CHRIS/CME_EC1'
}

data_index = pd.DataFrame()
for m in mkts.keys():
    try:
        data_index[m] = quandl.get(mkts[m], authtoken=token).Last
    except:
        try:
            data_index[m] = quandl.get(mkts[m], authtoken=token).Settle
        except:
            try:
                data_index[m] = quandl.get(mkts[m], authtoken=token).Value
            except:
                try:
                    data_index[m] = quandl.get(mkts[m], authtoken=token).value
                except:
                    try:
                        data_index[m] = quandl.get(mkts[m],
                                                   authtoken=token).Rate
                    except:
                        print(m)
data_pct = data_index.pct_change()

data_pct['2019':].cumsum().ffill().plot(
    colormap='brg').get_figure().savefig('YTD.png')

e = Email(subject='Morning Update: Macro YTD Email')
e.add_attachment('YTD.png')
e.send()
Example #15
0
def setup_mail(to, files):
    email = Email()

    email.prepare_msg(to)
    email.attach_msg(email.set_msg(files))
    email.send_email()
                data_index[m]=quandl.get(mkts[m],authtoken=token).Value
            except:
                try:
                    data_index[m]=quandl.get(mkts[m],authtoken=token).value
                except:
                    data_index[m]=quandl.get(mkts[m],authtoken=token).Rate
data_pct=data_index.pct_change()  



s=calc_ts_pairwise_correlation(data_pct)
s.dropna().to_csv('pairwise_c.csv')

s['2000':].plot(colormap='jet').get_figure().savefig('pairwise.png')

e=Email(subject='Morning Update: Pairwise Correlation')
e.add_attachment('pairwise.png')
e.send()


data_pct['2019':].cumsum().ffill().plot(colormap='brg').get_figure().savefig('YTD.png')

e=Email(subject='Morning Update: Macro YTD Email')
e.add_attachment('YTD.png')
e.send()




def get_sector_data():
      sp=SectorPerformances (key=key, output_format='pandas')
Example #17
0
            link = "http://xsb.seiee.sjtu.edu.cn" + hyper.get("href")
            mail_context += "<br>\r\n".join([title, link, '\r\n'])
    if not new_term:
        mail_context += "No new schoarship today & yesterday. <br>\r\n You may want to visit http://xsb.seiee.sjtu.edu.cn/xsb/list/611-1-20.htm"

    mail_context += "<br>"
    return mail_context


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Tongqu Crawler")
    parser.add_argument("-r",
                        "--recipient",
                        type=str,
                        default="*****@*****.**")
    args = parser.parse_args()
    msg1 = ""
    msg2 = ""

    try:
        msg1 = crawl_tongqu()
    except Exception as e:
        print(e)

    try:
        msg2 = crawl_scholarship()
    except Exception as e:
        print(e)

    email = Email(recipient=args.recipient, text=msg1 + msg2)
Example #18
0
data_index = pd.DataFrame()
for i in indices.keys():
    file = 'https://cib.societegenerale.com/fileadmin/indices_feeds/' + indices[
        i]
    data_index[i] = pd.read_csv(file,
                                sep='\t',
                                index_col=0,
                                parse_dates=[0],
                                usecols=[0, 1]).ix[:, 0]

data_pct = data_index.pct_change()

ax1 = data_pct['2018':].cumsum().ffill().plot(colormap='jet')
ax1.set_xlabel("")
ax1.get_figure().savefig('socgen.png')
plt.show()
plt.gcf().clear()

df = pd.DataFrame()
df['CTA'] = data_index.CTA
df['SP500'] = quandl.get('CHRIS/CME_SP1', authtoken=token).Last
df = df.dropna().pct_change()
ax2 = pd.ewmcorr(df.CTA, df['SP500'], 20)['2018':].plot(
    colormap='jet', title='20 Day Rolling Correlation: CTA index to S&P 500')
ax2.set_xlabel("")
ax2.get_figure().savefig('socgen_corr.png')

e = Email(to='*****@*****.**',
          subject='Morning Update: Soc Gen Indices')
e.add_attachments(['socgen.png', 'socgen_corr.png'])
e.send()
Example #19
0
class Main:
    def __init__(self):
        self.wechat = WeChat()
        self.openldap = OpenLdap()
        self.e_mail = Email()

    def get_wechat_uid_info(self, uid):
        #根据uid获取企业微信中该用户的属性值
        wechat_user_list = self.wechat.get_user_list()
        for info in wechat_user_list:
            for k_info, v_info in info.items():
                if k_info == 'userid':
                    v = v_info.lower()
                    if v == uid:
                        return info

    def get_wechat_gid_info(self, gid):
        #跟据部门id获取企业微信中该部门的属性值
        wechat_department_list = self.wechat.get_department_list()
        for info in wechat_department_list:
            for k_info, v_info in info.items():
                if k_info == 'id':
                    if v_info == gid:
                        return info

    def get_wechat_ugid(self, uid):
        #根据uid获取企业微信的部门id,用于排除添加某部门用户
        wechat_user_list = self.wechat.get_user_list()
        for info in wechat_user_list:
            for k_info, v_info in info.items():
                if k_info == 'userid':
                    v = v_info.lower()
                    if v == uid:
                        dep_id = info.get('department')
                        return dep_id

    def add_user(self):
        ldap_uid = self.openldap.get_ldap_uid()
        ldap_gid = self.openldap.get_ldap_gid()
        wechat_uid = self.wechat.get_wechat_userid()
        wechat_gid = self.wechat.get_wechat_gid()

        #添加用户组
        for w_gid in wechat_gid:
            #判断微信部门是否已经存在ldap组中
            if w_gid not in ldap_gid:
                #列表[id]转成字符串id
                gid = [str(x) for x in w_gid]
                gid_new = "".join(gid)
                wechat_gid_info = self.get_wechat_gid_info(int(gid_new))
                print(wechat_gid_info)

                # 不存在则向ldap添加部门信息
                def f(id, name):
                    return self.openldap.ldap_add_group(id, name)

                f(**wechat_gid_info)

        #添加用户
        for w_uid in wechat_uid:
            # 判断微信账号是否已经存在ldap中
            if w_uid not in ldap_uid:
                # 不存在则向ldap添加账号信息
                # 列表[uid]转成字符串'uid'
                uid = "".join(w_uid)
                #判断用户是否属于排除添加的部门:合作伙伴(:40)
                exclude = [40]
                wechat_dep_id = self.get_wechat_ugid(uid)
                if wechat_dep_id not in exclude:
                    #添加用户
                    wechat_uid_info = self.get_wechat_uid_info(uid)

                    def f(userid, name, mobile, email, position, department):
                        print('开始添加ldap用户:%s' % userid)
                        if self.openldap.ldap_add_user(userid, name, mobile,
                                                       email, position,
                                                       department):
                            print('开始发送邮件')
                            self.e_mail.send_mail(email, userid, name)

                    f(**wechat_uid_info)
Example #20
0
 def __init__(self):
     self.wechat = WeChat()
     self.openldap = OpenLdap()
     self.e_mail = Email()
Example #21
0
    tfs = TfsUtils(url, auth)
    items = tfs.find_stored_query()
    name = set()

    for item_id in items:
        work_item = tfs.find_work_item(item_id)
        if work_item["24"] not in name:
            rest_time = work_item["10000"] - 8
            used_time = work_item["10052"] + 8

            data = {
                u"10000": rest_time,
                u"10052": used_time
            }

            tfs.update_work_item(item_id, data)
            name.add(work_item["24"])

        print item_id

except Exception, e:
    # print exception info
    print Exception, ":", e
    subject = "TFS报工失败"
    text = "失败原因" + str(e)
    traceback.print_exc()
    # Email notification
    email = Email(config)
    email.send(subject, text)
Example #22
0
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
plt.switch_backend('agg')
from mail import Email
from lab import *
sns.set_context("poster")
sns.set(font_scale=1)

sp = get_sp_future()
pct_returns = sp.pct_change()
short_days = 1
long_days = 60
z = (pd.Series.ewm(pct_returns, short_days).mean() -
     pd.Series.ewm(pct_returns, long_days).mean()) / (pd.Series.ewm(
         pct_returns, long_days).std())

if z.abs().iloc[-1] > 1:
    df = pd.DataFrame()
    df['SP'] = sp
    df['Z score'] = z
    ax = df['2018':].plot(secondary_y='SP')
    ax.get_figure().savefig('zscore_sp.png')
    e = Email(subject='Morning Update: S&P 500 1sd Move')
    e.add_attachments(['zscore_sp.png'])
    e.send()
else:
    print('No email')
Example #23
0
def emailFromString(uid, s, sendtime_if_error):
    'Email RFC822 string -> Email object'

    return Email.fromEmailMessage(uid, DecodedEmail(email.message_from_string(s)),
                                  sendtime_if_error)
from urllib.request import urlopen
from mail import Email

quote_page = 'http://archive.wortfm.org/'
page = urlopen(quote_page)
soup = BeautifulSoup(page, 'html.parser')

msg = ''
for l in soup.find_all(sho='83'):
    msg = msg + '<p><a href="' + l.find('button').get('mp3') + '">Diaspora</a>'

for l in soup.find_all(sho='72'):
    msg = msg + '<p><a href="' + l.find('button').get(
        'mp3') + '">Global Revolution</a>'

for l in soup.find_all(sho='21'):
    msg = msg + '<p><a href="' + l.find('button').get(
        'mp3') + '">Entertainment</a>\n'

for l in soup.find_all(sho='62'):
    msg = msg + '<p><a href="' + l.find('button').get(
        'mp3') + '">Journeys Into Jazz</a>\n'

for l in soup.find_all(sho='43'):
    msg = msg + '<p><a href="' + l.find('button').get(
        'mp3') + '">Something Wonderful</a>\n'

e = Email(subject='Weekly Update: Music Email', to=['*****@*****.**'])
e.add_text(msg)
e.send()
Example #25
0
import pandas as pd
import matplotlib.pyplot as plt
plt.switch_backend('agg')
from mail import Email
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.sectorperformance import SectorPerformances
key = 'B22889019-EABCFEE1'
sns.set_context("poster")


def get_sector_data():
    sp = SectorPerformances(key=key, output_format='pandas')
    data, _ = sp.get_sector()
    df = pd.DataFrame()
    df['1M Performane'] = data['Rank D: Month Performance']
    df['YTD Performance'] = data['Rank F: Year-to-Date (YTD) Performance']
    df['1Y Performance'] = data['Rank G: Year Performance']
    df['3Y Performance'] = (data['Rank H: Year Performance'] +
                            1)**.33333333 - 1
    df['10Y Performance'] = (data['Rank J: Year Performance'] + 1)**.1 - 1
    return df


get_sector_data().plot(
    kind='bar', colormap='jet',
    title='Performance (Long term Annualized)').get_figure().savefig(
        'sector.png', bbox_inches='tight')

e = Email(subject='Morning Update: Sector Performance')
e.add_attachment('sector.png')
e.send()
 def sendEmail(self, updatedPostViews):
     email = Email()
     email.send(updatedPostViews)
Example #27
0
data_index = pd.DataFrame()
for m in mkts.keys():
    try:
        data_index[m] = quandl.get(mkts[m], authtoken=token).Last
    except:
        try:
            data_index[m] = quandl.get(mkts[m], authtoken=token).Settle
        except:
            try:
                data_index[m] = quandl.get(mkts[m], authtoken=token).Value
            except:
                try:
                    data_index[m] = quandl.get(mkts[m], authtoken=token).value
                except:
                    try:
                        data_index[m] = quandl.get(mkts[m],
                                                   authtoken=token).Rate
                    except:
                        print(m)
data_pct = data_index.pct_change()

mu = pd.ewma(data_pct, 260)
sd = pd.ewmstd(data_pct, 260)
zscores = (data_pct - mu) / sd
last = zscores.iloc[-2].dropna().sort_values()
last.plot(kind='barh', colormap='jet',
          ylim=[-3, 3]).get_figure().savefig('zscore.png', bbox_inches='tight')

e = Email(subject='Morning Update: Macro Dashboard')
e.add_attachment('zscore.png')
e.send()
Example #28
0
from mail import Email

if __name__ == '__main__':
    mail = Email(to='*****@*****.**', subject='Follow-up')
    ctx = {'username': '******'}
    mail.text('followup.txt', ctx)
    mail.html('followup.html', ctx)  # Optional
    mail.send()

Example #29
0
for m in mkts.keys():
    try:
        data_index[m] = quandl.get(mkts[m], authtoken=token).Last
    except:
        try:
            data_index[m] = quandl.get(mkts[m], authtoken=token).Settle
        except:
            try:
                data_index[m] = quandl.get(mkts[m], authtoken=token).Value
            except:
                try:
                    data_index[m] = quandl.get(mkts[m], authtoken=token).value
                except:
                    try:
                        data_index[m] = quandl.get(mkts[m],
                                                   authtoken=token).Rate
                    except:
                        print(m)
data_pct = data_index.pct_change()

mu = pd.ewma(data_pct, 60)
sd = pd.ewmstd(data_pct, 60)
zscores = (data_pct - mu) / sd
last = zscores.iloc[-2].dropna().sort_values()
last.plot(kind='barh', colormap='jet',
          ylim=[-3, 3]).get_figure().savefig('zscore.png', bbox_inches='tight')

e = Email(to='*****@*****.**',
          subject='Morning Update: Macro Dashboard')
e.add_attachment('zscore.png')
e.send()
Example #30
0
mkts = {
    'SP 500': 'CHRIS/CME_SP1',
    'Natural Gas': 'CHRIS/CME_NG1',
    'US 10Y': 'CHRIS/CME_TY1',
    'Crude Oil': 'CHRIS/CME_CL1',
    'Eurostoxx 50': 'CHRIS/EUREX_FESX1',
    'Dollar Index': 'CHRIS/ICE_DX1',
    'Wheat': 'CHRIS/CME_W7',
    'Corn': 'CHRIS/CME_C1',
    'Dax': 'CHRIS/EUREX_FDAX1',
    'FTSE100': 'CHRIS/LIFFE_Z1',
    'Eurodollar': 'CHRIS/CME_ED1',
    'Euro': 'CHRIS/CME_EC1',
    'GBP': 'CHRIS/CME_BP1',
    'Gold': 'CHRIS/CME_EC1'
}

data_index = pd.DataFrame()
for m in mkts.keys():
    try:
        data_index[m] = quandl.get(mkts[m], authtoken=token).Last
    except:
        data_index[m] = quandl.get(mkts[m], authtoken=token).Settle
data_pct = data_index.pct_change()

s = calc_ts_pairwise_correlation(data_pct)
s['2000':].plot(colormap='jet').get_figure().savefig('pairwise.png')

e = Email(subject='Morning Update: Pairwise Correlation')
e.add_attachment('pairwise.png')
e.send()
Example #31
0
sys.path.insert( 0, PATH + '/module' )

from getpass import getpass, getuser
from checker import Checker
from mail import Email

name = os.environ.get('PYMAIL_ADR')
if not name:
    name = raw_input('User : '******'Sorry .. retry')
        psw = getpass()
    e = Email( name, psw )
    try:
        e.send()
    except:
        print('\nSomething went wrong, retry')
    else:
        if e.failed:
            print('Failed sending to ' + str(e.failed))
        else:
            print('Sent')
except KeyboardInterrupt:
    print('\nTerminated')
    sys.exit(0)
Example #32
0
        SENT_VIA = 0
    MINISERVER = global_cfg.get("MINISERVER1", "IPADDRESS")
    INSTALLFOLDER = global_cfg.get("BASE", "INSTALLFOLDER")
    logging.info("<INFO> loading configuration...")
    logging.info("<INFO> DiskStation - " + DS_HOST + ", " + DS_PORT + ", " +
                 DS_USER + ", " + EMAIL)
    logging.info("<INFO> Camera IDs - " + CIDS)
    logging.info("<INFO> Miniserver - " + MINISERVER)

    while True:
        data, addr = sock.recvfrom(
            1024)  # read data with buffer size of 1024 bytes
        logging.info("<INFO> received message from %s: %s" % (addr[0], data))

        if (str(data).__contains__("TestMail")):
            email = Email()
            response = email.SendMsg(
                "Test from Loxberry",
                "This message was sent sucessfully from your Loxberry! \nHave fun :-) "
            )
            if response == True:
                logging.info("<INFO> successful executed \"%s\" " % data)
            else:
                logging.info("<ERROR> %s not executed" % data)
            continue

        if (addr[0] == MINISERVER or addr[0] == "127.0.0.1"
            ):  # only the miniserver is allowed to send commands
            # create DS object and login
            ds = DiskStation(DS_USER, DS_PWD, DS_HOST, DS_PORT, EMAIL,
                             INSTALLFOLDER)
Example #33
0
        'could not process areas.json file make sure that areas.json exists')
except KeyError:
    raise BaseException('areas key is not specified in areas.json')

# init the Email
try:
    sender_address = environ['EMAIL_ADDRESS']
    receiver_address = environ['EMAIL_ADDRESS']
    sender_pass = environ['PASSWORD']
except KeyError as e:
    print(
        'please make sure that you set the environment variables EMAIL_ADDRESS and PASSWORD correctly'
    )
    raise

email = Email(sender_address, receiver_address, sender_pass)

print('found {} areas in areas.json file'.format(len(AREAS)))
print('---------------------------------')


def get_inst_rain_average(file_path: str) -> Dict[str, float]:
    '''
        function to get the average rain over a grid for locations specified in areas.json 
        :param file_path x:   file path to a grib file 
        :return:              data row including (name: area name, area_max: max rain, 
                                area_min: min rain, area_average: average rain for all
                                areas specified in areas.json file)
    '''
    grbs = pygrib.open(file_path)
    grb = grbs[1]
Example #34
0
from mail import Email

if __name__ == '__main__':
    mail = Email(to='*****@*****.**', subject='Adaptation Complete')
    ctx = {'username': '******'}
    mail.text('adaptation.txt', ctx)
    mail.html('adaptation.html', ctx)  # Optional
    mail.send()

Example #35
0
#!/usr/bin/python
#coding:utf-8
import os
import sys
from datetime import *
from urlparse import urlparse
from jinja2 import Environment, FileSystemLoader
from mail import Email

if __name__ == "__main__":
    # get data
    log_result = 

    # generate using jinja2 template
    env = Environment(loader = FileSystemLoader('%s/templates' % os.path.dirname(os.path.abspath(__file__))))
    template = env.get_template('html.email.tpl')
    html_content = template.render(result = log_result)

    # mail 
    email = Email(smtp = 'smtp.company.com') 
    email.send(sender = '*****@*****.**',
              receiptors = ["*****@*****.**", "*****@*****.**", "*****@*****.**"],
              cc = '*****@*****.**',
              subject = 'email subject',
              content = html_content,
              content_subtype = 'html',
              attachment = ['/file/path/to/attachment'])