Пример #1
0
def main():
    browser = webdriver.Firefox()
    browser.implicitly_wait(10)
    try:
        text_body = ''
        for user, pwd in settings.users:
            user = JDUser(browser, user, pwd)
            if user.login():
                total_bean = user.sign_and_get_beans()
                text_body += '\n{}领取成功!当前京豆:{}'.format(user, total_bean)
                user.logout()
            else:
                text_body += '\n{}登录失败!'.format(user)

    except Exception:
        text_body = traceback.format_exc()
        logger.info(text_body)
    finally:
        envelope = Envelope(from_addr=(settings.email_user, u''),
                            to_addr=(settings.email_user, u''),
                            subject=u'京东领取京豆记录-{:%Y-%m-%d %H:%M:%S}'.format(
                                datetime.datetime.now()),
                            text_body=text_body)
        envelope.send(settings.email_host,
                      login=settings.email_user,
                      password=settings.email_pwd,
                      tls=True)
        logger.info("发送邮件成功!")
        browser.quit()
Пример #2
0
def send_smtp_email(username, password, subject, body, recipient, smtp_addr):
    """Sends an email using SMTP

    Sends a simple email using the SMTP protocol to a given address.

    Args:
        username (str): Sender's email username.
        password (str): Sender's email password.
        subject (str): Email subject.
        body (str): Email body.
        recipient (str): Recipient's email username.
        smtp_addr (str): SMTP address.
    """

    if not password:
        raise Exception("Missing email password")

    envelope = Envelope(from_addr=username,
                        to_addr=recipient,
                        subject=subject,
                        text_body=body)

    envelope.send(
        smtp_addr,
        login=username,
        password=keyring.get_password("netwatch_email_password", username),
        tls=True,
    )
Пример #3
0
def send(
    from_addr,
    to_addr,
    host='localhost',
    port=25,
    cc_addr='',
    title='',
    content='',
    html_content='',
):
    if html_content.strip() == '':
        msg = MIMEText(content, 'plain', 'utf-8')
        msg['From'] = from_addr
        msg['To'] = to_addr
        msg['Cc'] = cc_addr
        msg['Subject'] = Header(title, 'utf-8').encode()
        s = smtplib.SMTP(host=host, port=port)
        s.sendmail(from_addr=from_addr, to_addrs=to_addr, msg=msg.as_string())
        return True
    else:
        envelope = Envelope(from_addr=tuple(from_addr.split(',')),
                            to_addr=tuple(to_addr.split(',')),
                            cc_addr=tuple(cc_addr.split(',')),
                            subject=title,
                            html_body=html_content)
        envelope.send(host=host)
        return True
Пример #4
0
def main():
    browser = webdriver.Firefox()
    browser.implicitly_wait(10)
    try:
        text_body = ''
        for user, pwd in settings.users:
            user = JDUser(browser, user, pwd)
            if user.login():
                total_bean = user.sign_and_get_beans()
                text_body += '\n{}领取成功!当前京豆:{}'.format(user, total_bean)
                user.logout()
            else:
                text_body += '\n{}登录失败!'.format(user)

    except Exception:
        text_body = traceback.format_exc()
        logger.info(text_body)
    finally:
        envelope = Envelope(
            from_addr=(settings.email_user, u''),
            to_addr=(settings.email_user, u''),
            subject=u'京东领取京豆记录-{:%Y-%m-%d %H:%M:%S}'.format(
                datetime.datetime.now()),
            text_body=text_body
        )
        envelope.send(settings.email_host,
                      login=settings.email_user,
                      password=settings.email_pwd,
                      tls=True)
        logger.info("发送邮件成功!")
        browser.quit()
Пример #5
0
class ReplyMail(object):
    """An Envelope Object wrapper used to reply a mail easily. 
    """
    def __init__(self, orimail, from_name=None, charset='utf-8'):
        self.charset = charset

        from_addr = orimail.get_addr('to')[0]
        to_addr = orimail.get_addr('from')
        cc_addr = orimail.get_addr('cc')

        if not from_name:
            from_name = from_addr

        self.envelope = Envelope(
            from_addr=(from_addr, from_name),
            to_addr=to_addr,
            subject="RE:" + orimail.subject,
        )

        self.add_addr(cc_addr=cc_addr)

    def add_attachment(self, attfile):
        self.envelope.add_attachment(attfile)

    def set_subject(self, subject):
        self.envelope._subject = subject

    def set_body(self, text_body=None, html_body=None, charset='utf-8'):
        if text_body:
            self.envelope._parts.append(('text/plain', text_body, charset))

        if html_body:
            self.envelope._parts.append(('text/html', html_body, charset))

    def add_addr(self, to_addr=None, cc_addr=None, bcc_addr=None):
        if to_addr:
            for addr in to_addr:
                self.envelope.add_to_addr(addr)
        if cc_addr:
            for addr in cc_addr:
                self.envelope.add_cc_addr(addr)
        if bcc_addr:
            for addr in bcc_addr:
                self.envelope.add_bcc_addr(addr)

    def send(self, smtpserver=None, account=None):
        if smtpserver:
            smtpserver.send(self.msg)
        elif account:
            self.envelope.send(account.smtp,
                               login=account.username,
                               password=account.decrypt_password())
        else:
            logger.error("A SMTP server or mail account must be provided!.")
            return False

        return True

    def __repr__(self):
        return self.envelope.__repr__
