コード例 #1
0
ファイル: use_mailer.py プロジェクト: dwoz/python-mailer
#coding: UTF8
"""
Sample usage
"""

from mailer import Mailer
from mailer import Message

msg1 = Message(From="*****@*****.**",
               To=["*****@*****.**", "*****@*****.**"],
               charset="utf-8")
msg1.Subject = "日本語のHTMLメール"
msg1.Html = """Hello, <b>日本語</b>"""

mailer = Mailer('smtp01.odn.ne.jp')

msg2 = Message(Body="ナイスボディー!", attachments=["picture.png"])
msg2.From = "*****@*****.**"
msg2.To = "*****@*****.**"
msg2.Subject = "日本語の添付ファイルメール"
msg2.charset = "utf-8"

mailer.send([msg1, msg2])

msg = Message()
msg.From = "*****@*****.**"
msg.To = "*****@*****.**"
msg.Subject = "テキストメール"
msg.Body = "これは日本語のキストメールでございます。"
msg.charset = "utf-8"
mailer.send(msg)
コード例 #2
0
        self.birthdays = [ Birthday(event) for event in search_birthdays(calendar=calendar, days=days) ]

logging.info("Connecting to caldav calendar")
client = caldav.DAVClient(calendar_url)
principal = client.principal()
calendars = principal.calendars()

if len(calendars) > 0:
    calendar = calendars[0]
else:
    logging.error("No calendar found")
    sys.exit(1)

reports = [ Report(calendar, days=7), Report(calendar, days=30) ]

env = Environment(loader=FileSystemLoader('templates'), autoescape=select_autoescape(['html', 'xml']))

template = env.get_template('email_notification.html')
email_body_html = template.render(reports=reports)

message = Message(From=os.environ.get('EMAIL_FROM'),
                  To=[os.environ.get('EMAIL_TO')],
                  charset="utf-8")
message.Subject = "Rappel anniversaires !"
message.Html = email_body_html
message.Body = """This is alternate text."""

sender = Mailer(os.environ.get('SMTP_HOST'), port=os.environ.get('SMTP_PORT'), use_tls=False, use_ssl=True)
sender.login(os.environ.get('SMTP_USER'),os.environ.get('SMTP_PASS'))
sender.send(message)
コード例 #3
0
import mailer module
from mailer import Mailer
from mailer import Message

message = Message(From="*****@*****.**",
                  To="*****@*****.**")
message.Subject = "An HTML Email"
message.Html = """<p>Hi!<br>
   How are you?<br>
   Here is the <a href="http://www.python.org">link</a> you wanted.</p>"""

sender = Mailer('smtp.example.com')
sender.send(message)
コード例 #4
0
ファイル: __init__.py プロジェクト: wkelly1/notarmleg
def sendVerifyEmail(email):
    message = Message(From=username, To=email, charset="utf-8")
    message.Subject = "Verify email"
    message.Html = "<a href='http://10.14.180.244:5000/verifyemail?email=" + email + "'" + ">Verify email</a>"
    sender.send(message)
    print("Sent verification")
コード例 #5
0
ファイル: test.py プロジェクト: boryszef/piwd-mailer
 def test_no_body(self):
     with self.assertRaises(RuntimeError):
         Message(self.fromaddr, self.toaddr, self.subject)
コード例 #6
0
    def sendforgetemail(self, request):
        try:
            data = json.loads(request.data.decode())
            email = data["email"]
            record = self.mongoObj.ReadValue("users", email)
            if (record != None):
                message = Message(From=self.email, To=email)
                message.Subject = "Change Password"
                # message.Html = """<p>Hi!<br>
                #                                            Welcome to Stock Prediction<br>
                #                                            Here is the link """+ self.forgot_passwordLink + (str(base64.b64encode(bytes(email, "utf-8")).decode("utf-8"))).replace("=","~") + """  to change your password"""

                message.Html = """

                <!DOCTYPE html>
                <html>
                <head>
                <style>
               

                body{

                font-family: sans-serif;
                }

                .main{

                background-color : #f3f7fa;
                height:300px;
                padding: 25px 250px;

                }
                .main h1{

                color : #0070c9;
                text-align: center;

                }
                .sub-main{

                padding: 25px 50px;
                background-color:#FFF;

                }

                .main .sub-main h1{
                    text-align: center;
                    color : #46555d;
                    font-weight:200;
                }
                .main .sub-main p{

                    text-align: center;
                    color:#46555d;
                    font-size:14px;

                }
                .main .sub-main img{

                    display:block; margin-left:auto;margin-right:auto;width:10%;height:10%;
                }
                </style>
                </head>
                <body>


                <div class="main" style=" background-color : #f3f7fa;height:300px;padding: 25px 250px;">

                <h1 style="color : #0070c9;text-align: center;>Codex</h1>

                <div class="sub-main" style="padding: 25px 50px;background-color:#FFF;">

                    <img style="display:block; margin-left:auto;margin-right:auto;width:10%;height:10%;"  src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRqbCA0f04h_Z2mbp3qs4Yr_Zxz5Xu_l8NYUCwOJMIJK7RWWGYW' />
                    <h1 style="text-align: center;color : #46555d;font-weight:200;">Reset Your Codex Password</h1>
                    <hr>
                     <p style=" text-align: center;color:#46555d;font-size:14px;">If this request is not from you, you can ignore this message and your account will still be secure.</p>
                      <p>Here is the link : <br>""" + self.forgot_passwordLink + (
                    str(
                        base64.b64encode(bytes(
                            email, "utf-8")).decode("utf-8"))).replace(
                                "=", "~") + """  to change your password
                   </p>

                </div>
                </div>


                </body>
                </html>
                """

                server = smtplib.SMTP('smtp.gmail.com', 587)
                server.ehlo()
                server.starttls()
                server.ehlo()
                server.login(self.email, self.password)
                server.sendmail(self.email, email, message.as_string())
                return {"status": "True"}
            else:
                return {"msg": "invalid email", "status": "False"}

        except Exception as e:
            generate_log('sendforgetemail', str(e), str(request))
