コード例 #1
0
ファイル: mailer.py プロジェクト: CusinierIndian/Landing_IC
class Mailer:
    def __init__(self):
        self.mail = Mail(app)

    @async
    def sendAsyncMail(self, subject, senders, receivers, body, details):
        with app.app_context():
            with self.mail.connect() as conn:
                msg = Message(subject=subject,
                              recipients=receivers,
                              sender=senders)
                msg.html = render_template(body, details=details)
                conn.send(msg)

    @async
    def sendAsyncMailWithToken(self,
                               subject,
                               sender,
                               receivers,
                               link,
                               message,
                               body=None):
        print link
        with app.app_context():
            with self.mail.connect() as conn:
                msg = Message(subject=subject,
                              recipients=[receivers],
                              sender=sender)
                msg.html = render_template(body, link=link, message=message)
                conn.send(msg)
コード例 #2
0
    def execute(self, **kwargs):
        """
        Send email message
        """
        from . import actions
        with self.act_manager.app.app_context():
            if self.act_manager.app.debug == True:
                msg = Message(sender='*****@*****.**')
            for func in [getattr(self, aa) for aa in dir(self) if aa.startswith('get_')]:
                result = func(**kwargs)
                if result:
                    head, sep, tail = func.__name__.partition('_')
                    if tail == 'attachments':
                        for attachment in result:
                            msg.add_attachment(attachment)
                    else:
                        setattr(msg, tail, result)

            mail = Mail(self.act_manager.app)
            mail.connect()
            mail.send(msg)
            if self.log_mail:
                """
                Log email to a table with a timestamp. Note, for attachements, don't only log the
                file name and content_type, not the data.
                """
                pass
        return
コード例 #3
0
ファイル: app.py プロジェクト: Chandraxxx/File-Share-V.2
def helpCentre():
    if "uname" in session:
        if request.method == "POST":
            g_username = request.form['gmail_username']
            g_password = request.form['gmail_pw']
            to = request.form['to']
            subject = request.form['subject']
            message = request.form['message']

            app.config['MAIL_USERNAME'] = g_username
            app.config['MAIL_PASSWORD'] = g_password

            msg = Message(subject, sender=g_username, recipients=[to])
            msg.body = message

            try:
                mail = Mail(app)
                mail.connect()
                mail.send(msg)
                return render_template('help_centre.html', success="True")
            except:
                return render_template('help_centre.html', failed="True")
    else:
        return redirect(url_for('login'))
    return render_template('help_centre.html', failed="False", success="False")
コード例 #4
0
ファイル: others.py プロジェクト: CusinierIndian/Landing_IC
def sendMail(feedbackResponse):
    if feedbackResponse and feedbackResponse.get('notification').get(
            'status') == 'Success':
        mail = Mail(app)
        with app.app_context():
            with mail.connect() as conn:
                feedback = feedbackResponse.get('data').get('comments')[0].get(
                    'feedback')
                customerName = feedbackResponse.get('data').get('customerName')
                temp = {
                    'feedbackId':
                    feedbackResponse.get('data').get('comments')[0].get(
                        'feedbackId'),
                    'feedback':
                    feedback,
                    'customerName':
                    customerName
                }
                token = safeTimed.dumps(temp)
                link = 'http://127.0.0.1:5000/ic/approve/' + token
                modifyLink = 'http://127.0.0.1:5000/ic/modify/' + token
                msg = Message(subject='Feedback Approval',
                              recipients=['*****@*****.**'],
                              sender='*****@*****.**')
                msg.html = render_template('test.html',
                                           feedback=feedback,
                                           token=token,
                                           link=link,
                                           modifyLink=modifyLink,
                                           customerName=customerName)
                conn.send(msg)