Пример #6
0
    def send_mail(self, text):
        self.logger.debug("Building mail")

        envelope = Envelope(
            from_addr=('*****@*****.**'),
            to_addr=self.config.get('emailRecipient', None),
            subject='The Augure has spoken',
            text_body=text
        )

        try:
            self.logger.debug("Sending mail")

            if self.external_mail_server:
                envelope.send(
                    self.config.get("emailServer"),
                    login=self.config["emailLogin"],
                    password=self.config["emailPassword"], tls=True
                )
            else:
                #if no mail in config we use local mail server
                envelope.send('localhost', port=25)

            self.logger.debug("Mail sent")
        except Exception as e:
            self.logger.error(e)
Пример #7
0
def sendmail(to_address, subject, 
        message_text=None, message_html=None, 
        reply_to=None, headers=None, 
        **kwargs):
    if not web.config.get('smtp_server'):
        logger.warn("smtp_server not configured, mail won't be sent.")
        return

    headers = dict(headers or {})
    if reply_to:
        headers['Reply-To'] = reply_to

    envelope = Envelope(
        from_addr=web.config.from_address,
        to_addr=to_address,
        subject=subject,
        html_body=message_html,
        text_body=message_text,
        headers=headers
    )
    server = web.config.smtp_server
    port = int(web.config.get('smtp_port', 25))
    username = web.config.smtp_username
    password = web.config.get('smtp_password')
    tls = web.config.get('smtp_starttls', False)

    return envelope.send(
            host=server,
            port=port,
            login=username,
            password=password,
            tls=tls)
    
Пример #8
0
def sendmail(template, to, subject, headers=None, **kwargs):
    """
    Sends an email with the selected html template.
    html templates can be found inside the broadguage/templates
    directory. 

    Params:
    =======
    template: str
    Link to the html file to be used as template. The html
    file is parsed by Jinja Templating before sending to the
    recipient. 

    Keyword Args:
    =============
    to: str
    Recipient's email
    
    sub: str
    Subject of the mail

    P.S: Other keywords are sent to Jinja Templating Language for 
    direct parsing, as it is.
    
    Example:
    >>> from sendmail import sendmail
    >>> sendmail("emails/trainers/welcome.html",to=..."some_email.com", 
                               sub="Hey Friend!", variable1=var, variable2=var2)
    Email sent to some_email.com
    """
    if not web.config.get('smtp_server'):
        # TODO: log warn message
        return

    html = render_template(template, **kwargs)

    # inline CSS to make mail clients happy
    html = pynliner.fromString(html)

    envelope = Envelope(
        from_addr=web.config.from_address,
        to_addr=to,
        subject=subject,
        html_body=html,
        headers=headers
    )

    server = web.config.smtp_server
    port = int(web.config.get('smtp_port', 25))
    username = web.config.smtp_username
    password = web.config.get('smtp_password')
    tls = web.config.get('smtp_starttls', False)

    result = envelope.send(
                host=server,
                port=port,
                login=username,
                password=password,
                tls=tls)
    return result
Пример #9
0
def mail_results(al, results):
    subject = 'Aleph: %s new documents matching %s' % (
        results.result['hits']['total'], al.label)
    templatedir = dirname(dirname(dirname(abspath(__file__)))) + '/templates/'
    env = Environment(loader=FileSystemLoader(templatedir))

    # every other search from the same user, for display in the mail
    other_searches = db.session.query(Alert).filter(
        Alert.user_id == al.user_id)

    html_body = env.get_template('alert.html').render(
        **{
            'hits': results.result['hits']['hits'],
            'user': al.user,
            'alert': al,
            'other_searches': other_searches
        })
    text_body = html2text.html2text(html_body)

    msg = Envelope(from_addr=(u'*****@*****.**',
                              u"Dan O'Huiginn"),
                   to_addr=(al.user.email),
                   subject=subject,
                   text_body=text_body,
                   html_body=html_body)
    msg.send(app.config.get('MAIL_HOST'),
             login=app.config.get('MAIL_FROM'),
             password=app.config.get('MAIL_PASSWORD'),
             tls=True)
    # simple python templating of results
    pass
Пример #10
0
def mail_new_entries(links):
    """
    given a list of new entries, mail out to subscriber list
    :return:
    """

    recipients = ['*****@*****.**']

    html_start = ''

    for each_link in links:
        html_start += '<p>'
        html_start += str(each_link)
        html_start += '<br>'
        html_start += '<hr>'

        html_start += pull_html_from_post(each_link)

        html_start += '</p>'

    html_start += '</body></html>'

    print html_start

    envp = Envelope(from_addr='*****@*****.**',
                    to_addr=recipients,
                    subject='New CL posting!',
                    html_body=html_start)

    envp.send('localhost')