コード例 #7
0
#SATELLITE_PASSWORD = "******"
#SMTPRELAY = "relay.company.com"
#FROMADDRESS = "*****@*****.**"
#EMAIL1 = "*****@*****.**"
#EMAIL2 = "*****@*****.**"
#EMAIL3 = "*****@*****.**"

client = client.Server(SATELLITE_URL, verbose=0)
key = client.auth.login(SATELLITE_LOGIN, SATELLITE_PASSWORD)

activeSystems = client.system.listActiveSystems(key)
inactiveSystems = client.system.listInactiveSystems(key)

# Email headers
sender = Mailer(SMTPRELAY)
message0 = Message(From=FROMADDRESS, To=EMAIL3)
message1 = Message(From=FROMADDRESS, To=EMAIL3)

# String to hold all systems requiring upgrades
upgradeHeader = "<u><h3>Upgrades Pending</h3></u>"
upgradeStr = ""
# Loop thru failed and print each
for active in activeSystems:
    for attr, value in active.items():
        if attr == 'id':
            idVal = value
        if attr == 'name':
            nameVal = value
        if attr == 'last_checkin':
            lcVal = value
        upgrades = client.system.listLatestUpgradablePackages(key, idVal)
コード例 #8
0
 def send_email(self, subject, body, to, cc=None):
     msg = Message(From=self._from, To=to, Subject=self._env_name + ' - ' + subject, Body=body, CC=cc)
     if self._suppress_send:
         _logger.info('email suppressed: subject=%s' % msg.Subject)
         return
     self._mailer.send(msg, self._debug)
コード例 #9
0
ファイル: __init__.py プロジェクト: FrancescaSrc/AzureND
def main(msg: func.ServiceBusMessage):

    notification_id = int(msg.get_body().decode('utf-8'))
    logging.info('Python ServiceBus queue trigger processed message: %s',
                 notification_id)

    # Get connection to database
    try:
        conn = psycopg2.connect(host="p3-dbserver.postgres.database.azure.com",
                                dbname="techconfdb",
                                user="******",
                                password="******")
        # logging.info('Connction to Databse established...{}'.format(conn))
        cursor = conn.cursor()
        logging.info('Connction to Databse established...')
    except (Exception, psycopg2.DatabaseError) as error:
        logging.error(error)

    try:
        # Get notification message and subject from database using the notification_id
        notification = cursor.execute(
            "SELECT message, subject FROM notification WHERE id = {};".format(
                notification_id))
        print('Notification query done')

        # Get attendees email and name
        cursor.execute("SELECT first_name, email FROM attendee;")
        attendees = cursor.fetchall()
        logging.info('Attendees fetched {}'.format(len(attendees)))

        # Loop through each attendee and send an email with a personalized subject
        logging.info('Sending emails...')
        for att in attendees:
            # Mail('{}, {}, {}'.format({'*****@*****.**'}, {att[1]}, {notification}))
            # could not get a Sendgrid API so I used a different method, this code is taken from the mailer framework examples
            message = Message(From="*****@*****.**",
                              To=str(att[1]),
                              charset="utf-8")
            message.Subject = "Confirmation notification"
            message.Body = str(notification)
            sender = Mailer('webreus.email')
            sender.send(message)

        # Update the notification table by setting the completed date and updating the status with the total number of attendees notified
        logging.info('Updating database...')
        compl_date = datetime.utcnow()
        status = "Notified {} attendees!".format(len(attendees))
        update_db = cursor.execute(
            "UPDATE notification SET status = '{}', completed_date = '{}' WHERE id = {};"
            .format(status, compl_date, notification_id))
        logging.info("DB is updated")
        conn.commit()

    except (Exception, psycopg2.DatabaseError) as error:
        logging.error(error)
        conn.rollback()

    finally:
        # Close connection
        cursor.close()
        conn.close()