コード例 #5
0
def registerUser():
    try:
        userDetails = request.get_json()
    except BadRequest as badRequest:
        badRequest.message
    else:
        from controllers.controllers import AuthenticationController
        response = AuthenticationController().registerUser(userDetails)
        if response:
            mail = Mail(app)
            with app.app_context():
                with mail.connect() as conn:
                    email = response.get('data').get('email')
                    temp = {
                        'id': response.get('data').get('id'),
                        'user': '******'
                    }
                    token = safeTimed.dumps(temp)
                    link = 'http://127.0.0.1:5000/ic/verifyemail/' + token
                    msg = Message(subject='verification link',
                                  recipients=[email],
                                  sender='*****@*****.**')
                    msg.html = '<a href=' + link + '> Click here to verify your email with Indian Cuisinier</a>'
                    conn.send(msg)

        return jsonify(response)
コード例 #6
0
def login():
    from app import mongo
    import bcrypt
    import datetime
    users = mongo.db.users
    log = users.find_one({'name': request.form['username']})
    print(log)
    pass_word = redis_client.__getitem__(request.form['username'])
    if pass_word is not None:
        if bcrypt.checkpw(request.form['pass0'].encode('utf-8'), pass_word):
            session['username'] = request.form['username']
            if users.update_one({"name": log['name']}, {"$set": {"updated_at": datetime.datetime.utcnow()}}):
                print(log['updated_at'])
            mail = Mail(app)
            try:
               with app.app_context():
                  with mail.connect() as conn:
                      message = 'Hello everyone how are you i hope every one are fine and thop.. happy UGADI...'
                      subject = "hello, %s" % '*****@*****.**'
                      msg = Message(recipients=['*****@*****.**'], body=message, subject=subject)
                      print(1)
                      conn.send(msg)
            except Exception as e:
                      return (str(e))
            return redirect(url_for('account'))
        return "Invalid username or password"
    return "User is not registered yet"
コード例 #7
0
def send_naggy_emails():
    mail = Mail(app)

    with mail.connect() as conn:
        for email in EmailAddress.query.all():
            if email.opted_into_nags:
                send_naggy_email(conn, email.email_address,
                                 email.github_username)
コード例 #8
0
def sendMail(msgExp):
    mail = Mail()
    with mail.connect() as conn:
        for item in msgExp:
            msg = Message(sender=MAIL_USERNAME,
                          subject=item['subject'],
                          recipients=[item['addr']],
                          html=item['msgHTML'])
            conn.send(msg)
コード例 #9
0
class Mailer:
    def __init__(self):
        self.mail = Mail(app)

    @async
    def sendAsyncMail(self, subject, senders, receivers, body, details):
        with app.app_context():
            with self.mail.connect() as conn:
                msg = Message(subject=subject,
                              recipients=receivers,
                              sender=senders)
                msg.html = render_template(body, details=details)
                conn.send(msg)
コード例 #10
0
    def send_contact_response_mail(cls, target, full_name, contact_query, response):
        current_app.config['MAIL_DEFAULT_SENDER'][0] = "Equipo de consultas Booken"
        mail = Mail(current_app)

        cls._prepare_contact_response(cls, "contact_response_template", data=dict(
                                                                            full_name=full_name,
                                                                            contact_query=contact_query,
                                                                            response=response
                                                                        ))
        msg = Message("Consulta Booken",
                      recipients=[target],
                      html=cls.parser)

        with mail.connect() as connection:
            connection.send(msg)
コード例 #11
0
def instructor_action_distribute():
    course_id = request.args.get("course_id")
    assignment_id = request.args.get("assignment_id")

    current_assignment, recipients = instructor_action.distribute(assignment_id)

    app.config.update(MAIL_SETTINGS)
    mail = Mail(app)
    with mail.connect() as conn:
        for recipient in recipients:
            msg = Message("Your Assignment Has Been Reviewed", sender = ("Project Discourse", "*****@*****.**"), recipients = [recipient])
            msg.html = "Hello - <br> Your submission for Assignment: " + current_assignment.get_name() + " has been reviewed by your instructor. Please login to Project Discourse to view your feedback."
        conn.send(msg)

    href = '/instructor/' + str(course_id) + "/" + str(assignment_id)
    return redirect(href)