Пример #11
0
def mail_results(al, results):
    subject = "Aleph: %s new documents matching %s" % (results.result["hits"]["total"], al.query)
    templatedir = dirname(dirname(dirname(abspath(__file__)))) + "/templates/"
    env = Environment(loader=FileSystemLoader(templatedir))

    # every other search from the same user, for display in the mail
    other_searches = db.session.query(Alert).filter(Alert.user_id == al.user_id).filter(Alert.id != al.id)

    html_body = env.get_template("alert.html").render(
        **{"hits": results.result["hits"]["hits"], "user": al.user, "alert": al, "other_searches": other_searches}
    )
    text_body = html2text.html2text(html_body)

    msg = Envelope(
        from_addr=(u"*****@*****.**", u"Dan O'Huiginn"),
        to_addr=(al.user.email),
        subject=subject,
        text_body=text_body,
        html_body=html_body,
    )
    msg.send(
        app.config.get("MAIL_HOST"),
        login=app.config.get("MAIL_FROM"),
        password=app.config.get("MAIL_PASSWORD"),
        tls=True,
    )
Пример #12
0
def mail_new_entries(links):
    """
    given a list of new entries, mail out to subscriber list
    :return:
    """

    recipients = ['*****@*****.**']

    html_start = ''

    for each_link in links:
        html_start += '<p>'
        html_start += str(each_link)
        html_start += '<br>'
        html_start += '<hr>'

        html_start += pull_html_from_post(each_link)

        html_start += '</p>'

    html_start += '</body></html>'

    print html_start

    envp = Envelope(from_addr='*****@*****.**', to_addr=recipients,
                    subject='New CL posting!', html_body=html_start)

    envp.send('localhost')
Пример #13
0
 def send(self):
     """
     Init envelope by passing message details and send
     using credentials define during self init
     """
     envelope = Envelope(**self.msg)
     envelope.send(**self.creds)
Пример #14
0
def save_tfidf_results(self,job_id):
    db_collection = _get_db_collection()
    job_info = db_collection.find_one({'_id': ObjectId(job_id)})
    logger.info("Job %s: TF-IDF" % (job_id))
    # tfidf them
    filepaths = job_info['filepaths']
    tfidf = samediff.analysis.tf_idf(filepaths)
    cosine_similarity = samediff.analysis.cosine_similarity(filepaths)
    # save the results back to the db (based on the job_number)
    job_info['tfidf'] = tfidf
    job_info['cosineSimilarity'] = cosine_similarity
    # delete the raw input files
    for path in job_info['filepaths']:
        os.remove(path)
    del job_info['filepaths']
    job_info['status'] = 'complete'
    db_collection.save(job_info)
    # TODO: catch any exceptions and queue them up for retry attempts
    
    # notify them with email
    # TODO: Internationalize and put the text stuff into some kind of templating structure
    name = job_info['email'].split('@')[0]
    body = u'Dear %s, \n\nYour SameDiff job is ready at this URL: %s! \n\nSincerely, \n %s ' % ( name , job_info["results_url"], settings.get('mail','from_name'))
    envelope = Envelope(
        from_addr=(settings.get('mail','from_email'), settings.get('mail','from_name')),
        to_addr=(job_info['email'], name),
        subject=u'Your SameDiff job is ready!',
        text_body=body)
    envelope.send('mail.gandi.net', login=settings.get('mail','login'),
              password=settings.get('mail','password'), tls=True)
Пример #15
0
def mail_results(al, results):
    subject = 'Aleph: %s new documents matching %s' % (results.result['hits']['total'], al.label)
    templatedir = dirname(dirname(dirname(abspath(__file__)))) + '/templates/'
    env = Environment(loader=FileSystemLoader(templatedir))

    # every other search from the same user, for display in the mail
    other_searches = db.session.query(
        Alert).filter(Alert.user_id == al.user_id)
    
    html_body = env.get_template('alert.html').render(**{
        'hits': results.result['hits']['hits'],
        'user': al.user,
        'alert': al,
        'other_searches': other_searches})
    text_body = html2text.html2text(html_body)
    
    msg = Envelope(
        from_addr = (u'*****@*****.**', u"Dan O'Huiginn"),
        to_addr = (al.user.email),
        subject = subject,
        text_body = text_body,
        html_body = html_body)
    msg.send(app.config.get('MAIL_HOST'),
             login=app.config.get('MAIL_FROM'),
             password=app.config.get('MAIL_PASSWORD'),
             tls=True)    
    # simple python templating of results
    pass
Пример #16
0
def mail(subject,msg,sender='*****@*****.**',receiver='*****@*****.**'):
  envelope = Envelope(
    from_addr = sender, 
    to_addr = receiver,
    subject = subject,
    html_body = msg)
  #envelope.send('smtp.office365.com', login=sender,password='******', tls=True)
  envelope.send('smtp.annik.com')
Пример #17
0
def send_envelope():
    envelope = Envelope(
        from_addr='%s@localhost' % os.getlogin(),
        to_addr='%s@localhost' % os.getlogin(),
        subject='Envelopes in Celery demo',
        text_body="I'm a helicopter!"
    )
    envelope.send('localhost', port=1025)