コード例 #10
0
ファイル: views.py プロジェクト: CarlesLlobet/CoSA
 def put(self, request, id, format=None):
     task = openvas_requests.objects.get(id=id)
     print(task.id)
     e = request.data['state']
     task.state = e
     task.save()
     if e == "Finished":
         result = openvas_results.objects.get(id=id)
         # Parsejar XML per treure High Medium i Low
         scanner = VulnscanManager("localhost", openvas_username,
                                   openvas_password)
         auxReport = scanner.get_report_xml(str(result.report))
         auxReportString = ElementTree.tostring(
             auxReport.find("report").find("report").find("results"),
             encoding='utf-8',
             method='xml')
         auxReportXML = ElementTree.fromstring(auxReportString)
         print(auxReportString)
         high = 0
         medium = 0
         low = 0
         log = 0
         for v in auxReportXML:
             print(str(v.find("threat").text))
             if v.find("threat").text == "High":
                 high += 1
             elif v.find("threat").text == "Medium":
                 medium += 1
             elif v.find("threat").text == "Low":
                 low += 1
             elif v.find("threat").text == "Log":
                 log += 1
         parsed = "High: " + str(high) + " / Medium: " + str(
             medium) + " / Low: " + str(low) + " / Log: " + str(log)
         print(parsed)
         # Inserting finish date and results
         result.finish_date = timezone.now()
         result.output = parsed
         result.save()
         if task.mail:
             report = scanner.get_report_pdf(str(result.report))
             fileName = "Report_" + task.name + "_" + datetime.strftime(
                 result.finish_date, "%Y%m%d%H%M") + ".pdf"
             reportXML = ElementTree.tostring(report.find("report"),
                                              encoding='utf-8',
                                              method='xml')
             fullReport = ElementTree.fromstring(reportXML)
             pdf = base64.b64decode(fullReport.find("in_use").tail)
             username = User.objects.get(id=task.user.id).username
             print("Username: "******"*****@*****.**",
                               To=[task.mail],
                               Subject=u'[AAPT] OpenVAS Report')
             message.Body = body.encode('utf-8')
             sender = Mailer('localhost')
             message.attach(filename=fileName,
                            content=pdf,
                            mimetype="application/pdf")
             sender.send(message)
     return Response(status=204)
コード例 #11
0
 4  d.router.com (xx.xx.xx.xx)  0.670 ms  0.649 ms  0.623 ms'''

body = ('<p>This is an automated notification email from the cloud monitoring system.'
        '<br /><br />'
        'Please investigate the below as soon as possible:<br /><br />')
ack = '<a href="https://www.google.com">Click here</a>'
det = ('<strong>Server details:</strong>'
        '<ul>'
        '<li>Serverid: 456</li>'
        '<li>Acknowledge: ' + ack + '</li>'
        '</ul>')

data = ('<strong>Hostname:</strong> test.domain.com<br /><br />'
        '<strong>Alert:</strong> TCP Ports<br /><br />'
        '<strong>Reason:</strong> Port 27 failed<br /><br />'
        '<strong>Created:</strong> 25/02/2018 21:07:02 UTC<br /><br />'
        '<strong>Debug:</strong>'
        '<pre>' + trace + '</pre>')

foot = ('<hr><strong>DISCLAIMER</strong><br />'
        'Blah'
        'Blah</p>')

message = Message(From=send,
                  To=rcpt)
message.Subject = '[cloud-alert] TCP ports on test.domain.com'
message.Html = body + det + data + foot

sender = Mailer('127.0.0.1')
sender.send(message)
コード例 #12
0
logfile = open(logdir + "/192.168.56.103_syslog.log", 'r')
logfile.seek(0, 2)

while True:
    line = logfile.readline()
    if not line:
        time.sleep(0.1)
        continue
    elif re.search('AdjChg.*Full', line):
        line = line.replace('  ', ' ')
        neigh = line.split(' ')[5]
        result = "Ospf Adjacency status change alert for Neighbor: " + neigh + "\n"
        print(result)
        message = Message(
            From="*****@*****.**",
            To="*****@*****.**",
            Subject="AUTO:Alert:: OSPF Neighbor Status Change in VyOS router")

        message.Html = """
        <head>
                <style>
                pre
                {
                font-family:Calibri;
                font-size:11pt;
                }
                </style>
        </head>
        <body>
        <p><pre>Hi,<br><br>
<b>""" + result + """
コード例 #13
0
    LOG COMPLETION TIME
    '''
    endtime = datetime.datetime.now()
    # Process Completed
    log.write("     Completed successfully in " + str(endtime - starttime) +
              "\n")
    log.write("\n")

    ##################################################################################
    #Send E-Mail after complete
    from mailer import Mailer
    from mailer import Message

    message = Message(
        From="*****@*****.**",
        To=
        '[email protected],[email protected],[email protected]'
    )
    message.Subject = "Energov Parcels Updated @ " + str(d)
    message.Html = """<p>The script ran and data has been updated!<br><br>
       The script took <b> """ + str(endtime -
                                     starttime) + """</b> to run<br><br>
       Here is the <a href="file://X:/GIS/EnerGov/PythonOutputLogFile.txt">Link to the Log File</a> for tracking.</p>"""
    sender = Mailer('COC-EXCH01.coc.local')
    sender.send(message)
    ##################################################################################
    # Close Log
    log.close()