コード例 #12
0
    def send_ticket_order_mail(cls, target, full_name, order: OrdersModel):
        current_app.config['MAIL_DEFAULT_SENDER'][0] = "Pedido de Booken"
        mail = Mail(current_app)

        cls._prepare_ticket_response(cls, "ticket_response_template", data=dict(full_name=full_name))
        msg = Message("Pedido de Booken",
                      recipients=[target],
                      html=cls.parser)

        cls._prepare_ticket_pdf(cls, "ticket_pdf_template", order)
        msg.attach("ticket.pdf", "ticket/pdf", cls.pdf.getvalue())

        with mail.connect() as connection:
            connection.send(msg)

        cls.pdf.close()
コード例 #13
0
def sendAsyncEmail(message, subject, users):
    mail = Mail(app)
    with app.app_context():
        with mail.connect() as conn:
            for email in users:
                token = safeTimed.dumps(email)
                # link = url_for('unsubscribe', token=token, _external=True)
                link = 'http://127.0.0.1:5000/ic/admin/unsubscribe/' + token
                msg = Message(subject=subject,
                              recipients=[email],
                              body=message,
                              sender='*****@*****.**')
                #msg.html = '<a href='+ link +'> Unsubscribed</a>'
                msg.html = render_template('test.html')
                conn.send(msg)
    return 'message sent'
コード例 #14
0
def instructor_action_remind():
    course_id = request.args.get("course_id")
    assignment_id = request.args.get("assignment_id")

    current_assignment, recipients = instructor_action.remind(assignment_id)

    app.config.update(MAIL_SETTINGS)
    mail = Mail(app)
    with mail.connect() as conn:
        for recipient in recipients:
            msg = Message("Reminder: An Assignment Awaits Your Submission", sender = ("Project Discourse", "*****@*****.**"), recipients = [recipient])
            msg.html = "Hello - <br> Your instructor would like to remind you that Assignment: " + current_assignment.get_name() + " is due " + current_assignment.get_due_time().strftime("%Y-%m-%d") + " " + current_assignment.get_due_time().strftime("%H:%M") + ". Please login to Project Discourse to turn in your submission."
        conn.send(msg)

    href = '/instructor/' + str(course_id) + "/" + str(assignment_id)
    return redirect(href)
コード例 #15
0
def students(app, students, company):
    mail = Mail(app)
    with mail.connect() as conn:
        for student in students:
            print(student.get('name'))
            message = 'Hello %s,<br>The TPO wants to inform you that since you have a pointer greater than %d you are eligbile to \
                 sit for the %s test. The Test for the company is going to be held on %s.\
                <br> if you wish to sit for the company please click on the link below your information(as in placment portal) would \
                be automatically sent to the company<br> <a href=\"http://127.0.0.1:5000/%d/%s/entry\">CLICK HERE TO APPLY</a>' % (
                student.get('name'), company.get('criteria'),
                company.get('company'), company.get('start_date'),
                student.get('id'), company.get('company'))

            subject = "Congratulations, %s you are eligible to sit for %s" % (
                student.get("name"), company.get("company"))
            msg = Message(recipients=[student.get("email")],
                          html=message,
                          sender='*****@*****.**',
                          subject=subject)

            conn.send(msg)
コード例 #16
0
def mail(token):
    if (token != app_token):
        abort(404)

    mail = Mail(app)
    url = "https://abhishekbalam.xyz/newsletter/latest.json"
    data = requests.get(url).json()

    users = db.getusers()
    users = users.items()

    response = 'Newsletter Sent to the following emails:<br><ol>'
    for user in users:
        if ('1' in user[1]):
            response += '<li>' + user[0] + '</li>'

    response += '</ol>'

    with mail.connect() as conn:
        for user in users:

            status = str(user[1].split(',')[2])

            if (status == '1'):
                lname = str(user[1].split(',')[1])
                fname = str(user[1].split(',')[0])
                email = user[0]
                subject = 'Abhishek Balam\'s Newsletter for ' + data['date']
                msg = Message(subject,
                              sender=('Abhishek Balam',
                                      '*****@*****.**'),
                              recipients=[email])
                msg.html = render_template('newsletter.html',
                                           data=data,
                                           name=fname,
                                           email=email)
                mail.send(msg)
                conn.send(msg)

    return response