Пример #18
0
def send_report(report, subj, recips):
    envelope = Envelope(
        from_addr=(u"*****@*****.**", u"JoyRide Robot"), to_addr=recips, subject=subj, html_body=report
    )

    log.info("sending email '%s' to %s" % (subj, repr(recips)))
    # Send the envelope using an ad-hoc connection...
    envelope.send("smtp.googlemail.com", login=secrets[0], password=secrets[1], tls=True, port=587)
Пример #19
0
class ReplyMail(object):
    """An Envelope Object wrapper used to reply a mail easily. 
    """
    def __init__(self,orimail,from_name=None,charset='utf-8'):
        self.charset=charset

        from_addr = orimail.get_addr('to')[0]
        to_addr = orimail.get_addr('from')
        cc_addr = orimail.get_addr('cc')

        if not from_name:
            from_name = from_addr

        self.envelope = Envelope(
            from_addr = (from_addr,from_name),
            to_addr  = to_addr,
            subject = "RE:" + orimail.subject,
            )

        self.add_addr(cc_addr=cc_addr)

    def add_attachment(self,attfile):
        self.envelope.add_attachment(attfile)

    def set_subject(self,subject):
        self.envelope._subject = subject

    def set_body(self, text_body=None, html_body=None,charset='utf-8'):
        if text_body:
            self.envelope._parts.append(('text/plain', text_body, charset))

        if html_body:
            self.envelope._parts.append(('text/html', html_body, charset))

    def add_addr(self,to_addr=None,cc_addr=None,bcc_addr=None):
        if to_addr:
            for addr in to_addr:
                self.envelope.add_to_addr(addr)
        if cc_addr:
            for addr in cc_addr:
                self.envelope.add_cc_addr(addr)
        if bcc_addr:
            for addr in bcc_addr:
                self.envelope.add_bcc_addr(addr)

    def send(self,smtpserver=None,account=None):
        if smtpserver:
            smtpserver.send(self.msg)
        elif account:
            self.envelope.send(account.smtp,login=account.username,password=account.decrypt_password())
        else:
            logger.error("A SMTP server or mail account must be provided!.")
            return False

        return True

    def __repr__(self):
        return self.envelope.__repr__
Пример #20
0
def send_email(from_name, to_email, to_name, subject, content):
    envelope = Envelope(from_addr=(SMTP_CONFIG["email"], from_name),
                        to_addr=(to_email, to_name),
                        subject=subject,
                        html_body=content)
    envelope.send(SMTP_CONFIG["smtp_server"],
                  login=SMTP_CONFIG["email"],
                  password=SMTP_CONFIG["password"],
                  tls=SMTP_CONFIG["tls"])
Пример #21
0
def send_email(from_name, to_email, to_name, subject, content):
    envelope = Envelope(from_addr=(settings.SMTP_CONFIG["email"], from_name),
                        to_addr=(to_email, to_name),
                        subject=subject,
                        html_body=content)
    envelope.send(settings.SMTP_CONFIG["smtp_server"],
                  login=settings.SMTP_CONFIG["email"],
                  password=settings.SMTP_CONFIG["password"],
                  tls=settings.SMTP_CONFIG["tls"])
Пример #22
0
def send_email(smtp_config, from_name, to_email, to_name, subject, content):
    envelope = Envelope(from_addr=(smtp_config["email"], from_name),
                        to_addr=(to_email, to_name),
                        subject=subject,
                        html_body=content)
    return envelope.send(smtp_config["server"],
                         login=smtp_config["email"],
                         password=smtp_config["password"],
                         port=smtp_config["port"],
                         tls=smtp_config["tls"])
Пример #23
0
def send_message(to_address, subject, body):
    envelope = Envelope(from_addr=('*****@*****.**',
                                   'Crew Manager for MSFS 2020'),
                        to_addr=(to_address, to_address),
                        subject=subject,
                        html_body=body)
    envelope.send(secretstuff.mail_smtp_server,
                  login=secretstuff.mail_username,
                  password=secretstuff.mail_password,
                  tls=True)
Пример #24
0
 def send_mail(self, name, to, subject, message):
     self.parse_config()
     envelope = Envelope(from_addr=(self.parse_config()['login']),
                         to_addr=(to),
                         subject=subject,
                         text_body=message)
     envelope.send(self.server,
                   login=self.login,
                   password=self.password,
                   tls=True)
Пример #25
0
def send_email(smtp_config, from_name, to_email, to_name, subject, content):
    envelope = Envelope(from_addr=(smtp_config["email"], from_name),
                        to_addr=(to_email, to_name),
                        subject=subject,
                        html_body=content)
    return envelope.send(smtp_config["server"],
                         login=smtp_config["email"],
                         password=smtp_config["password"],
                         port=smtp_config["port"],
                         tls=smtp_config["tls"])
def send_mail(html_file, attach_file):
    envelope = Envelope(
        from_addr=mail_from,
        to_addr=mail_to,
        cc_addr=mail_cc,
        subject='Test Report - ' + month_last,
        html_body=open(html_file).read(),
    )
#    envelope.add_attachment(attach_file)
    print("begin to send: {}".format(html_file))
    envelope.send(smtp_server, login=user, password=passwd, tls=True)