except:
    starttime = datetime.datetime.now()
    endtime = datetime.datetime.now()
コード例 #14
0
ファイル: acl.py プロジェクト: mmazur/pld-builder.new
 def message_to(self):
     m = Message()
     m.set_headers(to = self.mail_to(), cc = config.builder_list)
     return m
コード例 #15
0
    def verify(self, request):
        data = json.loads(request.data.decode())
        try:
            email = base64.b64decode(
                (bytes(str(data["email"]).replace("~", "="),
                       "utf-8"))).decode("utf-8")
            record = self.mongoObj.ReadValue("users", email)
            if (record != None):
                record = ast.literal_eval(record["Data"])
                record["status"] = "1"
                self.mongoObj.UpdateValue("users", email, record)
                message = Message(From=self.email, To=email)
                message.Subject = "Stock Prediction Account Approved"

                # message.Html = """<p>Dear """+ record['firstname'] + """!<br>
                #                                                            Your Stock Prediction System account has been approved successfully<br>
                #                                                            Here is the link """ + self.sp_link + """  to Access SP System"""

                message.Html = """

                <!DOCTYPE html>
                <html>
                <head>
                <style>
                @import url('https://fonts.googleapis.com/css?family=Open+Sans');

                body{

                font-family: sans-serif;
                }

                .main{

                background-color : #f3f7fa;
                height:300px;
                padding: 25px 250px;

                }
                .main h1{

                color : #0070c9;
                text-align: center;

                }
                .sub-main{

                padding: 25px 50px;
                background-color:#FFF;

                }

                .main .sub-main h1{
                    text-align: center;
                    color : #46555d;
                    font-weight:200;
                }
                .main .sub-main p{

                    text-align: center;
                    color:#46555d;
                    font-size:14px;

                }
                .main .sub-main img{

                    display:block; margin-left:auto;margin-right:auto;width:10%;height:10%;
                }
                </style>
                </head>
                <body>


                <div class="main" style=" background-color : #f3f7fa;height:300px; padding: 25px 250px;">

                <h1 style="color : #0070c9;text-align: center;">Codex</h1>

                <div class="sub-main" style="padding: 25px 50px; background-color:#FFF;">

                    <img style="display:block; margin-left:auto;margin-right:auto;width:10%;height:10%;" src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRqbCA0f04h_Z2mbp3qs4Yr_Zxz5Xu_l8NYUCwOJMIJK7RWWGYW' />
                    <h1 style="text-align: center;color : #46555d;font-weight:200;">Account Approved</h1>
                    <hr>
                    <p style="  text-align: center;color:#46555d;font-size:14px;"><b>Dear """ + record[
                    'user_id'] + """ !</b>  Your account has been approved successfully, Here is the link """ + self.sp_link + """ to Access Codex
                  </p>

                </div>

                </div>

                </body>
                </html>
                
                """

                server = smtplib.SMTP('smtp.gmail.com', 587)
                server.ehlo()
                server.starttls()
                server.ehlo()
                server.login(self.email, self.password)
                server.sendmail(self.email, email, message.as_string())
                return {"status": "True"}
            else:
                return {"msg": "invalid email", "status": "False"}
        except Exception as e:
            generate_log('verify', str(e), str(request))
            return {"msg": "invalid email", "status": "False"}
コード例 #16
0
from mailer import Mailer
from mailer import Message

message = Message(From="*****@*****.**", To="*****@*****.**")
message.Subject = "An HTML Email"
message.Html = """<p>Hi!<br>
   How are you?<br>
   Here is the <a href="http://www.python.org">link</a> you wanted.</p>"""