コード例 #17
0
class EmailService:
    mail: Mail

    def __init__(self):
        self.mail = Mail(current_app)

    @property
    def is_valid(self):
        email = os.environ.get('MAIL_USERNAME') is not None
        email_password = os.environ.get('MAIL_PASSWORD') is not None
        return email and email_password

    def send(self, recipient: str, subject: str, content: str):
        msg = Message(recipients=[recipient], html=content, subject=subject)
        self.mail.send(msg)

    def send_bulk(self,
                  recipients: List[str],
                  subject: str,
                  content: str,
                  fills: List[Tuple] = None):
        if fills is not None:
            assert len(recipients) == len(fills)

        with self.mail.connect() as conn:
            for recip_idx in range(len(recipients)):
                recipient = recipients[recip_idx]
                if fills is not None:
                    fill = fills[recip_idx]
                    message = content % fill
                else:
                    message = content
                msg = Message(recipients=[recipient],
                              html=message,
                              subject=subject)
                conn.send(msg)
                yield message
コード例 #18
0
ファイル: app.py プロジェクト: freedPanda/CapstoneDeployable
mail_settings = {
    "MAIL_SERVER": 'smtp.gmail.com',
    "MAIL_PORT": 465,
    "MAIL_USE_TLS": False,
    "MAIL_USE_SSL": True,
    "MAIL_USERNAME": os.environ['EMAIL_USER'],
    "MAIL_PASSWORD": os.environ['EMAIL_PASSWORD']
}

app.config['WTF_CSRF_ENABLED'] = True

CURR_USER_KEY = 'username'

app.config.update(mail_settings)
mail = Mail(app)
mail.connect()

connect_db(app)

app.config['SECRET_KEY'] = "SECRET!"
debug = DebugToolbarExtension(app)
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False


@app.before_request
def add_user_to_g():
    """If we're logged in, add curr user to Flask global."""

    if CURR_USER_KEY in session:
        g.user = Admin.query.filter_by(username=session[CURR_USER_KEY])
        #the following code will make sure the admin is automatically logged out after
コード例 #19
0
ファイル: server.py プロジェクト: debbie-a/pokemon-project
def poke_selfie():
    pokemon_name = request.args.get('pokemon')
    email = request.args.get('email')

    if not pokemon_name or not email:
        return render_template('/poke_selfie2.html',
                               name="invalid input",
                               the_url=''), 400

    # path to downlods folder in pc where server is running
    selfie_picture = Image.open("C:\\Users\\1\\Downloads\selfie.png")

    try:
        # path to folder with all pokemon images
        pokemon_path = os.path.join("images", f'{pokemon_name}.jpg')
        pokemon_picture = Image.open(pokemon_path)

        # path to folder where the ready pokeSelfies are stored
        pokeSelfie_path = os.path.join("pokieSelfies", f'{email}.png')
        embed_pictures(selfie_picture, pokemon_picture, pokeSelfie_path)

        # delete selfie from downlowds
        os.remove("C:\\Users\\1\\Downloads\selfie.png")

    except FileNotFoundError:
        return render_template('/poke_return_page.html',
                               name="invalid pokemon to snap a selfie with",
                               the_url=''),

    # configuration of mail
    app.config['MAIL_SERVER'] = 'smtp.gmail.com'
    app.config['MAIL_PORT'] = 465
    app.config['MAIL_USERNAME'] = '******'
    # keep in seperate module my passworrd for security reasons...
    app.config['MAIL_PASSWORD'] = local_settings.MAIL_PASSWORD
    app.config['MAIL_USE_TLS'] = False
    app.config['MAIL_USE_SSL'] = True
    mail = Mail(app)

    try:

        with mail.connect() as conn:
            message = f"this is your very cool pokeSelfie with {pokemon_name}"
            subject = "PokeSelfie"

            msg = Message('PokieSelfie',
                          sender='*****@*****.**',
                          recipients=[email])
            msg.body = f"Your selfie from PokeSelfie with {pokemon_name}"
            with app.open_resource(pokeSelfie_path) as fp:
                msg.attach(f"pokeSelfieWith_{pokemon_name}.png", "image/png",
                           fp.read())

            conn.send(msg)
            # delete pokeSelfie from local storage
            os.remove(pokeSelfie_path)

            return render_template('/poke_return_page.html',
                                   name="Your PokeSelfie is on its way",
                                   the_url=''), 200

    except ConnectionRefusedError:
        return render_template('/poke_return_page.html',
                               name="error sending email",
                               the_url=''), 505