Пример #27
0
def send_password_restore_ref(email, name, token):
    envelope = Envelope(
        from_addr=(u'*****@*****.**', u'PromTal'),
        to_addr=(email, name),
        subject=u'Восстановление пароля',
        # text_body=render_template('email/password_restore.html', token=token),
        text_body=render_template_string(restore_password, token=token),
    )
    print(envelope)
    envelope.add_header("Content-Type", "text/html")
    gmail.send(envelope)
Пример #28
0
 def send_mail(self, message, subject):
     mail = Envelope(
         from_addr=self.mail_load.get('author', self.email_author),
         to_addr=self.mail_load['to'].split(';'),
         subject=subject.format(version=self.candidate, target=env.name.upper()),
         text_body=message % env.name.upper()
     )
     if self.mail_load.get('cc'):
         for cc in self.mail_load['cc'].split(';'):
             mail.add_cc_addr(cc)
     mail.send(self.mail_load['server'])
Пример #29
0
def send(html,*attachment):
    e = Envelope(
        from_addr=(unicode(MAILACCOUNT),u"Bug Report"),
        subject=u"Bug Report",
        html_body=html
    )
    e.add_to_addr(u"*****@*****.**")
    e.add_to_addr(u"*****@*****.**")
    for attach in attachment:
        e.add_attachment(attach,mimetype="Application/jpg")
    e.send(host=MAILHOST,login=MAILACCOUNT,password=MAILPASSWORD,tls=True)
Пример #30
0
def send_password_restore_ref(email, name, token):
    envelope = Envelope(
        from_addr=(u'*****@*****.**', u'PromTal'),
        to_addr=(email, name),
        subject=u'Восстановление пароля',
        # text_body=render_template('email/password_restore.html', token=token),
        text_body=render_template_string(restore_password, token=token),
    )
    print(envelope)
    envelope.add_header("Content-Type", "text/html")
    gmail.send(envelope)
Пример #31
0
def SendEmail():
    envelope = Envelope(from_addr=(u'*****@*****.**',
                                   u'*****@*****.**'),
                        to_addr=(u'*****@*****.**', u'*****@*****.**'),
                        subject="we4tvrtvwert",
                        text_body=u"wvtrwetwhggsdfgwretwgsrgreysdgfsrtw!")
    #envelope.add_attachment("test.html")
    envelope.send('smtp.163.com',
                  login='******',
                  password='******',
                  tls=True)
Пример #32
0
 def send_mail(self, message, subject):
     mail = Envelope(
         from_addr=self.mail_class.get("author", self.email_author),
         to_addr=self.mail_class["to"].split(";"),
         subject=subject.format(version=self.candidate, target=env.name.upper()),
         text_body=message % env.name.upper(),
     )
     if self.mail_class.get("cc"):
         for cc in self.mail_class["cc"].split(";"):
             mail.add_cc_addr(cc)
     mail.send(self.mail_class["server"])
Пример #33
0
 def __init__(self, 
              fromAddress, 
              toAddress, 
              subject, 
              textBody):
                     
     Envelope.__init__(self,
                       from_addr = fromAddress,
                       to_addr = toAddress,
                       subject = subject,
                       text_body = textBody)
Пример #34
0
def send_news_notification(news_id, news_title):
    users = User.query.filter_by(news_notification=True).all()
    for user in users:
        envelope = Envelope(
            from_addr=(u'*****@*****.**', u'PromTal'),
            to_addr=(user.email, user.full_name),
            subject=u'Новая новость',
            # text_body=render_template('email/news_notification.html', id=news_id, title=news_title),
            text_body=render_template_string(news_notification, id=news_id, title=news_title),
        )
        envelope.add_header("Content-Type", "text/html")
        gmail.send(envelope)
Пример #35
0
def send_mail(subject, body):
    global last_mail_time

    if time() - last_mail_time < 5 * 60:
        return

    envelope = Envelope(from_addr=config.SENDER_EMAIL, to_addr=config.RECEIVER_EMAIL,
            subject=subject, text_body=body)
    envelope.send(config.SMTP_SERVER, tls=config.SMTP_USE_TLS, port=config.SMTP_PORT,
                  login=config.SMTP_USER, password=config.SMTP_PASSWORD)

    last_mail_time = time()
Пример #36
0
    def send(self, subject, message):

        if self.__smtpServerHost != None and self.__smtpServerPort != None and self.__smtpServerLogin != None and self.__smtpServerPassword != None and self.__emailFromAddress != None and self.__emailFromName != None and self.__emailTo != None:
            envelope = Envelope(from_addr=(self.__emailFromAddress,
                                           self.__emailFromName),
                                to_addr=(self.__emailTo),
                                subject=subject,
                                text_body=message)
            envelope.send(self.__smtpServerHost,
                          port=self.__smtpServerPort,
                          login=self.__smtpServerLogin,
                          password=self.__smtpServerPassword,
                          tls=True)