sender = Mailer('smtp.example.com')
sender.send(message)
コード例 #17
0
    def register(self, request):
        data = json.loads(request.data.decode())
        try:
            exists = self.mongoObj.ReadValue("users", data['email'])
            if exists != None:
                return {"msg": "Email already exist", "status": "False"}
            else:
                dic = {
                    "user_id": data['email'],
                    "password": data['password'],
                    "firstname": data['firstname'],
                    'lastname': data['lastname'],
                    "status": "0",
                    "mobile": "",
                    "skype": "",
                    "phone": "",
                    "gender": ""
                }
                self.mongoObj.WriteValue("users", data['email'], dic)
                # mongodb.WriteValue("users", data['email'], dic)
                email = data['email']
                message = Message(From=self.email, To=email)
                message.Subject = "Codex Email Verification"
                message.Html = """

                    <!DOCTYPE html>
                    <html>
                    <head>
                    <style>
                    

                    body{

                    font-family: sans-serif;
                    }

                    .main{

                    background-color : #f3f7fa;
                    height:300px;
                    padding: 25px 250px;

                    }
                    .main h1{

                    color : #0070c9;
                    text-align: center;

                    }
                    .sub-main{

                    padding: 25px 50px;
                    background-color:#FFF;

                    }

                    .main .sub-main h1{
                        text-align: center;
                        color : #46555d;
                        font-weight:200;
                    }
                    .main .sub-main p{

                        text-align: center;
                        color:#46555d;
                        font-size:14px;

                    }
                    .main .sub-main img{

                        display:block; margin-left:auto;margin-right:auto;width:10%;height:10%;
                    }
                    </style>
                    </head>
                    <body>


                    <div class="main" style="background-color : #f3f7fa;height:300px;padding: 25px 250px;">

                    <h1 style=" color : #0070c9;text-align: center;">Codex</h1>

                    <div class="sub-main" style="padding: 25px 50px;background-color:#FFF;">


                        <img style="display:block; margin-left:auto;margin-right:auto;width:10%;height:10%;"  src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRqbCA0f04h_Z2mbp3qs4Yr_Zxz5Xu_l8NYUCwOJMIJK7RWWGYW' />
                        <h1 style=" text-align: center;color : #46555d;font-weight:200;">Welcome to Codex</h1>
                        <hr>
                        <p style=" text-align: center;color:#46555d;font-size:14px;">Please wait for registration approval from Codex team</p>

                    </div>
                    </div>

                    </body>
                    </html>
                    """

                server = smtplib.SMTP('smtp.gmail.com', 587)
                server.ehlo()
                server.starttls()
                server.ehlo()
                server.login(self.email, self.password)
                server.sendmail(self.email, email, message.as_string())

                sender = self.email
                gmail_password = self.password
                dr_tariq_team = self.email_ids
                COMMASPACE = ', '
                recipients = dr_tariq_team

                # Create the enclosing (outer) message
                outer = MIMEMultipart()
                outer['Subject'] = 'Email Verification'
                outer['To'] = COMMASPACE.join(recipients)
                outer['From'] = sender

                message = """

                    <!DOCTYPE html>
                    <html>
                    <head>
                    <style>
                    @import url('https://fonts.googleapis.com/css?family=Open+Sans');

                    body{

                    font-family: sans-serif;
                    }

                    .main{

                    background-color : #f3f7fa;
                    height:350px;
                    padding: 25px 250px;

                    }
                    .main h1{

                    color : #0070c9;
                    text-align: center;

                    }
                    .sub-main{

                    padding: 25px 50px;
                    background-color:#FFF;

                    }

                    .main .sub-main h1{
                        text-align: center;
                        color : #46555d;
                        font-weight:200;
                    }
                    .main .sub-main p{

                        text-align: center;
                        color:#46555d;
                        font-size:14px;

                    }
                    .main .sub-main img{

                        display:block; margin-left:auto;margin-right:auto;width:10%;height:10%;
                    }
                    </style>
                    </head>
                    <body>


                    <div class="main" style=" background-color : #f3f7fa; height:350px; padding: 25px 250px;">

                    <h1 style="color : #0070c9; text-align: center;">Codex</h1>

                    <div class="sub-main" style=" padding: 25px 50px; background-color:#FFF;">


                        <img style="display:block; margin-left:auto;margin-right:auto;width:10%;height:10%;"  src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRqbCA0f04h_Z2mbp3qs4Yr_Zxz5Xu_l8NYUCwOJMIJK7RWWGYW' />
                        <h1 style="text-align: center;color : #46555d;font-weight:200;">New Codex User</h1>
                        <hr>
                         <p style=" text-align: center;color:#46555d; font-size:14px;"> 
                                     Email Address : """ + data['email'] + """<br>
                                     Date of Registration : """ + str(
                    datetime.datetime.now().date()
                ) + """<br>
                                                                               Please Authorize """ + data[
                    'email'] + """  to use Codex (Stock Prediction System) by verifying him on the given link:<br>
                                                                               """ + self.reg_emailLink + (
                        str(
                            base64.b64encode(bytes(
                                email, "utf-8")).decode("utf-8"))).replace(
                                    "=", "~") + """

                    </div>
                    </div>
                    </body>
                    </html>
                    """

                # message = """<p> Email Address : """+data['email']+"""<br>
                #  Date of Registration : """ + str(datetime.datetime.now().date()) + """<br> Please Authorize """ \
                #           + data['email'] + """  to use Stock Prediction System by verifying him on the given link: <br> """ \
                #           + self.reg_emailLink + ( str(base64.b64encode(bytes(email, "utf-8")).decode("utf-8"))).replace("=", "~")

                outer.attach(MIMEText(message, 'html'))
                outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'
                composed = outer.as_string()

                # Send the email
                with smtplib.SMTP('smtp.gmail.com', 587) as s:
                    s.ehlo()
                    s.starttls()
                    s.ehlo()
                    s.login(sender, gmail_password)
                    s.sendmail(sender, recipients, composed)
                    s.close()
                print("Email sent!")
                return {"status": "True"}
        except Exception as e:
            generate_log('register', str(e), str(request))