コード例 #20
0
def double_out():
    while (True):
        mariadb_connection = mariadb.connect(user='******',
                                             password='',
                                             database="fastravel")
        cur = mariadb_connection.cursor()

        outQ = """SELECT userid FROM AptMail"""
        cur.execute(outQ, )
        users = cur.fetchall()
        #print(cities)
        for user in users:
            print(user)
            print(user[0])
            #result = request.form
            #userid = result['userid']
            cur.callproc('apartment_query', (str(user[0]), ))
            exist = cur.stored_results()
            for x in exist:
                data = x.fetchall()
            with app.app_context():
                mail = Mail(app)
                with mail.connect() as conn:
                    for results in data:
                        email = results[0]
                        msg = Message("Match found with " + user[0],
                                      recipients=[
                                          str(results[0]),
                                          "*****@*****.**"
                                      ])
                        outStr = "Email: " + user[
                            0] + "\nDestination: " + results[
                                1] + "\n\nDeparture Date: " + str(
                                    results[3]
                                ) + "\nDeparture Flight Price: " + str(
                                    results[4]
                                ) + "\nDeparture Airline: " + results[
                                    5] + "\n\nReturn Date: " + str(
                                        results[6]
                                    ) + "\nReturn Flight Price: " + str(
                                        results[7]
                                    ) + "\nReturn Airline: " + results[
                                        8] + "\nTotal Price: " + str(
                                            results[9]) + "\nWeather: " + str(
                                                results[10]
                                            ) + "\n\nPlease contact " + user[
                                                0] + " to confirm"
                        msg.body = outStr
                        mail = Mail(app)
                        conn.send(msg)

            query = "SELECT * FROM AptMail where userid = %s"
            cur.execute(query, (user[0], ))
            exist = cur.fetchall()
            if (cur.fetchall != []):
                query = """delete from AptMail where userid = %s"""
                cur.execute(query, (user[0], ))
                mariadb_connection.commit()
        cur.close()
        mariadb_connection.close()
        time.sleep(60)
コード例 #21
0
ファイル: mail_sender.py プロジェクト: ktomkow/FlatMatesFood
def send_many(messages: list):
    app = current_app
    mail = Mail(app)
    with mail.connect() as conn:
        for message in messages:
            conn.send(message)
コード例 #22
0
ファイル: send.py プロジェクト: dazcona/code-assistant
subject_encoded_emojis = '=?utf-8?Q?=F0=9F=A4=96_=F0=9F=91=BE_%s?=' % (subject)

# STUDENTS
students = db.students.find(
    {'status': {
        '$in': [0]
    }},
    {
        'email': 1,
        'token': 1
    },
)

# Emails in bulk
with app.app_context():
    with mail.connect() as conn:
        for student in students:
            email = student['email']
            token = student['token']
            content = render_template('mail.html', token=token)
            recipients = [email]
            msg = Message(
                subject=subject_encoded_emojis,
                sender=sender,
                #cc=cc,
                bcc=bcc,
                recipients=recipients,
                html=content)
            print("Sending mail to %s" % (email))
            conn.send(msg)
            print("Mail sent")