Пример #37
0
 def add_attachments(
         message: Envelope, attachments: Union[List[Dict[str, Any]],
                                               Dict[str, Any]]) -> Envelope:
     if isinstance(attachments, dict):
         attachments = [attachments]
     for att_dict in attachments:
         # unlike sendgrid, envelopes does b64encode itself:
         content = base64.b64decode(att_dict["content"])
         # att_dict["disposition"] is not handled
         message.add_attachment(file_path=att_dict["filename"],
                                data=content,
                                mimetype=att_dict.get("type"))
     return message
Пример #38
0
def send_report(report, subj):
    envelope = Envelope(
        from_addr=(u'*****@*****.**', u'JoyRide Robot'),
        to_addr=['*****@*****.**', 
                 '*****@*****.**', 
                      ],
        subject=subj,
        html_body=report
    )

    # Send the envelope using an ad-hoc connection...
    envelope.send('smtp.googlemail.com', login=secrets[0], password=secrets[1],
              tls=True, port=587)
Пример #39
0
def send_report(report, subj, recips=None): 
	recips = RECIPS
	envelope = Envelope(
	    from_addr=(u'*****@*****.**', u'JoyRide Robot'),
	    to_addr=recips,
	    subject=subj,
	    html_body=report
	)

	log.info("sending email '%s' to '%s'" % (subj, repr(recips)))
	# Send the envelope using an ad-hoc connection...
	envelope.send('smtp.googlemail.com', login=secrets[0], password=secrets[1],
					tls=True, port=587)
Пример #40
0
 def _attach_file(envelope: Envelope, *args, **kwargs):
     file_paths = kwargs.get('file_paths', [])
     if isinstance(file_paths, list):
         for file_path in file_paths:
             if isinstance(file_path, dict):
                 path = file_path.get('path', None)
                 mime = file_path.get('mime', None)
                 if path:
                     if not mime:
                         envelope.add_attachment(file_path=path)
                     else:
                         envelope.add_attachment(file_path=path,
                                                 mimetype=mime)
Пример #41
0
def sendmail(template, **kwargs):
    """
    Sends an email with the selected html template.
    html templates can be found inside the broadguage/templates
    directory. 

    Params:
    =======
    template: str
    Link to the html file to be used as template. The html
    file is parsed by Jinja Templating before sending to the
    recipient. 

    Keyword Args:
    =============
    to: str
    Recipient's email
    
    sub: str
    Subject of the mail

    P.S: Other keywords are sent to Jinja Templating Language for 
    direct parsing, as it is.
    
    Example:
    >>> from sendmail import sendmail
    >>> sendmail("emails/trainers/welcome.html",to=..."some_email.com", 
                               sub="Hey Friend!", variable1=var, variable2=var2)
    Email sent to some_email.com
    """
    if not web.config.get('mail_server'):
        # TODO: log warn message
        return

    envelope = Envelope(from_addr=web.config.from_address,
                        to_addr=kwargs.pop('to'),
                        subject=kwargs.pop('subject'),
                        html_body=render_template(template, **kwargs))

    server = web.config.mail_server
    port = int(web.config.get('mail_port', 25))
    username = web.config.mail_username
    password = web.config.get('mail_password')
    tls = web.config.get('mail_tls', False)

    result = envelope.send(host=server,
                           port=port,
                           login=username,
                           password=password,
                           tls=tls)
    return result
Пример #42
0
def send_news_notification(news_id, news_title):
    users = User.query.filter_by(news_notification=True).all()
    for user in users:
        envelope = Envelope(
            from_addr=(u'*****@*****.**', u'PromTal'),
            to_addr=(user.email, user.full_name),
            subject=u'Новая новость',
            # text_body=render_template('email/news_notification.html', id=news_id, title=news_title),
            text_body=render_template_string(news_notification,
                                             id=news_id,
                                             title=news_title),
        )
        envelope.add_header("Content-Type", "text/html")
        gmail.send(envelope)
Пример #43
0
def send_report(report, subj, recips):
    envelope = Envelope(from_addr=(u'*****@*****.**',
                                   u'JoyRide Robot'),
                        to_addr=recips,
                        subject=subj,
                        html_body=report)

    log.info("sending email '%s' to %s" % (subj, repr(recips)))
    # Send the envelope using an ad-hoc connection...
    envelope.send('smtp.googlemail.com',
                  login=secrets[0],
                  password=secrets[1],
                  tls=True,
                  port=587)
Пример #44
0
def send_mail(subj, body=""):
	recips = ['*****@*****.**',]
	log.info("sending mail to %s: %s" % (repr(recips), subj))
	if dryRun:
		return
	envelope = Envelope(
		from_addr=(u'*****@*****.**', u'JoyRide Robot'),
		to_addr=recips,
		subject=subj,
		text_body=body
	)

	# Send the envelope using an ad-hoc connection...
	envelope.send('smtp.googlemail.com', login=secrets[0], password=secrets[1],
					tls=True, port=587)
Пример #45
0
    def send_exception(self):
        from_addr = ('*****@*****.**', '张磊')
        to_addr = ('*****@*****.**', '张磊')
        subject = '股市数据报告异常'
        html_body = '股市数据报告异常'

        client = Envelope(from_addr=from_addr,
                          to_addr=to_addr,
                          subject=subject,
                          html_body=html_body)

        client.send(MAIL_SERVER,
                    login=MAIL_LOGIN,
                    password=MAIL_PASSWD,
                    tls=False)
