def _build_message(self): """build mesage""" self._message = mailer.Message(charset="utf-8") self._message.From = self._usr self._message.To = self._to self._message.Subject = self._subject if not self._body_wrapper: self._body_wrapper = { 'body': self._body_convert(self._body), 'signature': self._signature, 'send_time': '', } for key, value in self._body_wrapper.items(): self._html_model = self._html_model.replace('<!--%s-->' % key, value) self._message.Html = self._html_model if self._attach: ext = os.path.splitext(self._attach)[-1] mtype = mimetypes.types_map[ext] self._message.attach(filename=self._attach, cid=None, mimetype=mtype, content=None, charset=None)
def send_cia_report(r, is_src=False): subject = 'DeliverXML' m = mailer.Message() if (len(config.bot_email) == 0): return m.set_headers(to=config.bot_email, subject=subject) m.set_header("Message-ID", "<*****@*****.**>" % r.id) m.set_header("X-mailer", "$Id$") m.set_header("X-builder", "PLD") # get header of xml message from file f = open(path.root_dir + '/PLD_Builder/cia-head.xml') m.write(f.read()) f.close() # write in iteration list and status of all processed files for b in r.batches: m.write('<package name="%s" arch="%s">\n' % (b.spec, b.branch)) if b.build_failed: m.write('<failed/>\n') else: m.write('<success/>\n') m.write('</package>\n') # get footer of xml message from file f = open(path.root_dir + '/PLD_Builder/cia-foot.xml') m.write(f.read()) f.close() # send the e-mail m.send()
def process(self, infos): """ En prenant les informations dans la configuration fournie, un mail est envoyé en se basant sur les informations contenues dans le paramètre subject = infos['title'] content = mise en forme avec make_xhtml :param infos: données à envoyer par mail :return: - """ self.logger.debug("Send Mail notification, infos = {}".format(infos)) if self.conf: for dest in self.conf['to']: message = mailer.Message(From=self.conf['from'], To=dest, charset="utf-8") message.Subject = infos['title'] message.Html = content.xml2text( content.make_xhtml(root=None, entry=infos), 'utf-8') sender = mailer.Mailer(host=self.conf['server'], port=self.conf['port'], usr=self.conf['user'], pwd=self.conf['passwd'], use_ssl=self.conf['usessl']) sender.send(message) self.logger.debug("Mail sent to {}".format(dest))
def _notify(self): if len(self.mailusers) == 0: return subj = "Your mailbox has reached a quota threshold" body = ( "I am sorry to inform you that your email account for:\n\n" "%s\n\n" "has reached a usage of over %s%%. Please take actions before your inbox gets full.\n\n" "Sincerely, your email server.") emailhostname = config['emailhostname'] msg = mailer.Message() msg.Subject = subj msg.charset = "utf-8" if config['emailbcc']: msg.BCC = config['emailbcc'] mail = mailer.Mailer() mail.host = smtp['host'] mail.use_tls = smtp['tls'] mail.port = smtp['port'] if smtp['user'] and smtp['pass']: mail.login(smtp['user'], smtp['pass']) print("Notifying above listed users...") for email in self.mailusers: if emailhostname == "auto" or emailhostname is None: emailhostname = email['email'].split("@")[1] msg.Body = body % (email['email'], config['threshold']) msg.From = "quota-notification@%s" % emailhostname if config['demo']: msg.To = config['demoemail'] else: msg.To = email['email'] mail.send(msg)
def render_email(report_file, server, users): """ Render the report """ output = StringIO.StringIO() report_data = {} with open(report_file) as infile: report_data = json.load(infile) _render('email.html', report_data, output) summary = [] keys = report_data['summary'].keys() keys.sort() for key in keys: if report_data['summary'][key] > 0: summary.append('%s %d' % (key.title(), report_data['summary'][key])) summary_str = ', '.join(summary) message = mailer.Message() message.From = 'nobody <*****@*****.**>' message.To = users message.Subject = report_data['info']['name'] + ' - ' + summary_str message.Html = output.getvalue() sender = mailer.Mailer(server) sender.send(message)
def runTest(self): ''' Tests basic functionality. ''' t = threading.Thread(target=self.helper) t.setDaemon(True) t.start() self.assertEqual(self.queue.get(.1), 'ready') time.sleep(.1) try: From = "*****@*****.**" To = ["*****@*****.**", "*****@*****.**"] mailer_inst = mailer.Mailer('127.0.0.1', 1025) msg = mailer.Message(From=From, To=To, charset="utf-8") mailer_inst.send(msg) peer, mailfrom, rcpttos, data = self.queue.get(.1) self.assertEqual(mailfrom, From) self.assertEqual(rcpttos, To) print data finally: try: raise asyncore.ExitNow() except asyncore.ExitNow: pass
def send_mail(address, username, link, template): if EMAIL_ENABLED: message = mailer.Message(From="*****@*****.**", To=address) message.Subject, message.Html = get_email_text(username, link, template) sender = mailer.Mailer(SMTP_ADDRESS, SMTP_PORT) sender.send(message)
def sendmail(trace): m = mailer.Message() m.set_headers(to=status.admin, cc="%s, %s" % (status.email, status.builder_list), subject="fatal python exception") m.write("%s\n" % trace) m.write("during: %s\n" % status.get()) m.send()
def test(self): message = mailer.Message() message.From = "*****@*****.**" message.To = "*****@*****.**" message.Subject = "My Test Python Email" message.Body = "Hello Jose" # open("letter.txt", "rb").read() my_mailer = mailer.Mailer("outgoing.verizon.net") my_mailer.send(message)
def process_message(msg): msg = json.loads(msg) message = mailer.Message() message.From = msg['From'] message.To = msg['To'] message.Subject = msg['Subject'] message.Body = msg['Body'] sender = mailer.Mailer('localhost') sender.send(message) print("Sent message at {}: {}\n".format(timestamp(), msg))
def flush_queue(dir): q = [] os.chdir(dir) for f in glob.glob(dir + "/*.desc"): d = read_name_val(f) if d != None: q.append(d) def mycmp(x, y): rc = cmp(x['Time'], y['Time']) if rc == 0 and x.has_key('Type') and y.has_key('Type'): return cmp(x['Type'], y['Type']) else: return rc q.sort(mycmp) error = None # copy of q remaining = q[:] for d in q: if not send_file(d['_file'], d['Target']): error = d continue if os.access(d['_file'] + ".info", os.F_OK): if not send_file(d['_file'] + ".info", d['Target'] + ".info"): error = d continue os.unlink(d['_file'] + ".info") os.unlink(d['_file']) os.unlink(d['_desc']) remaining.remove(d) if error != None: emails = {} emails[config.admin_email] = 1 pr = "" for src, msg in problems.items(): pr = pr + "[src: %s]\n\n%s\n" % (src, msg) for d in remaining: if d.has_key('Requester'): emails[d['Requester']] = 1 e = emails.keys() m = mailer.Message() m.set_headers(to=string.join(e, ", "), subject="[%s] builder queue problem" % config.builder) m.write("there were problems sending files from queue %s:\n" % dir) m.write("problems:\n") m.write("%s\n" % pr) m.send() log.error("error sending files from %s:\n%s\n" % (dir, pr)) return 1 return 0
def send_email_with_error(data: dict, error_traceback: str) -> str: """ Send an email to the user who committed the changes that an error has happened while processing their .jobs_done file. Returns the recipient of the email in case of success, otherwise will raise an exception (not sure which exceptions are raised by the underlying library). """ import mailer recipient = data['actor']['emailAddress'] project_key = data['repository']['project']['key'] slug = data['repository']['slug'] changes = [(change['ref']['id'], change['toHash']) for change in data['changes']] changes_msg = ', '.join( f'{branch.replace("refs/heads/", "")} @ {commit[:7]}' for (branch, commit) in changes) subject = f'JobsDone failure during push to {project_key}/{slug} ({changes_msg})' message = mailer.Message( From=os.environ['JD_EMAIL_FROM'], To=[recipient], # RTo=None, # Cc=self.cc, Subject=subject, charset='UTF-8', ) pretty_json = pprint.pformat(data) message.Body = EMAIL_PLAINTEXT.format(error_traceback=error_traceback, pretty_json=pretty_json) style = 'colorful' html = EMAIL_HTML.format( error_traceback_html=highlight(error_traceback, PythonTracebackLexer(), HtmlFormatter(style=style)), pretty_json_html=highlight(pretty_json, JsonLexer(), HtmlFormatter(style=style)), ) message.Html = html sender = mailer.Mailer( host=os.environ['JD_EMAIL_SERVER'], port=int(os.environ['JD_EMAIL_PORT']), use_tls=True, usr=os.environ['JD_EMAIL_USER'], pwd=os.environ['JD_EMAIL_PASSWORD'], ) sender.send(message) return recipient
def enviarCorreo(destinatarios='Pablo <*****@*****.**>', asunto='Correo Test', mensaje='Test', adjuntos=''): message = mailer.Message() nombreCorreo = '*****@*****.**' message.From = 'Diagnostico github <%s>'%nombreCorreo message.To = destinatarios message.Subject = asunto message.Html = mensaje if len(adjuntos) != 0: message.attach(adjuntos) mail = mailer.Mailer('vvv.ovh.net') mail.login(nombreCorreo, creaPalabra()) mail.send(message)
def send_email(errorcode, site, conf): """ Send email ONLY on error """ mailhost = conf.get(site, 'mailhost') msg = mailer.Message() msg.From = 'Backup <emailaddress>' msg.To = ['MySQL Backup Failures <emailaddress>'] msg.Subject = 'MySQL Backup Failures %s - %s' % (TIMESTAMP, site) msg.Body = 'Failure on %s - %s due to %s' % (site, conf.get( site, 'host'), errorcode) sender = mailer.Mailer(mailhost) # MAILHOST configured at top sender.send(msg)
def send_report(r, is_src=False): s_failed = ' '.join([b.spec for b in r.batches if b.build_failed]) s_ok = ' '.join([b.spec for b in r.batches if not b.build_failed]) upgrades_status = [b.upgraded for b in r.batches] if s_failed: s_failed = "ERRORS: %s" % s_failed if s_ok: s_ok = "OK: %s" % s_ok subject = '' if 'test-build' in r.flags: subject = 'TEST build ' if not is_src and 'upgrade' in r.flags and False in upgrades_status: subject = 'upgrade failed ' subject += ' '.join((s_failed, s_ok)).strip() m = mailer.Message() m.set_headers(to=r.requester_email, cc=config.builder_list, subject=subject[0:100]) if is_src: m.set_header("Message-ID", "<*****@*****.**>" % r.id) else: m.set_header("References", "<*****@*****.**>" % r.id) m.set_header("In-Reply-To", "<*****@*****.**>" % r.id) m.set_header("X-Entity-Ref-ID", "%s" % r.id) for b in r.batches: if b.build_failed and b.logfile == None: info = b.skip_reason elif b.build_failed: info = "FAILED" else: info = "OK" m.write("%s (%s): %s\n" % (b.spec, b.branch, info)) for b in r.batches: if b.logfile != None: info_from_log(b, m) for b in r.batches: if (b.is_command() or b.build_failed) and b.logfile != None: m.write("\n\n*** buildlog for %s\n" % b.spec) m.append_log(b.logfile) m.write("\n\n") m.send()
def send_email(errorcode): """ Send email ONLY in case of error condition """ # Email Settings host = 'hostname/ip' fromemail = 'SendName <*****@*****.**>' toemail = ['ToName <*****@*****.**>'] filestamp = time.strftime('%Y-%m-%d') subject = 'Rsync Backup Failures ' + filestamp msg = mailer.Message() msg.From = fromemail msg.To = toemail msg.Body = errorcode msg.Subject = subject sender = mailer.Mailer(host) sender.send(msg)
def send_email(to_address, subject, html_body): try: smtp = EmailService.create_smtp_server() message = mailer.Message(From=EmailService.__from_address, To=to_address, charset='utf-8') message.Subject = subject message.Html = html_body message.Body = html2text.html2text(html_body) if not EmailService.__is_debug_mode: print("Sending message (live!)") smtp.send(message) else: print("Skipping send, email is in dev mode.") except Exception as x: print("Error sending mail: {}".format(x))
def sendNotif(self): """ send out mail """ if not self._fw_updated or not send_email: return print("Sending notification email...") message = mailer.Message( From=email_from, To=re.split("\s{1,}|\n", email_to), Subject="BreachBlocker Notification" ) message.Body = "" for ip in self._new_ips: message.Body += "Host " + ip + " added to firewall droplist (" + ", ".join(self._ip_violations[ip]) + ")\n" sender = mailer.Mailer(mailhost) try: sender.send(message) except Exception: self.printError("Could not send email. Server problems?")
def job_email(user, reciever_emails): import mailer import datetime today = datetime.datetime.today().date() message = mailer.Message() message.From = '{user}@agl.com.au'.format(user=user) message.To = [reciever_emails] message.Subject = 'DR BYOT churned customer report {0}'.format(today) message.Body = '''Hi Team, On {dt_today}, you got this email. '''.format(dt_today=today) #message.attach("P:/New Energy/Churn Moveout Report/Input_file/Full VPPSA Site List V3.xlsx") sender = mailer.Mailer('aglsmtp05.agl.com.au') sender.send(message) return ()
def __init__(self, _from): self.message = mailer.Message() self.message.From = _from self.sender = mailer.Mailer('sms.cellinkgy.com')
import arcpy import csv import logging import datetime import time import mailer message = mailer.Message() message.From = '*****@*****.**' message.To = [ "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**" ] start = time.time() todayDate = datetime.date.today() d = str(todayDate).replace("-", "") logFile = r"\\admin\Admin\Groups\Parks\OS\GIS_TEAM\3_Resources\3_1_GIS_Team\3_1_8_Tracking\Data_Sync_Log\{}.log".format( d) csvFile = r'\\admin\Admin\Groups\Parks\OS\GIS_TEAM\3_Resources\3_1_GIS_Team\3_1_8_Tracking\Tracking___PRO_Data_Sourced_to_Editing_Database.csv' editingGDB = r'\\admin\Admin\Groups\Parks\OS\GIS_TEAM\1_GIS_Backups\1_1_Org_Data\Editing_1_1_Org_Data\JCOS\Jeffco_Open_Space_Managed_Data___EDITING.gdb' hubGDB = r'\\admin\Admin\Groups\Parks\OS\GIS\1_GIS_Hub\1_1_Org_Data\JCOS\Jeffco_Open_Space_Managed_Data.gdb' with open(csvFile, 'r') as f: reader = csv.reader(f) # Skip headers next(reader, None)
def check_email(user, sender_email, path_input, path_output, reciever_emails): t_preliminary_0 = time.time() # Set user. # Create engine. engine = create_engine('hana://{user}@hananode1:30015'.format(user=user)) df1 = pd.read_excel(path_input) df1.to_sql('vpp_churn_tom_from_python', engine, schema=user, if_exists='replace', dtype=types.NVARCHAR(length=255)) t_preliminary_1 = time.time() # Wait for 5 seconds #time.sleep(300) t_sql_code_0 = time.time() sql = """ SELECT A."Inverter", A."POD (NMI)" NMI, A."*approved BP*" BP_VPP, C.BUSINESSPARTNER BP_Active,C.COMPANY, min(CASE WHEN C.BUSINESSPARTNER IS NULL THEN '3_LeftVPP_New_NonAGL_Customer' WHEN C.BUSINESSPARTNER IS NOT NULL AND right(A."*approved BP*",9) <> right(C.BUSINESSPARTNER,9) and C.COMPANY != 'AGL' THEN '3_LeftVPP_New_NonAGL_Customer' WHEN C.BUSINESSPARTNER IS NOT NULL AND right(A."*approved BP*",9) <> right(C.BUSINESSPARTNER,9) THEN '4_LeftVPP_New_AGL_Customer' when C.BUSINESSPARTNER IS NOT NULL AND right(A."*approved BP*",9) = right(C.BUSINESSPARTNER,9) and C.COMPANY = 'PD' THEN '2_PowerDirect' ELSE '1_CURRENT' END) AS STATUS , CASE WHEN A."*approved BP*" IS NOT NULL THEN (SELECT max(MOVEINDATE) from "SP_CUSTOMER"."CIA_TheTruthAboutCustomer"D where right(D.BUSINESSPARTNER,9) = right(A."*approved BP*",9) and left(D.NMI,10)=left(A."POD (NMI)",10)) END VPP_MOVEIN , CASE WHEN A."*approved BP*" IS NOT NULL THEN (SELECT max(MOVEOUTDATE) from "SP_CUSTOMER"."CIA_TheTruthAboutCustomer"D where right(D.BUSINESSPARTNER,9) = right(A."*approved BP*",9) and left(D.NMI,10)=left(A."POD (NMI)",10)) END VPP_MOVEOUT ,CASE WHEN C.BUSINESSPARTNER IS NOT NULL THEN (SELECT max(MOVEINDATE) from "SP_CUSTOMER"."CIA_TheTruthAboutCustomer"D where right(D.BUSINESSPARTNER,9) = right(C.BUSINESSPARTNER,9)and left(D.NMI,10)=left(C.NMI,10)) END CURRENT_CUSTOMER_MOVEIN from (SELECT * from "{user}"."VPP_CHURN_TOM_FROM_PYTHON") A left join (SELECT * FROM "SP_CUSTOMER"."CIA_TheTruthAboutCustomer" B WHERE FUEL = 'ELEC' AND STATUS = 'ACTIVE' ) C on left(A."POD (NMI)",10) = left(C.NMI,10) GROUP BY A."Inverter", A."POD (NMI)", A."*approved BP*", C.NMI, C.BUSINESSPARTNER, C.TYPE, C.STATE, C.STATUS, C.COMPANY order by STATUS """.format(user=user) df2 = pd.read_sql(sql, engine) t_sql_code_1 = time.time() t_exportfile_code_0 = time.time() today = datetime.today().date() path_output_file = path_output + "/Full VPPSA Site List V3 outputfile {datetime}.xlsx".format( datetime=today) df2.to_excel(path_output_file) t_exportfile_code_1 = time.time() category_all = df2['nmi'].nunique() category_1 = df2.groupby('status')['nmi'].nunique()['1_CURRENT'] category_2 = df2.groupby('status')['nmi'].nunique()['2_PowerDirect'] category_3 = df2.groupby( 'status')['nmi'].nunique()['3_LeftVPP_New_NonAGL_Customer'] category_4 = df2.groupby( 'status')['nmi'].nunique()['4_LeftVPP_New_AGL_Customer'] ##log f = open("P:/New Energy/Churn Moveout Report/LOG_RUN.txt", "a+") f.write("%s, %s, %s, %s, %s\n" % (time.strftime("%x, %X"), len(df2), t_preliminary_1 - t_preliminary_0, t_sql_code_1 - t_sql_code_0, t_exportfile_code_1 - t_exportfile_code_0)) f.close() if category_2 + category_3 + category_4 > 0: message = mailer.Message() message.From = sender_email message.To = [reciever_emails] message.Subject = 'VPPSA move and Churn Report on {datetime}'.format( datetime=today) message.Body = '''Hi all, On {today_date}, from {category_all_num} unique NMIs in the VPP list, {category_2_num} NMIs are identified as 2_PowerDirect, {category_3_num} NMIs are identified as 3_VPPChurn_New_NonAGL_Customer , {category_4_num} NMIs are identified as 4_VPPChurn_New_AGL_Customer, and %s NMIs are identified as 1_Current. The report is attached to this email and can be find at {path_output_file_loc}. Definition of Flags: 1_CURRENT: The Business partner ID in the VPPSA list is the same as the current active Business partner ID at that NMI. 2_PowerDirect: The Business partner ID in the VPPSA list is the same as the current active Business partner ID at that NMI, but their COMPANY is power direct. 3_LeftVPP_New_NonAGL_Customer: The Business partner ID in the VPPSA list has left that NMI and the new occupant at that NMI is not an AGL customer. 4_LeftVPP_New_AGL_Customer: The Business partner ID in the VPPSA list has left that NMI, but the new occupant at that NMI is still an AGL customer. If you have any questions please let me know. Kind regards, Javad'''.format(today_date=today, category_all_num=category_all, category_2_num=category_2, category_3_num=category_3, category_4_num=category_4, category_1=category_1, path_output_file_loc=path_output_file) message.attach(path_output_file) sender = mailer.Mailer('aglsmtp05.agl.com.au') sender.send(message) return ()
# order = api_key, domain, csv with recipients and codes, and filepath to logfile _, api_key, domain, codes_file, log_file_path = argv sender = mailer.Sender(api_key=api_key, domain=domain, log_file_path=log_file_path) # open csv, create download code:recipient mapping inside this script pairs = {} with open(codes_file) as csvfile: read_csv = csv.reader(csvfile, delimiter=',') for row in read_csv: pairs[row[1]] = row[0] messages = [] for recipient, code in pairs.items(): messages.append( mailer.Message( # Just plug in your subject subject='cool subject', # desired from-address (where the email is coming from) from_address='*****@*****.**', to=recipient, # Email body - use {code} where you want to put the Bandcamp code body=f'Here is your damn {code}', )) for message in messages: sender.send(message) print(f'Script completed! Logs written to {log_file_path}')
def create(self, **kwargs): return mailer.Message(**kwargs)