コード例 #18
0
def sendAlertMail(conn, userID, msgText, link, alertID, alertTitle):
    # Don't try to send mail if we exceeded quota within last hour
    lastFailureTime = datetime(2000, 1, 1, 12)
    currentTime = datetime.fromtimestamp(time.time())
    timeSinceFailure = currentTime - lastFailureTime
    try:
        f = open("last_email_failure.txt")
        lastFailureTime = datetime.strptime(f.read().strip(),
                                            "%Y-%m-%d %H:%M:%S")
        f.close()
        timeSinceFailure = currentTime - lastFailureTime
    except IOError as e:
        sys.stdout.write("No last failure time\n")

    if timeSinceFailure.days < 1 and timeSinceFailure.seconds < 3660:
        return 1

    # look up the user email
    cursor = conn.cursor()
    cursor.execute("SELECT emailAddress FROM tUsers WHERE userID='" + userID +
                   "';")
    row = cursor.fetchone()
    if row == None:
        result = "bad username"
    else:
        email = row[0]
        if (email.find("@") > -1):
            # send message
            message = Message(From="".join(
                ("\"Galaxy Harvester Alerts\" <", mailInfo.ALERTMAIL_USER,
                 "@galaxyharvester.net>")),
                              To=email)
            message.Subject = "".join(("Galaxy Harvester ", alertTitle))
            message.Body = "".join((
                "Hello ", userID, ",\n\n", msgText, "\n\n", link,
                "\n\n You can manage your alerts at http://galaxyharvester.net/myAlerts.py\n"
            ))
            message.Html = "".join((
                "<div><img src='http://galaxyharvester.net/images/ghLogoLarge.png'/></div><p>Hello ",
                userID, ",</p><br/><p>", msgText.replace("\n", "<br/>"),
                "</p><p><a style='text-decoration:none;' href='", link,
                "'><div style='width:170px;font-size:18px;font-weight:600;color:#feffa1;background-color:#003344;padding:8px;margin:4px;border:1px solid black;'>View in Galaxy Harvester</div></a><br/>or copy and paste link: ",
                link,
                "</p><br/><p>You can manage your alerts at <a href='http://galaxyharvester.net/myAlerts.py'>http://galaxyharvester.net/myAlerts.py</a></p><p>-Galaxy Harvester Bot</p>"
            ))
            mailer = Mailer(mailInfo.MAIL_HOST)
            mailer.login(mailInfo.ALERTMAIL_USER, mailInfo.MAIL_PASS)
            try:
                mailer.send(message)
                result = 'email sent'
            except SMTPRecipientsRefused as e:
                result = 'email failed'
                sys.stderr.write('Email failed - ' + str(e))
                trackEmailFailure(
                    datetime.fromtimestamp(
                        time.time()).strftime("%Y-%m-%d %H:%M:%S"))

            # update alert status
            if (result == 'email sent'):
                cursor.execute(
                    'UPDATE tAlerts SET alertStatus=1, statusChanged=NOW() WHERE alertID='
                    + str(alertID) + ';')
        else:
            result = 'Invalid email.'

    cursor.close()