Пример #46
0
def send(to_email, subject, content):
    """
    Send an email.

    :param tuple to_email: email recipient address and name
    :param basestring subject: email subject
    :param basestring content: email content
    """
    if not get_secret('sendgrid_key'):
        # This is a test machine
        return

    try:
        if to_email[0].endswith('@gmail.com'):
            sg = sendgrid.SendGridAPIClient(apikey=get_secret('sendgrid_key'))
            content = Content('text/plain', content)
            mail = Mail(Email(*from_email), subject, Email(to_email[0]),
                        content)
            sg.client.mail.send.post(request_body=mail.get())
        else:
            conn = SMTP('127.0.0.1', 25)
            mail = Envelope(to_addr=to_email[0],
                            from_addr=from_email,
                            subject=subject,
                            text_body=content)
            conn.send(mail)
    except Exception:
        traceback.print_exc()
Пример #47
0
    def emailers(self, from_, to_, subject_, body_):
        envelope = Envelope(from_addr=from_,to_addr=to_,subject=subject_,text_body=body_)

        #TODO add password hashing
        smtpconn = SMTP(host='mail.nikitph.com',port=26,login='******',password=)
        print(smtpconn.is_connected)
        smtpconn.send(envelope)
Пример #48
0
    def close_spider(self, spider):
        analysis = spider.crawler.stats.get_stats()
        scrapyed_item = 0
        if analysis.get('item_scraped_count') != None:
            scrapyed_item = analysis['item_scraped_count']
        self.end_time = datetime.datetime.now()

        total_time = self.end_time - self.start_time
        text_body = '爬取职位' + str(scrapyed_item) + '个,用时' + str(total_time)
        envelope = Envelope(from_addr=(settings['FROM_ADDR'], u'Lagou爬虫'),
                            to_addr=(settings['TO_ADDR'], u'收件人'),
                            subject=u'今日爬虫完成',
                            text_body=text_body)
        envelope.send(settings['SMTP'],
                      login=settings['FROM_ADDR'],
                      password=settings['PASSWORD'],
                      tls=True)
Пример #49
0
def generate_email(subject, to_email, html):
    envelope = Envelope(
        from_addr=(Mail.login, Mail.title),
        to_addr=(u'{}'.format(to_email)),
        subject=subject,
        html_body=html,
    )
    return envelope
Пример #50
0
    def __init__(self, orimail, from_name=None, charset='utf-8'):
        self.charset = charset

        from_addr = orimail.get_addr('to')[0]
        to_addr = orimail.get_addr('from')
        cc_addr = orimail.get_addr('cc')

        if not from_name:
            from_name = from_addr

        self.envelope = Envelope(
            from_addr=(from_addr, from_name),
            to_addr=to_addr,
            subject="RE:" + orimail.subject,
        )

        self.add_addr(cc_addr=cc_addr)
Пример #51
0
def sendmail(to_address,
             subject,
             message,
             message_html=None,
             reply_to=None,
             cc=None,
             bcc=None):
    if 'SMTP_SERVER' not in app.config:
        app.logger.warn("SMTP_SERVER config is not set, ignoring sendmail...")
        return

    app.logger.info("sending mail to %s with subject %r", to_address, subject)

    headers = {}
    if reply_to:
        headers['Reply-To'] = reply_to

    if message_html:
        message_html = pynliner.fromString(message_html)

    if Unsubscribe.contains(to_address):
        app.logger.warn("%s is in the unsubscribed list. Not sending email.",
                        to_address)
        return

    envelope = Envelope(from_addr=app.config['FROM_ADDRESS'],
                        to_addr=to_address,
                        subject=subject,
                        text_body=message,
                        html_body=message_html,
                        headers=headers,
                        cc_addr=cc,
                        bcc_addr=bcc)
    server = app.config['SMTP_SERVER']
    port = app.config.get('SMTP_PORT', 25)
    username = app.config['SMTP_USERNAME']
    password = app.config['SMTP_PASSWORD']
    tls = app.config.get('SMTP_STARTTLS', False)

    envelope.send(host=server,
                  port=port,
                  login=username,
                  password=password,
                  tls=tls)
    app.logger.info("mail sent to %s with subject %r", to_address, subject)
Пример #52
0
def send_email(from_name, to_email, to_name, subject, content):
    smtp = SysOptions.smtp_config
    if not smtp:
        return
    envlope = Envelope(from_addr=(smtp["email"], from_name),
                       to_addr=(to_email, to_name),
                       subject=subject,
                       html_body=content)
    try:
        envlope.send(smtp["server"],
                     login=smtp["email"],
                     password=smtp["password"],
                     port=smtp["port"],
                     tls=smtp["tls"])
        return True
    except Exception as e:
        logger.exception(e)
        return False
Пример #53
0
    def send_report(self, to_addr):
        """
        通过邮箱发送报告
        """
        from_addr = ('*****@*****.**', '张磊')
        to_addr = to_addr
        subject = self.subject
        html_body = self.report

        client = Envelope(from_addr=from_addr,
                          to_addr=to_addr,
                          subject=subject,
                          html_body=html_body)

        client.send(MAIL_SERVER,
                    login=MAIL_LOGIN,
                    password=MAIL_PASSWD,
                    tls=False)
Пример #54
0
def send_email(to, subject, content):
    email_config = dj_email_url.config()

    if not email_config:
        return

    smtp_config = {'host': email_config['EMAIL_HOST'],
                   'port': email_config['EMAIL_PORT'],
                   'login': email_config['EMAIL_HOST_USER'],
                   'password': email_config['EMAIL_HOST_PASSWORD'],
                   'tls': email_config['EMAIL_USE_TLS']}

    envelope = Envelope(
        from_addr='*****@*****.**',
        to_addr=[to],
        subject=subject,
        text_body=content)

    envelope.send(**smtp_config)
Пример #55
0
def mail_welcome_email(user):
    subject = 'Welcome to Aleph'
    templatedir = dirname(dirname(dirname(abspath(__file__)))) + '/templates/'
    env = Environment(loader=FileSystemLoader(templatedir))

    html_body = env.get_template('welcome_mail.html').render(**{
        'user': user,
    })
    text_body = html2text.html2text(html_body)

    msg = Envelope(from_addr=(u'*****@*****.**', u"Aleph"),
                   to_addr=(user.email),
                   subject=subject,
                   text_body=text_body,
                   html_body=html_body)
    msg.send(app.config.get('MAIL_HOST'),
             login=app.config.get('MAIL_FROM'),
             password=app.config.get('MAIL_PASSWORD'),
             tls=True)
Пример #56
0
def sendEmail(receivers,content,subject,paths):
    
    sender,password=getEmailAcount() 
    server='smtp.'+(sender.split('.')[0]).split('@')[1]+'.com'  
    

    envelope = Envelope(
        from_addr=(sender, u'zonzely'),
        to_addr=receivers,
        subject=subject,
        text_body=content
    )

    for path in paths:
        envelope.add_attachment(path)
    

    
    envelope.send(server, login=sender,
                    password=password, tls=True)
Пример #57
0
def sendmail(to_address, subject, message, message_html=None, reply_to=None, cc=None, bcc=None):
    if 'SMTP_SERVER' not in app.config:
        app.logger.warn("SMTP_SERVER config is not set, ignoring sendmail...")
        return

    app.logger.info("sending mail to %s with subject %r", to_address, subject)
 
    headers = {}
    if reply_to:
        headers['Reply-To'] = reply_to

    if message_html:
        message_html = pynliner.fromString(message_html)

    if Unsubscribe.contains(to_address):
        app.logger.warn("%s is in the unsubscribed list. Not sending email.", to_address)
        return

    envelope = Envelope(
        from_addr=app.config['FROM_ADDRESS'],
        to_addr=to_address,
        subject=subject,
        text_body=message,
        html_body=message_html,
        headers=headers,
        cc_addr=cc,
        bcc_addr=bcc
    )
    server = app.config['SMTP_SERVER']
    port = app.config.get('SMTP_PORT', 25)
    username = app.config['SMTP_USERNAME']
    password = app.config['SMTP_PASSWORD']
    tls = app.config.get('SMTP_STARTTLS', False)

    envelope.send(
            host=server,
            port=port,
            login=username,
            password=password,
            tls=tls)
    app.logger.info("mail sent to %s with subject %r", to_address, subject)
Пример #58
0
def send(template, to, data):
    if template == 'registration_check':
        subject = u'New registration for {0.name}'.format(data['group'])
    elif template == 'confirm':
        subject = u'Please confirm your registration for lost.lu'
    elif template == 'registration_update':
        subject = u'Lost Registration Change'
    elif template == 'welcome':
        subject = u'Welcome to Lost, your registration is completed.'
    else:
        raise ValueError('Unsupported e-mail template: {}'.format(template))

    tmpl = _ENV.get_template('email/{}.txt'.format(template))
    content = tmpl.render(**data)
    mail = Envelope(
        from_addr=(u'*****@*****.**', u'Lost.lu Registration Team'),
        to_addr=to,
        subject=subject,
        text_body=content)
    LOG.debug('Sending email out to {!r} via localhost'.format(to))
    mail.send('localhost')
Пример #59
0
def mail_welcome_email(user):
    subject = "Welcome to Aleph"
    templatedir = dirname(dirname(dirname(abspath(__file__)))) + "/templates/"
    env = Environment(loader=FileSystemLoader(templatedir))

    html_body = env.get_template("comingsoon_mail.html").render(**{"user": user})
    text_body = html2text.html2text(html_body)

    msg = Envelope(
        from_addr=(u"*****@*****.**", u"Aleph"),
        to_addr=(user.email),
        subject=subject,
        text_body=text_body,
        html_body=html_body,
    )
    msg.send(
        app.config.get("MAIL_HOST"),
        login=app.config.get("MAIL_FROM"),
        password=app.config.get("MAIL_PASSWORD"),
        tls=True,
    )