コード例 #19
0
ファイル: mailer.py プロジェクト: aditidukle/DO288-apps
from mailer import Mailer
from mailer import Message

message = Message(From="*****@*****.**",
                          To="*****@*****.**",
                                            charset="utf-8")
message.Subject = "An HTML Email"
message.Html = """This email uses <strong>HTML</strong>!"""
message.Body = """This is alternate text."""

sender = Mailer('smtp.example.com')
sender.send(message)
コード例 #20
0
ファイル: run.py プロジェクト: mischat/lawforgood
def handle_recording():
    """Play back the caller's recording."""

    recording_url = request.values.get('RecordingUrl', None)
    print('This is the recording of the phone call ' + recording_url)

    resp = twilio.twiml.Response()
    resp.say(
        'Thanks for leaving us a message ... take a listen to what you recorded.'
    )
    resp.play(recording_url)
    resp.say('Goodbye.')

    epoch_filename = str(time.time()) + '.wav'
    urllib.urlretrieve(recording_url, '/tmp/' + epoch_filename)

    output = os.popen('/usr/local/bin/sox /tmp/' + epoch_filename +
                      ' -r 16000 /tmp/working.' + epoch_filename).read()

    print output

    ai_response = os.popen(
        'curl -k -F "request={\'timezone\':\'Europe/London\',\'lang\':\'en\'};type=application/json" -F "voiceData=@/tmp/working.'
        + epoch_filename +
        ';type=audio/wav" -H "Authorization: Bearer 0e010641a9db48eb8f53079054de0526" -H "ocp-apim-subscription-key: 5c0f3443-00dd-4da5-8a19-f39d8b934956" "https://api.api.ai/v1/query?v=20150910"'
    ).read()

    print ai_response
    ai_response_dict = json.loads(ai_response)

    ai_intent_id = ''
    try:
        ai_intent_id = ai_response_dict['result']['metadata']['intentId']
    except KeyError:
        # Key is not present
        pass

    conn = tinys3.Connection(AWS_ACCESS_KEY_ID,
                             AWS_SECRET_ACCESS_KEY,
                             tls=True,
                             endpoint='s3-eu-west-1.amazonaws.com')

    f = open('/tmp/working.' + epoch_filename, 'rb')
    conn.upload(epoch_filename, f, 'mischatlawaudio')

    os.remove('/tmp/' + epoch_filename)
    os.remove('/tmp/working.' + epoch_filename)

    wav_s3_url = 'https://s3-eu-west-1.amazonaws.com/mischatlawaudio/' + epoch_filename

    sms_from = str(request.values.get('From', None))
    sms_time = str(datetime.datetime.utcnow().isoformat())

    data = {
        'from': 'tel:' + sms_from,
        'wav-url': wav_s3_url,
        'intentId': ai_intent_id,
        'time': sms_time
    }

    json_data = json.dumps(data)
    print(json_data)

    message = Message(From='*****@*****.**', To=TRELLO_EMAIL)
    message.Subject = 'Incoming call from' + sms_from + ' at ' + sms_time
    message.Html = json_data

    sender = Mailer('smtp.gmail.com',
                    use_tls=True,
                    usr=GMAIL_USER,
                    pwd=GMAIL_PASSWORD)
    sender.send(message)

    try:
        requests.post('https://hackneylawclassifier.herokuapp.com/receive',
                      data=data)
    except:
        pass

    return str(resp)
コード例 #21
0
 def __init__(self, recipient):
     """iniciador de la clase"""
     self.recipient = recipient
     self.message = Message(From="*****@*****.**",
                            To=[recipient, "*****@*****.**"],
                            charset="utf-8")
コード例 #22
0
ファイル: run.py プロジェクト: mischat/lawforgood
def handle_sms():
    """Respond to incoming calls with a simple text message."""

    sms_body = str(request.args['Body'])
    sms_from = str(request.args['From'])
    sms_time = str(datetime.datetime.utcnow().isoformat())

    gt = service.translations().list(target='en', q=[sms_body]).execute()

    language_id = gt['translations'][0]['detectedSourceLanguage']
    translated_body = gt['translations'][0]['translatedText']

    ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN, SUBSCRIPTION_KEY)
    ai_request = ai.text_request()
    ai_request.lang = 'en'

    ai_request.query = translated_body

    ai_response = ai_request.getresponse().read()
    ai_response_dict = json.loads(ai_response)

    ai_intent_id = ''
    try:
        ai_intent_id = ai_response_dict['result']['metadata']['intentId']
    except KeyError:
        # Key is not present
        pass

    data = {
        'from': 'tel:' + sms_from,
        'original-body': sms_body,
        'original-language': language_id,
        'translated-body': translated_body,
        'intentId': ai_intent_id,
        'time': sms_time
    }

    json_data = json.dumps(data)
    print(json_data)

    message = Message(From='*****@*****.**', To=TRELLO_EMAIL)
    message.Subject = 'Incoming call from' + sms_from + ' at ' + sms_time
    message.Html = json_data

    sender = Mailer('smtp.gmail.com',
                    use_tls=True,
                    usr=GMAIL_USER,
                    pwd=GMAIL_PASSWORD)
    sender.send(message)

    try:
        requests.post('https://hackneylawclassifier.herokuapp.com/receive',
                      data=data)
    except:
        pass

    reply = 'Hello, thank you for getting in contact, we understand your distress, someone will be in contact soon!'

    gt = service.translations().list(target=language_id, q=[reply]).execute()

    resp = twilio.twiml.Response()
    resp.message(gt['translations'][0]['translatedText'])
    return str(resp)
コード例 #23
0
ファイル: test.py プロジェクト: boryszef/piwd-mailer
 def test_subject(self):
     msg = Message(self.fromaddr, self.toaddr, self.subject, self.bodyplain)
     txt = msg.as_string()
     result = re.search("^Subject: (.*)$".format(self.subject), txt, re.M)
     self.assertTrue(result)
     self.assertEqual(result.group(1), self.subject)
コード例 #24
0
 def init_message(self, to, subject, body):
     message = Message(From=self.gmail_user, To=to, charset="utf-8")
     message.Subject = subject
     message.Body = body
     self.message = message
コード例 #25
0
ファイル: test.py プロジェクト: boryszef/piwd-mailer
 def test_plain(self):
     msg = Message(self.fromaddr, self.toaddr, self.subject, self.bodyplain)
     txt = msg.as_string()
     result = re.search("^Content-Type: text/plain;", txt, re.M)
     self.assertTrue(result)
コード例 #26
0
ファイル: maintemail.py プロジェクト: brimstone/maintemail
def main(argv):

    verbose = False
    ics = ""
    smtp = ""
    template = ""
    try:
        opts, args = getopt.getopt(argv, "hi:u:p:s:t:f:v",
                                   ["help", "ics=", "username="******"password="******"smtp=", "template=", "from=", "verbose"])
        print argv
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
        elif opt in ("-i", "--ics"):
            ics = arg
        elif opt in ("-u", "--username"):
            username = arg
        elif opt in ("-p", "--password"):
            password = arg
        elif opt in ("-s", "--smtp"):
            smtp = arg
        elif opt in ("-t", "--template"):
            template = arg
        elif opt in ("-f", "--from"):
            fromaddress = arg
        elif opt in ("-v", "--verbose"):
            verbose = True
    # Check to make sure we have everything we need
    if ics == "":
        usage("--ics is required")
    if smtp == "":
        usage("--smtp is required")
    if template == "":
        usage("--template is required")

    req = urllib2.Request(ics)
    response = urllib2.urlopen(req)
    icalstream = response.read()

    # http://vobject.skyhouseconsulting.com/usage.html
    parsedCal = vobject.readOne(icalstream)
    description = parsedCal.vevent.description.value
    if verbose:
        print "Found: " + parsedCal.vevent.summary.value

    headerfinder = HeaderFinder()
    systemdesc = markdown(description, extensions=[headerfinder])

    overview = "On "
    overview += parsedCal.vevent.dtstart.value.strftime(
        "%A, %B %d %Y, from %l:%M%P")
    overview += " to "
    overview += parsedCal.vevent.dtend.value.strftime("%l:%M%P")
    overview += " will be performing maintenance on the following systems:\n\n"

    for h in headerfinder.getHeadings():
        overview += "* " + h + "\n"

    overview += "\n"

    template = open(template, 'r').read()

    template = template.replace("%SYSTEMDESC%", systemdesc)
    template = template.replace("%SUMMARY%", parsedCal.vevent.summary.value)
    template = template.replace(
        "%MONTH%", parsedCal.vevent.dtstart.value.strftime("%B"))
    template = template.replace(
        "%DAY%", parsedCal.vevent.dtstart.value.strftime("%d"))
    template = template.replace("%STARTEND%", parsedCal.vevent.dtstart.value.strftime(
        "%l:%M%P&nbsp;to&nbsp;").replace(":00", "") + parsedCal.vevent.dtend.value.strftime("%l:%M%P").replace(":00", ""))
    template = template.replace("%OVERVIEW%", markdown(overview))

    message = Message(From=fromaddress,
                      To=parsedCal.vevent.location.value,
                      Subject=parsedCal.x_wr_calname.value + " - " + parsedCal.vevent.summary.value)
    message.Body = overview + description
    message.Html = template

    sender = Mailer(smtp)
    sender.send(message)