def welcome_email(user_email, wallet, uuid): if user_email is not None: msg = MIMEMultipart('alternative') msg['From'] = email_from msg['To'] = user_email msg['Subject'] = "Account Created: Welcome to Omniwallet" text = ( 'Welcome To Omniwallet!\n' '\n' 'You are receiving this email because your address was entered during the signup process.\n' 'If you did not signup for this account please contact our support department using the information at the bottom of this email.\n' '\n' 'Thank you for creating a new wallet and choosing to join the exciting world of cryptocurrency.\n' 'While we know you are eager to get started, this email contains important information about your new Omniwallet.\n' 'So please take a moment to read through it completely.\n' '\n' 'Your Wallet Login Details' 'This is your Wallet ID: ' + str(uuid) + '\n' 'Never share your Wallet ID or Password with anyone. Be sure to keep them safe and stored separately for security.\n\n' 'This is your unique Login Link: https://' + str(email_domain) + '/login/' + str(uuid) + '\n' 'Bookmark this, you can use it to login directly to your Omniwallet with your password.\n' '\n' 'Omniwallet NEVER STORES Your Password.\n' 'This means you need your password to access your wallet and the private keys within.\n' 'If you lose or forget your password there is nothing we can do to recover it.\n' 'This may result in the loss of funds in any wallet addresses which have not been Backed Up!\n\n' 'Please, Please, Please Keep Your Password Safe!\n' '\n' 'Important Information On Backing Up Your Wallet' 'If you lose or forget your password the only thing you can use to recover your funds is a Wallet Backup.\n' 'You should create a new backup any time you make a change to your wallet (add/remove an address).\n' 'Remove the old backup only after you have confirmed the contents of the new backup are complete.\n' 'On the "My Addresses" page you can export a backup of your wallet under the "Wallet Options" button.\n' 'This backup file contains every address and private key (if known) for the addresses in your wallet at the time of backup.\n' 'Store your backup file in a secure place. Anyone with access to this file has access to your funds.' '\n' 'Thank you for taking the time to read this introduction. \n' 'This as well as many more questions/answers are available on our Knowledge Base: http://support.omniwallet.org \n' 'If you have any questions please feel free to reach out to us using the information on our Contact Us page: https://' + str(email_domain) + '/about/contact \n' '\n' 'Sincerely, \n The Omniwallet Team') html = ( '<html><head></head><body style="background-color:rgba(234, 235, 236, 0.43);">' '<img src="https://' + str(email_domain) + '/assets/img/logo.png"><h1><font color="#034F92">Welcome To Omniwallet!</font></h1>' '<p>' 'You are receiving this email because your address was entered during the signup process.<br>' 'If you did not signup for this account please contact our support department using the information at the bottom of this email.<br>' '</p>' '<p>' 'Thank you for creating a new wallet and choosing to join the exciting world of cryptocurrency.<br>' 'While we know you are eager to get started, this email contains important information about your new Omniwallet.<br>' 'So please take a moment to read through it completely.<br>' '</p>' '<h2><font color="#034F92">Your Wallet Login Details</font></h2>' '<p>' 'This is your <b>Wallet ID:</b> ' + str(uuid) + '<br>' 'Never share your Wallet ID or Password with anyone. Be sure to keep them safe and stored separately for security.<br><br>' 'This is your unique <b>Login Link:</b> <a href="https://' + str(email_domain) + '/login/' + str(uuid) + '">https://' + str(email_domain) + '/login/' + str(uuid) + '</a><br>' 'Bookmark this, you can use it to login directly to your Omniwallet with your password.<br>' '</p><p>' '<strong>Omniwallet Never Stores Your Password.</strong><br>' 'This means you need your password to access your wallet and the private keys within.<br>' 'If you lose or forget your password there is nothing we can do to recover it.<br>' 'This may result in the loss of funds in any wallet addresses which have not been Backed Up!<br><br>' '<strong>Please, Please, Please Keep Your Password Safe!</strong><br>' '</p>' '<h2><font color="#034F92">Important Information On Backing Up Your Wallet</font></h2>' '<p>' 'If you lose or forget your password the only thing you can use to recover your funds is a Wallet Backup.<br>' 'You should create a new backup any time you make a change to your wallet (add/remove an address).<br>' 'Remove the old backup only after you have confirmed the contents of the new backup are complete.<br>' 'On the "My Addresses" page you can export a backup of your wallet under the "Wallet Options" button.<br>' 'This backup file contains every address and private key (if known) for the addresses in your wallet at the time of backup.<br>' '<strong>Store your backup file in a secure place. Anyone with access to this file has access to your funds.</strong>' '</p><p>' 'Thank you for taking the time to read this introduction. <br>' 'This as well as many more questions/answers are available on our <a href="http://support.omniwallet.org">Knowledge Base</a><br>' 'If you have any questions please feel free to reach out to us using the information on our <a href="https://' + str(email_domain) + '/about/contact">Contact Us</a> page.<br>' '</p><p>' 'Sincerely, <br><i> The Omniwallet Team</i>' '</p></body></html>') part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') msg.attach(part1) msg.attach(part2) if config.WELCOMECID is not None: msg.add_header('X-Mailgun-Tag', config.WELCOMECID) if config.AWSCID is not None: msg.add_header('X-SES-CONFIGURATION-SET', config.AWSCID) #wfile = MIMEBase('application', 'octet-stream') #wfile.set_payload(wallet) #Encoders.encode_base64(wfile) #wfile.add_header('Content-Disposition', 'attachment', filename=uuid+'.json') #msg.attach(wfile) smtp = smtplib.SMTP(config.SMTPDOMAIN, config.SMTPPORT) if config.SMTPUSER is not None and config.SMTPPASS is not None: if config.SMTPSTARTTLS: smtp.starttls() smtp.login(config.SMTPUSER, config.SMTPPASS) smtp.sendmail(email_from, user_email, msg.as_string()) smtp.close()
def mail(to, subject, text, attach, prioflag1, prioflag2): msg = MIMEMultipart() # From msg['From'] = user1 # To msg['To'] = to # Add Priority msg['X-Priority'] = prioflag1 msg['X-MSMail-Priority'] = prioflag2 # Subject tag msg['Subject'] = subject # specify if its html or plain # body message here body_type=MIMEText(text, "%s" % (message_flag)) # any attachments msg.attach(body_type) # define connection mimebase part = MIMEBase('application', 'octet-stream') part.set_payload(open(attach, 'rb').read()) # base 64 encode message mimebase Encoders.encode_base64(part) # add headers part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(attach)) msg.attach(part) # define connection to smtp server mailServer = smtplib.SMTP(smtp, int(port)) mailServer.ehlo() # send ehlo to smtp server if sendmail == 0: if email_provider == "gmail": mailServer.ehlo() # start TLS for gmail sometimes needed try: mailServer.starttls() except: pass mailServer.ehlo() if counter == 0: try: if email_provider == "gmail": try: mailServer.starttls() except: pass mailServer.ehlo() mailServer.login(user, pwd) #thread.start_new_thread(mailServer.sendmail,(user, to, msg.as_string())) mailServer.sendmail(user, to, msg.as_string()) except Exception, e: PrintError("Unable to deliver email. Printing exceptions message below, this is most likely due to an illegal attachment. If using GMAIL they inspect PDFs and is most likely getting caught.") raw_input("Press {return} to view error message.") print str(e) try: mailServer.docmd("AUTH LOGIN", base64.b64encode(user)) mailServer.docmd(base64.b64encode(pwd), "") except Exception,e: print str(e) try: mailServer.login(user, pwd) thread.start_new_thread(mailServer.sendmail,(user, to, msg.as_string())) except Exception, e: #print "\n It appears your password was incorrect.\nPrinting response: "+(str(e)) ReturnContinue()
def send_email(body): print "Configure email with body:" + body body_json=json.loads(body) costumers = [] deals = [] size = 0 for item in body_json: customer = base64.b64decode((item["key"])) if customer.startswith('"') and customer.endswith('"'): customer = customer[1:-1] costumers.append(customer) deal = base64.b64decode((item["value"])) if deal.startswith('"') and deal.endswith('"'): deal = deal[1:-1] deals.append(deal) size += 1 text = "" for i in range(0, size): text = text + "Customer name: " + costumers[i] + "<\n>" text = text + "Deal size: " + deals[i] + "<\n>" # Above text in table format table_text = "" for i in range(0, size): table_text += "<tr>" table_text += "<td width='50%'>" + costumers[i] + "</td>" table_text += "<td width='50%'>" + deals[i] + "</td>" table_text += "</tr>" me = "*****@*****.**" you = "*****@*****.**" msg = MIMEMultipart('related') msg['Subject'] = 'Bell Project deal notification' msg['From'] = me msg['To'] = you # Encapsulate the plain and HTML versions of the message body in an # 'alternative' part, so message agents can decide which they want to display. msgAlternative = MIMEMultipart('alternative') msg.attach(msgAlternative) msgText = MIMEText(text) msgAlternative.attach(msgText) ##### Image text greetMsg = get_greeting_msg() image_txt = \ ''' <b>''' + greetMsg + ''' </b><br><br><img src="cid:image1"><br><br><br> <b> Here is the latest customer deal: </b><br><br> <table border="1" style="width:80%"> <tr> <th>Customer name</th> <th>Deal Size</th> </tr> <p> ''' + table_text + ''' </p> </table><br> <p> Thanks, <br>Bell-project team!<br> ''' # We reference the image in the IMG SRC attribute by the ID we give it below msgText = MIMEText(image_txt, 'html') msgAlternative.attach(msgText) # Assume the image is in the current directory fp = open('bell.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close() # Define the image's ID as referenced above msgImage.add_header('Content-ID', 'image1') msg.attach(msgImage) # Send the message via our own SMTP server, but don't include the # envelope header. HOST = "smtp.gmail.com" PORT = "587" s = smtplib.SMTP() s.connect(HOST, PORT) USER = "******" PASSWD = "maprmapr" s.starttls() s.login(USER, PASSWD) #s.set_debuglevel(True) try: s.sendmail(me, [you], msg.as_string()) finally: s.quit()
def send_mail_ssl(server, sender, to, to_cert, subject, text, files=[], attachments={}, send=False): """ Sends SSL signed mail server - mailserver domain name eg. smtp.foo.bar sender - content of From field eg. "No Reply" <*****@*****.**> to - string with email addresses of recipent subject - subject of a mail text - text of email files - list of strings with paths to file to be attached attachmets - dict where keys are file names and values are content of files to be attached send - bool whether message should really be sent """ # create multipart message msg = MIMEMultipart() # attach message text as first attachment msg.attach(MIMEText(text)) # attach files to be read from file system for file in files: part = MIMEBase('application', "octet-stream") part.set_payload(open(file, "rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(part) # attach filest read from dictionary for name in attachments: part = MIMEBase('application', "octet-stream") part.set_payload(attachments[name]) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % name) msg.attach(part) msg_str = msg.as_string() # Make a MemoryBuffer of the message. buf = BIO.MemoryBuffer(msg_str) # Seed the PRNG. Rand.load_file('randpool.dat', -1) # Instantiate an SMIME object. s = SMIME.SMIME() # Load target cert to encrypt to. x509 = X509.load_cert_string(to_cert) sk = X509.X509_Stack() sk.push(x509) s.set_x509_stack(sk) # Set cipher: 3-key triple-DES in CBC mode. s.set_cipher(SMIME.Cipher('des_ede3_cbc')) # Encrypt the buffer. p7 = s.encrypt(buf) # Output p7 in mail-friendly format. out = BIO.MemoryBuffer() out.write('From: %s\n' % sender) out.write('To: %s\n' % to) out.write('Subject: %s\n' % subject) # append signed message and original message to mail header s.write(out, p7) # Save the PRNG's state. Rand.save_file('randpool.dat') # finally send mail if send: # print("would have sent") smtp = smtplib.SMTP(server) smtp.sendmail(sender, to, out.read() ) smtp.close() else: print("sending is disabled (use --send)")
import smtplib, sys, getpass from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEBase import MIMEBase from email import encoders from ConfigParser import SafeConfigParser parser = SafeConfigParser() parser.read('config.ini') fromaddr = parser.get('email', 'fromaddr') toaddr = parser.get('email', 'toaddr') message = MIMEMultipart() message['From'] = fromaddr message['To'] = toaddr if len(sys.argv)>2: message['Subject'] = sys.argv[1] else: message['Subject'] = '' body = "This is a file from MailMe" message.attach(MIMEText(body, 'plain')) filename = sys.argv[1] attachment = open(filename, "rb") part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read())
def main(): mysqlconn = MySQLdb.connect(host='dbod-cmsrv1.cern.ch', user='******', passwd="relval", port=5506) curs = mysqlconn.cursor() curs.execute("use " + dbname + ";") #curs.execute("lock tables batches write, batches_archive write, workflows write, workflows_archive write, datasets write, clone_reinsert_requests write") curs.execute("select * from batches") batches = curs.fetchall() batches_colnames = [desc[0] for desc in curs.description] for batch in batches: #for name, value in zip(batches_colnames, batch): # print name+" => "+str(value) batch_dict = dict(zip(batches_colnames, batch)) userid = batch_dict["useridyear"] + "_" + batch_dict[ "useridmonth"] + "_" + batch_dict["useridday"] + "_" + str( batch_dict["useridnum"]) + "_" + str( batch_dict["batch_version_num"]) if batch_dict["status"] == "input_dsets_ready": print " userid => " + userid curs.execute( "select workflow_name from workflows where useridyear = \"" + batch_dict["useridyear"] + "\" and useridmonth = \"" + batch_dict["useridmonth"] + "\" and useridday = \"" + batch_dict["useridday"] + "\" and useridnum = " + str(batch_dict["useridnum"]) + " and batch_version_num = " + str(batch_dict["batch_version_num"]) + ";") wfs = curs.fetchall() #first do checks to make sure the workflows do not write into an existing dataset for wf in wfs: conn = httplib.HTTPSConnection( 'cmsweb.cern.ch', cert_file=os.getenv('X509_USER_PROXY'), key_file=os.getenv('X509_USER_PROXY')) headers = { "Content-type": "application/json", "Accept": "application/json" } r1 = conn.request("GET", '/reqmgr2/data/request/' + wf[0], headers=headers) r2 = conn.getresponse() schema = (json.loads(r2.read())) schema = schema['result'] if len(schema) != 1: os.system( 'echo ' + wf[0] + ' | mail -s \"assignor.py error 9\" [email protected]' ) sys.exit(1) schema = schema[0] schema = schema[wf[0]] #if schema['RequestTransition'][len(schema['RequestTransition'])-1]['Status'] != "assignment-approved": # continue for key, value in schema.items(): if key == "ProcessingString": procstring_main = value for key, value in schema.items(): if type(value) is dict and key.startswith("Task"): if ('KeepOutput' in value and value['KeepOutput'] ) or 'KeepOutput' not in value: if 'InputDataset' in value: if 'AcquisitionEra' not in value: os.system( 'echo \"' + wf[0] + '\" | mail -s \"assignor.py error 10\" [email protected]' ) sys.exit(1) if 'ProcessingString' in value: procstring = value['ProcessingString'] elif "procstring_main" in vars(): procstring = procstring_main else: os.system( 'echo \"' + wf[0] + '\" | mail -s \"assignor.py error 11\" [email protected]' ) sys.exit(1) dset = "/" + value['InputDataset'].split( '/' )[1] + "/" + value[ 'AcquisitionEra'] + "-" + procstring + "-v" + str( batch_dict["processing_version"] ) + "/*" curs.execute( "select * from datasets where dset_name = \"" + dset.rstrip("*") + "\";") dbs_dset_check = utils.getDatasets(dset) curs_fetchall = curs.fetchall() if len(curs_fetchall) != 0: dsets_colnames = [ desc[0] for desc in curs.description ] dset_dict = dict( zip(dsets_colnames, curs_fetchall[0])) userid_previously_inserted_dset = dset_dict[ "useridyear"] + "_" + dset_dict[ "useridmonth"] + "_" + dset_dict[ "useridday"] + "_" + str( dset_dict["useridnum"] ) + "_" + str(dset_dict[ "batch_version_num"]) os.system( 'echo \"' + userid + "\n" + wf[0] + "\n" + userid_previously_inserted_dset + "\n" + dset_dict["workflow_name"] + "\n" + dset + '\" | mail -s \"assignor.py error 1\" [email protected]' ) sys.exit(1) elif len(dbs_dset_check) != 0: os.system( 'echo \"' + userid + "\n" + wf[0] + "\n" + dset + '\" | mail -s \"assignor.py error 5\" [email protected]' ) sys.exit(1) else: curs.execute( "insert into datasets set dset_name=\"" + dset.rstrip("*") + "\", workflow_name=\"" + wf[0] + "\", useridyear = \"" + batch_dict["useridyear"] + "\", useridmonth = \"" + batch_dict["useridmonth"] + "\", useridday = \"" + batch_dict["useridday"] + "\", useridnum = " + str(batch_dict["useridnum"]) + ", batch_version_num = " + str(batch_dict["batch_version_num"]) + ";") elif 'PrimaryDataset' in value: dset = "/" + value[ 'PrimaryDataset'] + "/" + value[ 'AcquisitionEra'] + "-" + value[ 'ProcessingString'] + "-v" + str( batch_dict["processing_version"] ) + "/*" curs.execute( "select * from datasets where dset_name = \"" + dset.rstrip("*") + "\";") curs_fetchall = curs.fetchall() dbs_dset_check = utils.getDatasets(dset) if len(curs_fetchall) != 0: dsets_colnames = [ desc[0] for desc in curs.description ] dset_dict = dict( zip(dsets_colnames, curs_fetchall[0])) userid_previously_inserted_dset = dset_dict[ "useridyear"] + "_" + dset_dict[ "useridmonth"] + "_" + dset_dict[ "useridday"] + "_" + str( dset_dict["useridnum"] ) + "_" + str(dset_dict[ "batch_version_num"]) os.system( 'echo \"' + userid + "\n" + wf[0] + "\n" + userid_previously_inserted_dset + "\n" + dset_dict["workflow_name"] + "\n" + dset + '\" | mail -s \"assignor.py error 2\" [email protected]' ) sys.exit(1) elif len(dbs_dset_check) != 0: os.system( 'echo \"' + userid + "\n" + wf[0] + '\" | mail -s \"assignor.py error 7\" [email protected]' ) sys.exit(1) else: curs.execute( "insert into datasets set dset_name=\"" + dset.rstrip("*") + "\", workflow_name=\"" + wf[0] + "\", useridyear = " + batch_dict["useridyear"] + ", useridmonth = " + batch_dict["useridmonth"] + ", useridday = " + batch_dict["useridday"] + ", useridnum = " + str(batch_dict["useridnum"]) + ", batch_version_num = " + str(batch_dict["batch_version_num"]) + ";") #only assign the workflows after all of the checks are done for wf in wfs: conn = httplib.HTTPSConnection( 'cmsweb.cern.ch', cert_file=os.getenv('X509_USER_PROXY'), key_file=os.getenv('X509_USER_PROXY')) headers = { "Content-type": "application/json", "Accept": "application/json" } r1 = conn.request("GET", '/reqmgr2/data/request/' + wf[0], headers=headers) r2 = conn.getresponse() if r2.status != 200: time.sleep(30) conn = httplib.HTTPSConnection( 'cmsweb.cern.ch', cert_file=os.getenv('X509_USER_PROXY'), key_file=os.getenv('X509_USER_PROXY')) r1 = conn.request("GET", '/reqmgr2/data/request/' + wf[0], headers=headers) r2 = conn.getresponse() if r2.status != 200: os.system( 'echo ' + wf[0] + ' | mail -s \"assignor.py error 8\" [email protected]' ) sys.exit(0) schema = json.loads(r2.read()) schema = schema['result'] if len(schema) != 1: os.system( 'echo ' + wf[0] + ' | mail -s \"assignor.py error 9\" [email protected]' ) sys.exit(1) schema = schema[0] schema = schema[wf[0]] if schema['RequestTransition'][ len(schema['RequestTransition']) - 1]['Status'] != "assignment-approved": continue #hack because workflows assigned to only T2_CH_CERN_T0 never get acquired site = batch_dict["site"] #if site == "T2_CH_CERN_T0": # site = ["T2_CH_CERN","T2_CH_CERN_T0"] params = assignment.make_assignment_params( schema, site, batch_dict["processing_version"]) result = reqMgrClient.assignWorkflow("cmsweb.cern.ch", wf[0], "relval", params) if result != True: os.system( 'echo ' + wf[0] + ' | mail -s \"assignor.py error 4\" [email protected]' ) sys.exit(0) time.sleep(30) curs.execute( "update batches set status=\"assigned\", current_status_start_time=\"" + datetime.datetime.now().strftime("%y:%m:%d %H:%M:%S") + "\" where useridyear = \"" + batch_dict["useridyear"] + "\" and useridmonth = \"" + batch_dict["useridmonth"] + "\" and useridday = \"" + batch_dict["useridday"] + "\" and useridnum = " + str(batch_dict["useridnum"]) + " and batch_version_num = " + str(batch_dict["batch_version_num"]) + ";") mysqlconn.commit() if batch_dict[ "hn_message_id"] != "do_not_send_an_acknowledgement_email": msg = MIMEMultipart() reply_to = [] send_to = [ "*****@*****.**", "*****@*****.**" ] #send_to = ["*****@*****.**","*****@*****.**"] #send_to = ["*****@*****.**"] msg['In-Reply-To'] = batch_dict["hn_message_id"] msg['References'] = batch_dict["hn_message_id"] msg['From'] = "*****@*****.**" msg['reply-to'] = COMMASPACE.join(reply_to) msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = batch_dict["announcement_title"] msg['Message-ID'] = email.Utils.make_msgid() messageText = "Dear all,\n" messageText = messageText + "\n" messageText = messageText + "This batch has been assigned.\n" messageText = messageText + "\n" messageText = messageText + "RelVal Batch Manager" try: msg.attach(MIMEText(messageText)) smtpObj = smtplib.SMTP() smtpObj.connect() smtpObj.sendmail("*****@*****.**", send_to, msg.as_string()) smtpObj.close() except Exception as e: print "Error: unable to send email: %s" % (str(e))
def SMSToMail(cfg, sms, lookuplist=None, mailbox=False): ''' Converts SMS to formated mail. It will contain all images and sounds from message and predefined animations. Also text formatting is preserved in HTML. ''' msg = MIMEMultipart('related', None, None, type='text/html') prepend = '' name = '' if lookuplist is not None: i = SearchNumber(lookuplist, sms['Number']) if i != -1: msg.add_header(HEADER_FORMAT % 'ContactID', str(i)) name = '%s ' % lookuplist[i]['Name'] for header in PARTS_TO_HEADER: msg.add_header(HEADER_FORMAT % header, unicode(sms['SMS'][0][header])) msg.add_header(HEADER_FORMAT % 'SMSC', sms['SMS'][0]['SMSC']['Number']) if sms['SMS'][0]['SMSCDateTime'] is not None: msg.add_header( HEADER_FORMAT % 'SMSCDate', DateToString(sms['SMS'][0]['SMSCDateTime']) ) remote = '%s<*****@*****.**>' % (name, sms['Number'].replace(' ', '_')) local = cfg.Read('/MessageExport/From') if sms['SMS'][0]['Type'] == 'Submit': msg['To'] = remote msg['From'] = local else: msg['To'] = local msg['From'] = remote prepend = ( 'Received: from %s via GSM\n' % unicode(sms['SMS'][0]['SMSC']['Number']) ) + prepend if len(sms['Name']) > 0: msg['Subject'] = SmsTextFormat(cfg, sms['Name'], False) else: msg['Subject'] = SmsTextFormat(cfg, sms['Text'], False)[:50] + '...' if sms['DateTime'] is not None: msg['Date'] = DateToString(sms['DateTime']) if 'SMSInfo' in sms: text = '' cid = 0 for i in sms['SMSInfo']['Entries']: if i['ID'] in Wammu.Data.SMSIDs['PredefinedAnimation']: if i['Number'] > len(Wammu.Data.PredefinedAnimations): sub = MIMEImage(XPMToPNG(Wammu.Data.UnknownPredefined)) else: img = Wammu.Data.PredefinedAnimations[i['Number']][1] xpm = XPMToPNG(img) sub = MIMEImage(xpm) sub.add_header('Content-ID', '<%s>' % CID_FORMAT % cid) sub.add_header('Content-Disposition', 'inline') msg.attach(sub) text = text + '<img src="cid:%s">' % (CID_FORMAT % cid) cid = cid + 1 # FIXME: need sounds if 0 and i['ID'] in Wammu.Data.SMSIDs['PredefinedSound']: if i['Number'] >= len(Wammu.Data.PredefinedSounds): sub = '' else: sub = '' sub.add_header('Content-Disposition', 'attachment') msg.attach(sub) if i['ID'] in Wammu.Data.SMSIDs['Sound']: sub = MIMEAudio(RingtoneToMIDI(i['Ringtone']), 'midi') sub.add_header('Content-Disposition', 'attachment') msg.attach(sub) if i['ID'] in Wammu.Data.SMSIDs['Text']: fmt = '%s' for format_data in Wammu.Data.TextFormats: for name, dummy, style in format_data[1:]: if name in i and i[name]: fmt = style % fmt text = text + (fmt % SmsTextFormat(cfg, i['Buffer'])) if i['ID'] in Wammu.Data.SMSIDs['Bitmap']: for bitmap in i['Bitmap']: sub = MIMEImage(XPMToPNG(bitmap['XPM'])) sub.add_header('Content-ID', '<%s>' % CID_FORMAT % cid) sub.add_header('Content-Disposition', 'inline') msg.attach(sub) text = text + '<img src="cid:%s">' % (CID_FORMAT % cid) cid = cid + 1 if i['ID'] in Wammu.Data.SMSIDs['Animation']: for bitmap in i['Bitmap']: sub = MIMEImage(XPMToPNG(bitmap['XPM'])) sub.add_header('Content-ID', '<%s>' % CID_FORMAT % cid) sub.add_header('Content-Disposition', 'inline') msg.attach(sub) text = text + '<img src="cid:%s">' % (CID_FORMAT % cid) cid = cid + 1 else: text = SmsTextFormat(cfg, sms['Text']) html = '<html><head></head><body>%s</body></html>' sub = MIMEText(html % text.encode('utf-8'), 'html', 'utf-8') msg.attach(sub) if sms['DateTime'] is not None: filename = '%s-%s-%s.eml' % ( sms['SMS'][0]['Type'], sms['DateTime'].strftime("%Y%m%d%H%M%S"), md5(sms['Text'].encode('utf-8')).hexdigest()) else: filename = '%s-%s.eml' % ( sms['SMS'][0]['Type'], md5(sms['Text'].encode('utf-8')).hexdigest()) # Add message ID msgid = '<%s@%s>' % (filename[:-4], sms['Number'].replace(' ', '_')) msgid = msgid.encode('ascii', 'xmlcharrefreplace') msg.add_header('Message-ID', msgid) if mailbox: if sms['DateTime'] is None: timestamp = time.asctime(time.localtime(None)) else: timestamp = time.asctime(sms['DateTime'].timetuple()) prepend = ('From [email protected] %s\n' % timestamp) + prepend return filename, prepend + msg.as_string(), msgid
def welcome_email(user_email, wallet, uuid): if user_email is not None: msg = MIMEMultipart('alternative') msg['From'] = email_from msg['To'] = user_email msg['Subject'] = "Welcome to HcOmniwallet" text = ( 'Welcome To HcOmniwallet!\n' '\n' 'Thank you for creating a new wallet and choosing to join the exciting world of cryptocurrency.\n' 'While we know you are eager to get started, this email contains important information about your new HcOmniwallet.\n' 'So please take a moment to read through it completely.\n' '\n' 'Your Wallet Login Details' 'This is your Wallet ID: ' + str(uuid) + '\n' 'Never share your Wallet ID or Password with anyone. Be sure to keep them safe and stored separately for security.\n\n' 'This is your unique Login Link: https://' + str(email_domain) + '/login/' + str(uuid) + '\n' 'Bookmark this, you can use it to login directly to your HcOmniwallet with your password.\n' '\n' 'Omniwallet NEVER STORES Your Password.\n' 'This means you need your password to access your wallet and the private keys within.\n' 'If you lose or forget your password there is nothing we can do to recover it.\n' 'This may result in the loss of funds in any wallet addresses which have not been Backed Up!\n\n' 'Please, Please, Please Keep Your Password Safe!\n' '\n' 'Important Information On Backing Up Your Wallet' 'If you lose or forget your password the only thing you can use to recover your funds is a Wallet Backup.\n' 'You should create a new backup any time you make a change to your wallet (add/remove an address).\n' 'Remove the old backup only after you have confirmed the contents of the new backup are complete.\n' 'On the "My Addresses" page you can export a backup of your wallet under the "Wallet Options" button.\n' 'This backup file contains every address and private key (if known) for the addresses in your wallet at the time of backup.\n' 'Store your backup file in a secure place. Anyone with access to this file has access to your funds.' '\n' 'Thank you for taking the time to read this introduction. \n' 'This as well as many more questions/answers are available on our FAQ Page: https://' + str(email_domain) + '/about/faq \n' 'If you have any questions please feel free to reach out to us using the information on our Contact Us page: https://' + str(email_domain) + '/about/contact \n' '\n' 'Sincerely, \n The HCASH Team') html = ( '<!doctype html><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type"content="text/html; charset=UTF-8"/><title>EDM</title><meta name="viewport"content="width=device-width, initial-scale=1.0"/>' '</head><body>' '<table border="0" cellpadding="0" cellspacing="0" width="100%"><tbody><tr><td style="font-family: ' "STHeiti Light" ', ' "Helvetica" ', ' "arial" ', ' "Microsoft Yahei" ', ' "sans-serif" '">' '<table align="center"border="0"cellpadding="0"cellspacing="0"width="600"style="text-align:left;">' '<tbody><tr><td style="padding:10px 10px 0px 10px; text-align:center;"><div style="width:600px;max-width: 100%;"><img ' 'src="https://' + str(email_domain) + '/assets/img/logo.png"></div></td></tr><tr><td style="font-size:20px;font-weight:bold;color:#034F92;padding:30px 10px 0px 10px;text-align:center;">Welcome To HcOmniwallet!</td></tr><tr><td ' 'style="font-size:13px;color:#555;padding:10px 10px 10px 10px;">Thank you for creating a new wallet and choosing to join the exciting world of cryptocurrency.<br>While we know you are eager to get started,this email contains ' 'important information about your new HcOmniwallet.<br>So please take a moment to read through it completely.</td></tr><tr><td style="font-size:16px;font-weight:bold;color:#034F92;padding:30px 10px 0px ' '10px;text-align:center;">Your Wallet Login Details</td></tr><tr><td style="font-size:13px;color:#555;padding:10px 10px 10px 10px;">This is your<b>Wallet ID:</b>' + str(uuid) + '<br>Never share your Wallet ID or Password with ' 'anyone.Be sure to keep them safe and stored separately for security.<br><br>This is your unique<b>Login Link:</b>' ' <a style="color:#0e5bc9;"href="https://' + str(email_domain) + '/login/' + str(uuid) + '">https://' + str(email_domain) + '/login/' + str(uuid) + '</a><br>' 'Bookmark this,you can use it to login directly to your HcOmniwallet with your password.<strong>HcOmniwallet Never Stores Your Password.</strong><br>' 'This means you need your password to access your wallet and the private keys within.<br>If you lose or ' 'forget your password there is nothing we can do to recover it.<br>This may result in the loss of funds in any wallet addresses which have not been Backed Up!<br><br><strong>Please,Please,Please Keep Your Password ' 'Safe!</strong><br></td></tr><tr><td style="font-size:16px;font-weight:bold;color:#034F92;padding:30px 10px 0px 10px;text-align:center;">Important Information On Backing Up Your Wallet</td></tr><tr><td ' 'style="font-size:13px;color:#555;padding:10px 10px 10px 10px;">If you lose or forget your password the only thing you can use to recover your funds is a Wallet Backup.<br>You should create a new backup any time you make a change ' 'to your wallet(add/remove an address).<br>Remove the old backup only after you have confirmed the contents of the new backup are complete.<br>On the"My Addresses"page you can export a backup of your wallet under the"Wallet ' 'Options"button.<br>This backup file contains every address and private key(if known)for the addresses in your wallet at the time of backup.<br><strong>Store your backup file in a secure place.Anyone with access to this file has ' 'access to your funds.</strong>Thank you for taking the time to read this introduction.<br>This as well as many more questions/answers are available on our <a ' 'style="color:#0e5bc9; "href="https://' + str(email_domain) + '/about/faq"> FAQ </a>page.<br>If you have any questions please feel free to reach out to us using the information on our <a ' 'style="color:#0e5bc9; "href="https://' + str(email_domain) + '/about/contact"> Contact Us </a>page.<br></td></tr><tr><td style="border-top: 1px solid #BABCC0; font-size:16px;color:#1B222D;padding:30px 10px 10px' '10px;text-align:center;">Sincerely,</td></tr><tr><td style="font-size:16px;color:#1B222D;padding:10px 10px 10px 10px;text-align:center;">The HCASH Team</td></tr><tr><td style="font-size:16px;color:#1B222D;padding:10px 10px 10px' '10px;text-align:center;"><img src="http://test.legenddigital.com.au/jack/hcash_email/images/icon.jpg"width="46"></td></tr><tr><td style="background-color: #f7f6f7;color: #000000;font-size:12px; text-align:center;padding:20px' '10px;text-align:center;">Copyright 2018<span style="color:#8219bf;">HCASH</span>,All rights reserved.</td></tr></tbody></table></td></tr></tbody></table></body></html>' ) part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') msg.attach(part1) msg.attach(part2) if config.WELCOMECID is not None: msg.add_header('X-Mailgun-Tag', config.WELCOMECID) #wfile = MIMEBase('application', 'octet-stream') #wfile.set_payload(wallet) #Encoders.encode_base64(wfile) #wfile.add_header('Content-Disposition', 'attachment', filename=uuid+'.json') #msg.attach(wfile) smtp = smtplib.SMTP_SSL(config.SMTPDOMAIN, config.SMTPPORT) if config.SMTPUSER is not None and config.SMTPPASS is not None: smtp.login(config.SMTPUSER, config.SMTPPASS) smtp.sendmail(email_from, user_email, msg.as_string()) smtp.close()
def send_mail(to, subject, text, attachments=[], cc=[], bcc=[], smtphost="", fromaddr=""): if sys.version_info[0] == 2: from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders else: from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate from email import encoders as Encoders from string import Template import socket import smtplib if not isinstance(to, list): print("the 'to' parameter needs to be a list") return False if len(to) == 0: print("no 'to' email addresses") return False myhost = socket.getfqdn() if smtphost == '': smtphost = get_mx_from_email_or_fqdn(myhost) if not smtphost: sys.stderr.write('could not determine smtp mail host !\n') if fromaddr == '': fromaddr = os.path.basename(__file__) + '-no-reply@' + \ '.'.join(myhost.split(".")[-2:]) # extract domain from host tc = 0 for t in to: if '@' not in t: # if no email domain given use domain from local host to[tc] = t + '@' + '.'.join(myhost.split(".")[-2:]) tc += 1 message = MIMEMultipart() message['From'] = fromaddr message['To'] = COMMASPACE.join(to) message['Date'] = formatdate(localtime=True) message['Subject'] = subject message['Cc'] = COMMASPACE.join(cc) message['Bcc'] = COMMASPACE.join(bcc) body = Template( 'This is a notification message from $application, running on \n' + 'host $host. Please review the following message:\n\n' + '$notify_text\n\n') host_name = socket.gethostname() full_body = body.substitute(host=host_name.upper(), notify_text=text, application=os.path.basename(__file__)) message.attach(MIMEText(full_body)) for f in attachments: part = MIMEBase('application', 'octet-stream') part.set_payload(open(f, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) message.attach(part) addresses = [] for x in to: addresses.append(x) for x in cc: addresses.append(x) for x in bcc: addresses.append(x) smtp = smtplib.SMTP(smtphost) smtp.sendmail(fromaddr, addresses, message.as_string()) smtp.close() return True
def login(): """Render the website's login user page.""" secret= app.config['TOKEN_SECRET'] email= request.json['email'] password= request.json['password'] payload={"email": email,"password": password} encoded_token=jwt.encode({'logon_info': payload}, secret, algorithm='HS256' user = Person.query.filter_by(email_address=email, password=password).first() if user is not None: login_user(user) # Sends back the information along with the token generated response = jsonify(information={"error":"null","data":{'user':{'id':user.id,'email': user.email_address,'fname':user.first_name, 'lname': user.last_name, 'Authorization_token':encoded_token},"message":"Success"}}) else: response = jsonify({"error":"1","data":{},"message":'failed'}) response.status_code = 401 return response @app.route('/api/users/<userid>/wishlist', methods=["GET","POST"]) @login_required def apiadd(userid): if request.method == "POST": new_wish= Wish(wish_url=request.json['url'], user_id=userid , wish_descript=request.json['description'], wish_title=request.json['title'], thumbnail=request.json['image'], added=str(datetime.now())); db.session.add(new_wish) db.session.commit() response = jsonify({"error":"null","data":{},"message":"Success"}) return response else: user = Person.query.filter_by(id=userid).first() userwishes = Wish.query.filter_by(user_id=userid) wishlist = [] for wish in userwishes: wishlist.append({'id':wish.wish_id,'title': wish.wish_title,'description':wish.wish_descript,'url':wish.wish_url,'thumbnail':wish.thumbnail, 'added': wish.added}) if(len(wishlist)>0): response = jsonify({"error":"null","data":{"wishes":wishlist}}) else: response = jsonify({"error":"1","data":{}}) return response @app.route('/api/thumbnails', methods=['POST']) def thumbnail(): url = request.json['url'] imagelist = get_images(url) for each in imagelist: if not each.lower().endswith(('.png', '.jpg', '.jpeg')): imagelist.remove(each) imagelist= list(set(imagelist)); output = jsonify(thumbnails= imagelist) return output def get_images(url): result = requests.get(url) soup = BeautifulSoup(result.text, "html.parser") imgs=[] image = "%s" for img in soup.findAll("img", src=True): link = image % urlparse.urljoin(url, img["src"]) imgs+=[link] return imgs @app.route('/api/users/<userid>/wishlist/<itemid>', methods=['POST']) def deletewish(userid,itemid): item_id= request.json['itemid'] #because based on the db the wish id and the person/userid are always the same deleted_wish= Wish.query.filter_by(user_id=userid,wish_id= itemid).first() # use session.delete here instead of add db.session.delete(deleted_wish) db.session.commit() response = jsonify({"error":"null","data":{},"message":"Success"}) return response @app.route('/about/') def about(): """Render the website's about page.""" return render_template('about.html') # user_loader callback. This callback is used to reload the user object from # the user ID stored in the session @login_manager.user_loader def load_user(id): return Person.query.get(int(id)) # ### # # The functions below should be applicable to all Flask apps. # ### @app.route('/share/', methods = ['POST']) def send_email(): firstname = request.json['firstname'] lastname = request.json['lastname'] user= Person.query.filter_by(id=request.json['userid']).first() name = user.first_name userid= user.id from_addr = '*****@*****.**' to_addr = request.json['email'] msg = MIMEMultipart() msg['From'] = from_addr msg['To'] = to_addr msg['Subject'] = str(name) + " has shared their wishlist with you" body = "Member " + str(name) + " from Wishlstproject.com has shared their wishlist with you!! https://www.google.com/search?q=cats+meme&client=firefox-b&noj=1&source=lnms&tbm=isch&sa=X&ved=0ahUKEwizk8GiyMXTAhWBKiYKHc0NAh0Q_AUICigB&biw=1366&bih=669" msg.attach(MIMEText(body, 'plain')) #from_name = 'wishlistproject' #to_name = request.json['name'] #subject = 'Someone has shared their wishlist with you' ### message = 'Member '+ username + 'from Wishlstproject.com has shared his/her wishlist with you!! /n http://info3180-project2-shadain94.c9users.io/api/users/' + userid + '/wishlist' #message = "test" #message_to_send = message.format(from_name, from_addr, to_name, to_addr, subject, message) # Credentials (if needed) username = '******' password = '******' # The actual mail send server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.login(username, password) text = msg.as_string() server.sendmail(from_addr, to_addr, text) server.quit() response = jsonify({"error":"null", "message":"Success"}) return response def timeinfo(entry): day = time.strftime("%a") date = time.strftime("%d") if (date <10): date = date.lstrip('0') month = time.strftime("%b") year = time.strftime("%Y") return day + ", " + date + " " + month + " " + year @app.route('/<file_name>.txt') def send_text_file(file_name): """Send your static text file.""" file_dot_text = file_name + '.txt' return app.send_static_file(file_dot_text) @app.after_request def add_header(response): """ Add headers to both force latest IE rendering engine or Chrome Frame, and also to cache the rendered page for 10 minutes. """ response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1' response.headers['Cache-Control'] = 'public, max-age=0' return response @app.errorhandler(404) def page_not_found(error): """Custom 404 page.""" return render_template('404.html'), 404 if __name__ == '__main__': app.run(debug=True,host="0.0.0.0",port="8080")
import time import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEBase import MIMEBase from email import encoders from email.mime.image import MIMEImage from smbus2 import SMBus from mlx90614 import MLX90614 fromaddr = "*****@*****.**" # change the email address accordingly toaddr = "*****@*****.**" mail = MIMEMultipart() mail['From'] = fromaddr mail['To'] = toaddr mail['Subject'] = "Temperature value exceed alert" body = "Please find the attached image" data = "" def sendMail(data): mail.attach(MIMEText(body, 'plain')) print data dat = '%s.jpg' % data print dat attachment = open(dat, 'rb')
def mail(to, subject, text, attach, prioflag1, prioflag2): msg = MIMEMultipart() msg['From'] = str( Header(from_displayname, 'UTF-8').encode() + ' <' + from_address + '> ') msg['To'] = to msg['X-Priority'] = prioflag1 msg['X-MSMail-Priority'] = prioflag2 msg['Subject'] = Header(subject, 'UTF-8').encode() # specify if its html or plain # body message here body_type = MIMEText(text, "%s" % (message_flag), 'UTF-8') msg.attach(body_type) # define connection mimebase part = MIMEBase('application', 'octet-stream') part.set_payload(open(attach, 'rb').read()) # base 64 encode message mimebase Encoders.encode_base64(part) # add headers part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach)) msg.attach(part) io = StringIO() msggen = Generator(io, False) msggen.flatten(msg) # define connection to smtp server mailServer = smtplib.SMTP(smtp, int(port)) mailServer.ehlo() # send ehlo to smtp server if sendmail == 0: if email_provider == "gmail" or email_provider == "yahoo": mailServer.ehlo() # start TLS needed for gmail and yahoo try: mailServer.starttls() except: pass mailServer.ehlo() if counter == 0: try: if email_provider == "gmail" or email_provider == "yahoo": try: mailServer.starttls() except: pass mailServer.ehlo() if len(provideruser) > 0: mailServer.login(provideruser, pwd) mailServer.sendmail(from_address, to, io.getvalue()) except Exception, e: print_error( "Unable to deliver email. Printing exceptions message below, this is most likely due to an illegal attachment. If using GMAIL they inspect PDFs and is most likely getting caught." ) raw_input("Press {return} to view error message.") print str(e) try: mailServer.docmd("AUTH LOGIN", base64.b64encode(provideruser)) mailServer.docmd(base64.b64encode(pwd), "") except Exception, e: print str(e) try: mailServer.login(provideremail, pwd) thread.start_new_thread( mailServer.sendmail(from_address, to, io.getvalue())) except Exception, e: return_continue()
def send_test_mail(kindle_mail): msg = MIMEMultipart() msg['Subject'] = _(u'Calibre-web test email') text = _(u'This email has been sent via calibre web.') msg.attach(MIMEText(text.encode('UTF-8'), 'plain', 'UTF-8')) return send_raw_email(kindle_mail, msg)
def simple_send_mail(plain, html, addresses, mfrom, subject, immediate=True): """Send a notification email to the list of addresses. The method is called 'simple' because all the clever stuff should already have been done by the caller. message is passed without change to the mail host. It should probably be a correctly encoded Message or MIMEText. One mail with the given message and subject is sent for each address. Note that with Plone 4 (Zope 2.12) by default the sending is deferred to the end of the transaction. This means an exception would roll back the transaction. We usually do not want that, as the email sending is an extra: we do not mind too much if sending fails. Luckily we have the option to send immediately, so we can catch and ignore exceptions. In this method we do that. You can override that by passing immediate=False. Note that in Plone 3 this has no effect at all. """ mail_host = utils.get_mail_host() if mail_host is None: logger.warn("Cannot send notification email: please configure " "MailHost correctly.") # We print some info, which is perfect for checking in unit # tests. print('Subject ={0}'.format(subject)) print('Addresses ={0}'.format(addresses)) print('Message =') print(plain) return if not mfrom: mfrom = utils.get_mail_from_address() header_charset = utils.get_charset() text_part = MIMEText(plain, 'plain', header_charset) html_part = MIMEText(html, 'html', header_charset) if plain and html: email_content = MIMEMultipart('alternative') email_content.epilogue = '' email_content.attach(text_part) email_content.attach(html_part) elif plain: email_content = text_part elif html: email_content = html_part else: # Hm, that's weird. email_content = '' for address in addresses: if not address: continue try: if USE_SECURE_SEND: mail_host.secureSend( message=email_content, mto=address, mfrom=mfrom, subject=subject, charset=header_charset, ) else: mail_host.send( email_content, mto=address, mfrom=mfrom, subject=subject, immediate=immediate, charset=header_charset, ) except (socket.error, SMTPException, MailHostError): logger.warn('Could not send email to %s with subject %s', address, subject) except: raise
def send_Email(json_result): print '*******开始发送邮件****' buildName = json_result['data']['buildName'] buildKey = json_result['data']['buildKey'] buildVersion = json_result['data']['buildVersion'] buildBuildVersion = json_result['data']['buildBuildVersion'] buildShortcutUrl = json_result['data']['buildShortcutUrl'] buildQRCodeURL = json_result['data']['buildQRCodeURL'] buildUpdated = json_result['data']['buildUpdated'] #邮件接受者 mail_receiver = ['*****@*****.**', '*****@*****.**'] #根据不同邮箱配置 host,user,和pwd mail_host = 'your mail host' mail_port = 25 mail_user = '******' mail_pwd = 'email password' mail_to = ','.join(mail_receiver) msg = MIMEMultipart() environsString = '<h3>本次打包相关信息</h3><p>' environsString += '<p>应用名称:' + str(buildName) + '</p>' environsString += '<p>版本号:' + str(buildVersion) + '</p>' environsString += '<p>更新时间:' + str(buildUpdated) + '</p>' environsString += '<p>安装密码:' + str(buildPassword) + '</p>' if changelog: print "changelog not empty" environsString += '<p>变更记录:</p>' environsString += '<p>' + str(changelog) + '</p>' else: print "changelog empty" # environsString += '<p>你可从蒲公英网站在线安装 : ' + 'http://www.pgyer.com/' + str(buildShortcutUrl) + '<p>' environsString += '<img src="' + str(buildQRCodeURL) + '" alt="二维码" />' environsString += '<p>扫码直接安装</p>' message = environsString body = MIMEText(message, _subtype='html', _charset='utf-8') # 添加附件 part = MIMEBase('application', 'octet-stream') # 'octet-stream': binary data 创建附件对象 source_path = get_ipa_file_path() part.set_payload(open(source_path, 'rb').read()) # 将附件源文件加载到附件对象 encoders.encode_base64(part) nowTime = time.strftime("%Y-%m-%d", time.localtime()) part_name = 'your_app-' + nowTime + '_' + sel_product_flavors + '.ipa' part_name = part_name.decode('utf-8').encode(sys.getfilesystemencoding()) print part_name part.add_header('Content-Disposition', 'attachment; filename="' + part_name + '"') # 给附件添加头文件 msg.attach(body) msg.attach(part) # 将附件附加到根容器 msg['To'] = mail_to msg['from'] = mail_user msg['subject'] = 'iOS打包文件: ' + sel_product_flavors + ' ' + buildName + ' ' + buildVersion try: s = smtplib.SMTP() # 设置为调试模式,就是在会话过程中会有输出信息 s.set_debuglevel(1) s.connect(mail_host) s.login(mail_user, mail_pwd) s.sendmail(mail_user, mail_receiver, msg.as_string()) s.close() print '*******邮件发送成功****' except Exception, e: print e
def envia_email(self): #url = "http://localhost/web?debug=1#id=2&view_type=form&model=gestion_clinica.paciente&menu_id=235&action=264" #uri = urlparse(url) #qs = uri.fragment #final = parse_qs(qs).get('id', None) pacientes = self.env['gestion_clinica.paciente'].search( [] ) #Ya filtra por los pacientes que vel el doctor logeado. Caso de que se quiera limitar la busqueda: .search([('id','=', '2')], limit=1) gmailUser = '' gmailPassword = '' directory_path = os.path.dirname( os.path.abspath(inspect.getfile(inspect.currentframe()))) dir_file = os.path.join(directory_path, 'pdata.txt') with open(dir_file, 'r') as f: gmailUser = f.readline().rstrip('\n') gmailPassword = f.readline().rstrip('\n') for paciente in pacientes: if ((len(gmailUser) > 1) and (len(gmailUser) > 0)): for dosis in paciente.dosis_ids: fecha_sumada = datetime.datetime.now( ) + datetime.timedelta(7) date_fecha = datetime.datetime.strftime( fecha_sumada, '%Y-%m-%d') fecha_hoy = datetime.datetime.strftime( datetime.datetime.now(), '%Y-%m-%d') if (dosis.cancelado == False) and (dosis.alertaEnviada == False) and ( date_fecha > dosis.fechaFin) and ( dosis.fechaFin >= fecha_hoy): recipient = paciente.email asunto = dosis.visita_id.asunto.encode('utf-8') medicamento = dosis.medicamento_id.nombre.encode( 'utf-8') fechaF = str(dosis.fechaFin) nombreCompleto = paciente.nombre.encode( 'utf-8') + ' ' + paciente.apellidos.encode('utf-8') nombreDoctor = dosis.visita_id.paciente_id.doctor_id.name.encode( 'utf-8') html = """\ <html> <head></head> <body> <tr> <td> <table border="0" cellpadding="0" cellspacing="0"> <tr> <td> <p>Hola <strong>{nombreCompleto}</strong>,</p> <p>Desde Inebir le recordamos que su tratamiento actual con <i>"{medicamento}"</i> relacionado con la visita <i>{asunto}</i>, termina muy pronto <strong>{fechaF}</strong>.</p> <p>No dude en contactar con nosotros o con su doctor ({nombreDoctor}) ante cualquier duda.</p> <p>Coordiales saludos, el equipo de Inebir.</p> </td> </tr> </table> </td> </tr> </body> </html> """.format(nombreCompleto=nombreCompleto, medicamento=medicamento, asunto=asunto, fechaF=fechaF, nombreDoctor=nombreDoctor) msg = MIMEMultipart() msg['From'] = gmailUser msg['To'] = recipient msg['Subject'] = "Notificacion" cuerpo = MIMEText(html, 'html') msg.attach(cuerpo) mailServer = smtplib.SMTP('smtp.gmail.com', 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(gmailUser, gmailPassword) mailServer.sendmail(gmailUser, recipient, msg.as_string()) mailServer.close() dosis.alertaEnviada = True
maintype, subtype = contenttype.split('/') if maintype == 'text': retval = MIMEText(data, _subtype=subtype) else: retval = MIMEBase(maintype, subtype) retval.set_payload(data) Encoders.encode_base64(retval) return retval messagetext = """Hello, This is a *great* test message from Chapter 9. I hope you enjoy it! -- Anonymous""" messagehtml = """Hello,<P> This is a <B>great</B> test message from Chapter 9. I hope you enjoy it!<P> -- <I>Anonymous</I>""" msg = MIMEMultipart('alternative') msg['To'] = '*****@*****.**' msg['From'] = 'Test Sender <*****@*****.**>' msg['Subject'] = 'Test Message, Chapter 9' msg['Date'] = Utils.formatdate(localtime=1) msg['Message-ID'] = Utils.make_msgid() msg.attach(alternative(messagetext, 'text/plain')) msg.attach(alternative(messagehtml, 'text/html')) print msg.as_string()
def sendmail(car_no,rfid_no,balance,email,firstname,lastname,phone_no,vehicle_category,vehicle_color,vehicle_company,vehicle_model,vehicle_type): fromaddr = "*****@*****.**" toaddr = email msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "BILL RECEIPT FOR YOUR TOLL" body = "<b>BILLING INFORMATION</b>" html ="""<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> .table{width:100%;max-width:100%;margin-bottom:1rem;background-color:transparent}.table td,.table th{padding:.75rem;vertical-align:top;border-top:1px solid #dee2e6}.table thead th{vertical-align:bottom;border-bottom:2px solid #dee2e6}.table tbody+tbody{border-top:2px solid #dee2e6}.table .table{background-color:#fff}.table-sm td,.table-sm th{padding:.3rem}.table-bordered{border:1px solid #dee2e6}.table-bordered td,.table-bordered th{border:1px solid #dee2e6}.table-bordered thead td,.table-bordered thead th{border-bottom-width:2px}.table-striped tbody tr:nth-of-type(odd){background-color:rgba(0,0,0,.05)}.table-hover tbody tr:hover{background-color:rgba(0,0,0,.075)}.table-primary,.table-primary>td,.table-primary>th{background-color:#b8daff}.table-hover .table-primary:hover{background-color:#9fcdff}.table-hover .table-primary:hover>td,.table-hover .table-primary:hover>th{background-color:#9fcdff}.table-secondary,.table-secondary>td,.table-secondary>th{background-color:#d6d8db}.table-hover .table-secondary:hover{background-color:#c8cbcf}.table-hover .table-secondary:hover>td,.table-hover .table-secondary:hover>th{background-color:#c8cbcf}.table-success,.table-success>td,.table-success>th{background-color:#c3e6cb}.table-hover .table-success:hover{background-color:#b1dfbb}.table-hover .table-success:hover>td,.table-hover .table-success:hover>th{background-color:#b1dfbb}.table-info,.table-info>td,.table-info>th{background-color:#bee5eb}.table-hover .table-info:hover{background-color:#abdde5}.table-hover .table-info:hover>td,.table-hover .table-info:hover>th{background-color:#abdde5}.table-warning,.table-warning>td,.table-warning>th{background-color:#ffeeba}.table-hover .table-warning:hover{background-color:#ffe8a1}.table-hover .table-warning:hover>td,.table-hover .table-warning:hover>th{background-color:#ffe8a1}.table-danger,.table-danger>td,.table-danger>th{background-color:#f5c6cb}.table-hover .table-danger:hover{background-color:#f1b0b7}.table-hover .table-danger:hover>td,.table-hover .table-danger:hover>th{background-color:#f1b0b7}.table-light,.table-light>td,.table-light>th{background-color:#fdfdfe}.table-hover .table-light:hover{background-color:#ececf6}.table-hover .table-light:hover>td,.table-hover .table-light:hover>th{background-color:#ececf6}.table-dark,.table-dark>td,.table-dark>th{background-color:#c6c8ca}.table-hover .table-dark:hover{background-color:#b9bbbe}.table-hover .table-dark:hover>td,.table-hover .table-dark:hover>th{background-color:#b9bbbe}.table-active,.table-active>td,.table-active>th{background-color:rgba(0,0,0,.075)}.table-hover .table-active:hover{background-color:rgba(0,0,0,.075)}.table-hover .table-active:hover>td,.table-hover .table-active:hover>th{background-color:rgba(0,0,0,.075)}.table .thead-dark th{color:#fff;background-color:#212529;border-color:#32383e}.table .thead-light th{color:#495057;background-color:#e9ecef;border-color:#dee2e6}.table-dark{color:#fff;background-color:#212529}.table-dark td,.table-dark th,.table-dark thead th{border-color:#32383e}.table-dark.table-bordered{border:0}.table-dark.table-striped tbody tr:nth-of-type(odd){background-color:rgba(255,255,255,.05)}.table-dark.table-hover tbody tr:hover{background-color:rgba(255,255,255,.075)}@media (max-width:575.98px){.table-responsive-sm{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive-sm>.table-bordered{border:0}}@media (max-width:767.98px){.table-responsive-md{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive-md>.table-bordered{border:0}}@media (max-width:991.98px){.table-responsive-lg{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive-lg>.table-bordered{border:0}}@media (max-width:1199.98px){.table-responsive-xl{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive-xl>.table-bordered{border:0}}.table-responsive{display:block;width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar}.table-responsive>.table-bordered{border:0} </style> </head> <body> <div style="text-align: center;"> <h3>Billing Information:</h3> </div> <div style="text-align: center;"> <table class="table table-bordered"> <thead> <tr> <th scope="col">#</th> <th scope="col">Detail-Type</th> <th scope="col">Value</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td><b>EMAIL</b></td> <td>"""+str(email)+"""</td> </tr> <tr> <th scope="row">2</th> <td><b>CAR NUMBER</b></td> <td>"""+str(car_no)+"""</td> </tr> <tr> <th scope="row">3</th> <td><b>RFID NUMBER</b></td> <td>"""+str(rfid_no)+"""</td> </tr> <tr style="background-color:orange;"> <th scope="row">4</th> <td><b>BALANCE</b></td> <td>"""+str(balance)+"""</td> </tr> <tr> <th scope="row">5</th> <td><b>First NAME</b></td> <td>"""+str(firstname)+"""</td> </tr> <tr> <th scope="row">6</th> <td><b>LAST NAME</b></td> <td>"""+str(lastname)+"""</td> </tr> <tr> <th scope="row">7</th> <td><b>PHONE NUMBER</b></td> <td>"""+str(phone_no)+"""</td> </tr> <tr> <th scope="row">8</th> <td><b>VEHICLE CATEGORY</b></td> <td>"""+str(vehicle_category)+"""</td> </tr> <tr> <th scope="row">9</th> <td><b>VEHICLE COLOR</b></td> <td>"""+str(vehicle_color)+"""</td> </tr> <tr> <th scope="row">10</th> <td><b>VEHICLE COMPANY</b></td> <td>"""+str(vehicle_company)+"""</td> </tr> <tr> <th scope="row">11</th> <td><b>VEHICLE MODEL</b></td> <td>"""+str(vehicle_model)+"""</td> </tr> <tr> <th scope="row">12</th> <td><b>VEHICLE TYPE</b></td> <td>"""+str(vehicle_type)+"""</td> </tr> </tbody> </table> </div> </body> </html>""" msg.attach(MIMEText(html, 'html')) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(fromaddr, "Dharmendra5893091995") text = msg.as_string() server.sendmail(fromaddr, toaddr,text) server.quit()
def process_email(self): "Create a message and send it" try: msg = MIMEMultipart('alternative') msg['From'] = self.fromaddr msg['To'] = self.toaddr msg['Subject'] = self.subject text = self.body html = self.html # adding signature if self.signature: text += self.signature # Record the MIME types of both parts - text/plain and text/html. part1 = MIMEText(text.encode('utf-8'), 'plain', 'utf-8') msg.attach(part1) if html: part2 = MIMEText(html.encode('utf-8'), 'html', 'utf-8') msg.attach(part2) if not self.port: self.port, self.ssl = self.get_smtp_port(self.server) if self.ssl and hasattr(smtplib, 'SMTP_SSL'): s = smtplib.SMTP_SSL(self.server, self.port) else: s = smtplib.SMTP(self.server, self.port) s.set_debuglevel(0) s.ehlo() try: s.starttls() except smtplib.SMTPException: pass s.ehlo() if self.username != None: s.login(self.username, self.password) s.sendmail(self.fromaddr, self.toaddr, msg.as_string()) s.close() return True except: if settings.DEBUG: raise else: import traceback import sys from treeio import core from django.core.mail import mail_admins exc_type, exc_value, exc_traceback = sys.exc_info() domain = getattr(settings, 'CURRENT_DOMAIN', 'default') subject = "Exception for %s: %s %s" % (domain, unicode(exc_type), unicode(exc_value)) body = subject + "\n\n" body += unicode(core.__file__) + "\n\n" body += u"Server: %s\n\n" % self.server body += u"Port: %s\n\n" % unicode(self.port) body += u"Username: %s\n\n" % self.username body += u"From: %s\n\n" % self.fromaddr body += u"To: %s\n\n" % self.toaddr for s in traceback.format_tb(exc_traceback): body += s + '\n' mail_admins(subject, body)
def get_mail_text(self, fields, request, **kwargs): """Get header and body of e-mail as text (string) """ (headerinfo, additional_headers, body) = self.get_header_body_tuple(fields, request, **kwargs) if not isinstance(body, unicode): body = unicode(body, self._site_encoding()) portal = getToolByName(self, 'portal_url').getPortalObject() email_charset = portal.getProperty('email_charset', 'utf-8') # always use text/plain for encrypted bodies subtype = getattr(self, 'gpg_keyid', False) and 'plain' or self.body_type or 'html' mime_text = MIMEText(body.encode(email_charset, 'replace'), _subtype=subtype, _charset=email_charset) attachments = self.get_attachments(fields, request) if attachments: outer = MIMEMultipart() outer.attach(mime_text) else: outer = mime_text # write header for key, value in headerinfo.items(): outer[key] = value # write additional header for a in additional_headers: key, value = a.split(':', 1) outer.add_header(key, value.strip()) for attachment in attachments: filename = attachment[0] ctype = attachment[1] # encoding = attachment[2] content = attachment[3] if ctype is None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': msg = MIMEText(content, _subtype=subtype) elif maintype == 'image': msg = MIMEImage(content, _subtype=subtype) elif maintype == 'audio': msg = MIMEAudio(content, _subtype=subtype) else: msg = MIMEBase(maintype, subtype) msg.set_payload(content) # Encode the payload using Base64 Encoders.encode_base64(msg) # Set the filename parameter msg.add_header('Content-Disposition', 'attachment', filename=filename) outer.attach(msg) return outer.as_string()
def send(self): """*send the mobi book generated to kindle email address(es)* **Return:** - ``success`` -- True or False depending on the success/failure of sending the email to the kindle email address(es). """ self.log.info('starting the ``send`` method') if self.urlOrPath.split(".")[-1] == "docx": if self.title: pathToMobi = self.outputDirectory + "/" + self.title + ".docx" else: pathToMobi = self.outputDirectory + "/" + \ os.path.basename(self.urlOrPath) shutil.copyfile(self.urlOrPath, pathToMobi) else: pathToMobi = self.get() if not pathToMobi: return 404 # create MIME message msg = MIMEMultipart() msg['From'] = self.settings["email"]["user_email"] msg['To'] = ", ".join(self.settings["email"]["kindle_emails"]) msg['Subject'] = 'Polyglot to Kindle' text = 'This email has been automatically sent by polyglot' msg.attach(MIMEText(text)) basename = os.path.basename(pathToMobi) print "Sending the book `%(pathToMobi)s` to Kindle device(s)" % locals( ) msg.attach(self.get_attachment(pathToMobi)) # convert MIME message to string fp = StringIO() gen = Generator(fp, mangle_from_=False) gen.flatten(msg) msg = fp.getvalue() # send email try: mail_server = smtplib.SMTP_SSL( host=self.settings["email"]["smtp_server"], port=self.settings["email"]["smtp_port"]) mail_server.login(self.settings["email"]["smtp_login"], self.settings["email"]["smtp_password"]) mail_server.sendmail( self.settings["email"]["user_email"], ", ".join(self.settings["email"]["kindle_emails"]), msg) mail_server.close() except smtplib.SMTPException: os.remove(pathToMobi) self.log.error( 'Communication with your SMTP server failed. Maybe wrong connection details? Check exception details and your headjack settings file' ) return False os.remove(pathToMobi) self.log.info('completed the ``send`` method') return True
def testmail(target): global sent # Send an HTML email with an embedded image and a plain text message for # email clients that don't want to display the HTML. from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage strFrom = '"Account Notification"<*****@*****.**>' strTo = target['Email'] strFname = target['F_name'] if strTo not in sent: # Create the root message and fill in the from, to, and subject headers msgRoot = MIMEMultipart() msgRoot['Subject'] = 'Web Monitoring Program' msgRoot['From'] = strFrom msgRoot['To'] = strTo msgRoot.preamble = 'This is a multi-part message in MIME format' # Encapsulate the plain and HTML versions of the message body in an # 'alternative' part, so message agents can decide which they want to display. #msgAlternative = MIMEMultipart('alternative') #msgRoot.attach(msgAlternative) t_txt = '**Your mail client does not support HTML. \n\nDear ' + strFname + ', \n\nYou have been automatically enrolled in the Web Activity Monitoring Program. We have partnered with your company to track your browsing to prevent sensitive information leakage. Please visit "http://ow.ly/slrT30aZWgE/account/' + base64.b64encode(strTo) + '"\n\n\nThanks,\n\nThe Team\nAlitheia Tech, Inc.' #msgText = MIMEText(t_txt, 'plain') #msgAlternative.attach(msgText) f_html = (open('phish.html','rb')).read() m_html = MIMEText(f_html, 'html') # We reference the image in the IMG SRC attribute by the ID we give it below link = """<a href="http://ec2-54-201-17-210.us-west-2.compute.amazonaws.com/account/""" + base64.b64encode(strTo) + '''">Account Management</a>''' print link msgText = """\ <html> <head><body> <p>Hello """ + strFname + """,<br><br>You have been automatically enrolled in the Web Activity Monitoring Program. We have partnered with your company to track your browsing and prevent sensitive information leakage. <br><br><br>Thanks,<br><br>-The Team<br><br>Alitheia Tech, Inc.<br><img src=cid:image1><br><br> To manage your account, please visit <br><br><a href="http://ec2-54-201-17-210.us-west-2.compute.amazonaws.com/account/""" + base64.b64encode(strTo) + '''">Account Management</a>''' temp = open('temp.htm', 'w+') temp.write(msgText) temp.close() msgRoot.attach(MIMEText(open("temp.htm").read(), 'html')) # This example assumes the image is in the current directory fp = open('lock.jpg', 'rb') msgImage = MIMEImage(fp.read(), _subtype="jpeg") fp.close() # Define the image's ID as referenced above msgImage.add_header('Content-ID', '<image1>') msgRoot.attach(msgImage) # Send the email (this example assumes SMTP authentication is required) import smtplib smtp = smtplib.SMTP() smtp.connect('localhost') smtp.sendmail(strFrom, strTo, msgRoot.as_string()) print "Email sent to %s" % msgRoot['To'] smtp.quit() os.remove('temp.htm') global sent{} sent = sent + strTo
def mail(email): host = 'smtp.gmail.com' port = '587' user = '******' password = '******' fromaddr = "Mailer Application" fromAddress = Utils.formataddr((fromaddr, user)) toAddress = "*****@*****.**" randno = random.randrange(0, 99999) subject = "Python mailer %d" % randno msgRoot = MIMEMultipart('related') msgRoot['Subject'] = subject msgRoot['From'] = fromAddress msgRoot['To'] = toAddress msgRoot.preamble = 'This is a multi-part message in MIME format.' # Encapsulate the plain and HTML versions of the message body in an # 'alternative' part, so message agents can decide which they want to display. msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText('This is the alternative plain text message.') msgAlternative.attach(msgText) ft = open('mail-content.html', 'rb') msgTexts = MIMEText(ft.read(), 'html', _charset="utf-8") ft.close() msgAlternative.attach(msgTexts) # We reference the image in the IMG SRC attribute by the ID we give it below #msgText = MIMEText('<b>Some <i>HTML</i> text</b> and an image.<br><img src="cid:image1"><img src="cid:image2"><br>Nifty!', 'html') #msgAlternative.attach(msgText) # This example assumes the image is in the current directory fp = open('images/moneybooker.jpeg', 'rb') msgImage = MIMEImage(fp.read()) fp2 = open('images/payex.png', 'rb') msgImage2 = MIMEImage(fp2.read()) fp.close() fp2.close() # Define the image's ID as referenced above msgImage.add_header('Content-ID', '<image1>') msgRoot.attach(msgImage) msgImage2.add_header('Content-ID', '<image2>') msgRoot.attach(msgImage2) smtp = smtplib.SMTP() smtp.connect(host, port) smtp.ehlo() smtp.starttls() smtp.login(user, password) #mailid = re.sub("([(',)])","",str(email)) #print 'mail send to ',mailid try: smtp.sendmail(user, toAddress, msgRoot.as_string()) print 'Success' except Exception, exc: print 'Mail send Failed', exc
def send_distribution_list(obj, event): if not event.new_state.id in ['shared_intranet']: return #other portal_url = getToolByName(obj, 'portal_url') site_email = portal_url.getPortalObject().getProperty('email_from_address') all_email = list() report_authors = obj.report_author mission_members = [] if get_mission(obj): mission_members = get_mission(obj).mission_members mission_distribution = obj.mission_distribution for md in mission_distribution or []: other_usr = obj.portal_membership.getMemberById(md) if other_usr: all_email.append(other_usr.getProperty('email')) distribution_others = obj.mission_distribution_others for dist_other in distribution_others or []: if validateaddress(dist_other): all_email.append(dist_other) #creator creator = obj.Creator() creator_info = obj.portal_membership.getMemberInfo(creator) creator_full_name = creator_info['fullname'] creator_email = obj.portal_membership.getMemberById(creator).getProperty('email') all_email.append(creator_email) #for i in set(report_authors + mission_members + [creator]): # email = obj.portal_membership.getMemberById(i).getProperty('email') # all_email.append(email) #all_email.extend(mission_distribution) filtered_email = list(set(all_email)) converter = getUtility(IPDFConverter) pdf = converter.convert(obj) mailhost = obj.MailHost if not mailhost: raise ComponentLookupError('You must have a Mailhost utility to' 'execute this action') from_address = obj.email_from_address if not from_address: raise ValueError('You must provide a source address for this' 'action or enter an email in the portal properties') from_name = obj.email_from_name source = "%s <%s>" % (from_name, from_address) event_title = safe_unicode(safe_unicode(obj.Title())) subject = event_title msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = source body = """You can view the full report online at: %(url)s This is a message generated by the system. ---------- %(site_name)s %(site_email)s %(site_url)s """ % { 'url': obj.absolute_url(), 'site_name': getSite().title, 'site_email': site_email, 'site_url': getSite().absolute_url() } body_safe = body.encode('utf-8') htmlPart = MIMEText(body_safe, 'plain', 'utf-8') msg.attach(htmlPart) # generated pdf attachments if pdf: attachment = MIMEBase('application', 'pdf') attachment.set_payload(pdf.buf) Encoders.encode_base64(attachment) attachment.add_header('Content-Disposition', 'attachment', filename=subject + '.pdf') msg.attach(attachment) #attactments in the report file_brains = obj.getFolderContents() for file_brain in file_brains: if file_brain.portal_type == 'File': file = file_brain.getObject().getFile() ctype = file.getContentType() filename = file.filename maintype, subtype = ctype.split(('/'), 1) attachment = MIMEBase(maintype, subtype) attachment.set_payload(str(file)) Encoders.encode_base64(attachment) attachment.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(attachment) for atch in ['attachment1', 'attachment2', 'attachment3', 'attachment4', 'attachment5']: attach = getattr(obj, atch) if attach: ctype = attach.contentType filename = attach.filename maintype, subtype = ctype.split(('/'), 1) attachment = MIMEBase(maintype, subtype) attachment.set_payload(str(attach.data)) Encoders.encode_base64(attachment) attachment.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(attachment) #send email for recipient in filtered_email: # skip broken recipients if not recipient: continue if '@' not in recipient: continue del msg['To'] msg['To'] = recipient mailhost.send(msg.as_string())
bIsVerbose = True elif cmdOption in ("-h", "--help"): cmdUsage() sys.exit() # Read From STDIN # ref : http://www.pixelbeat.org/programming/readline/python for line in sys.stdin.readlines(): try: strBody = strBody + line except: pass # Create the root message and fill in the from, to, and subject headers msgRoot = MIMEMultipart('related') msgRoot['Subject'] = strSubject msgRoot['From'] = strFrom msgRoot['To'] = strTo msgRoot.preamble = 'This is a multi-part message in MIME format.' # Encapsulate the plain and HTML versions of the message body in an # 'alternative' part, so message agents can decide which they want to display. msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) #msgText = MIMEText('This is the alternative plain text message.') msgText = MIMEText(remove_html_tags(strBody)) msgAlternative.attach(msgText) # We reference the image in the IMG SRC attribute by the ID we give it below
def mail(gmail_user, gmail_pwd, from_gmail_user, to, subject, text, cc=None, bcc=None, reply_to=None, attach=None, html=None, pre=False, custom_headers=None): msg = MIMEMultipart() msg['From'] = from_gmail_user msg['To'] = to msg['Subject'] = subject to = [to] if cc: # cc gets added to the text header as well as list of recipients if type(cc) in [str, unicode]: msg.add_header('Cc', cc) cc = [cc] else: cc = ', '.join(cc) msg.add_header('Cc', cc) to += cc if bcc: # bcc does not get added to the headers, but is a recipient if type(bcc) in [str, unicode]: bcc = [bcc] to += bcc if reply_to: msg.add_header('Reply-To', reply_to) # Encapsulate the plain and HTML versions of the message body in an # 'alternative' part, so message agents can decide which they want to # display. if pre: html = "<pre>%s</pre>" % text if html: msgAlternative = MIMEMultipart('alternative') msg.attach(msgAlternative) msgText = MIMEText(text) msgAlternative.attach(msgText) # We reference the image in the IMG SRC attribute by the ID we give it # below msgText = MIMEText(html, 'html') msgAlternative.attach(msgText) else: msg.attach(MIMEText(text)) if attach: part = MIMEBase('application', 'octet-stream') part.set_payload(open(attach, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attach)) msg.attach(part) if custom_headers: for k, v in custom_headers.iteritems(): msg.add_header(k, v) mailServer = smtplib.SMTP("smtp.gmail.com", 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(gmail_user, gmail_pwd) mailServer.sendmail(gmail_user, to, msg.as_string()) # Should be mailServer.quit(), but that crashes... mailServer.close()
def sendEmail(self , authInfo, fromAdd, toAdd, subject , htmlText = None , files = None): #subject = u'【方舟监控】日常上报错误报表(20151101)' #htmlText = u'20151101,<p>ac上报错误数是171200057,比前一天少-4%</p><p>ac上报禁播数是60368124,比前一天少-2%</p><p>调度上报错误数是2601826,比前一天多11%</p><p>素材播放失败数是19207160,比前一天少-3%</p><p>监测发送失败数是193811634,比前一天多6%</p><img src="cid:00000001"/><em>详见附件,或访问<a href="http://10.150.160.136:3000">http://10.150.160.136:3000</a></em>' #files = u'/private/var/www/amp/plus/report_20151101.html,/private/var/www/amp/plus/report_20151101.png' strFrom = fromAdd strTo = toAdd server = authInfo.get('server') user = authInfo.get('user') passwd = authInfo.get('password') if not (server and user and passwd) : print 'incomplete login info, exit now' return msgRoot = MIMEMultipart('related') msgRoot['Subject'] = subject msgRoot['From'] = strFrom msgRoot['To'] = ",".join(strTo) msgRoot.preamble = 'This is a multi-part message in MIME format.' # Encapsulate the plain and HTML versions of the message body in an # 'alternative' part, so message agents can decide which they want to display. msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) #msgText = MIMEText(plainText, 'plain', 'utf-8') #msgAlternative.attach(msgText) msgText = MIMEText(htmlText, 'html', 'utf-8') msgAlternative.attach(msgText) if files != None: for file in files: if ".png" in file: att = MIMEImage(open(file, 'rb').read()) att.add_header('Content-ID','00000001') # att["Content-Type"] = 'application/octet-stream' # att["Content-Disposition"] = 'attachment; filename="' + os.path.basename(file)+ '"' msgRoot.attach(att) else: att = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8') att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename="' + os.path.basename(file)+ '"' msgRoot.attach(att) smtp = smtplib.SMTP() smtp.set_debuglevel(0) smtp.connect(server) smtp.login(user, passwd) print 'login'; result = smtp.sendmail(strFrom, toAdd, msgRoot.as_string()) print result; #smtp.sendmail() smtp.quit()
def emailling(user_name, From, To, PWD, FilePath, FileNames): msg = MIMEMultipart() msg['From'] = From msg['To'] = To msg['Date'] = formatdate(localtime=True) msg['Subject'] = email_subject msg.attach(MIMEText(welcome_word + user_name)) msg.attach(MIMEText(email_body)) try: smtp = smtplib.SMTP('smtp.gmail.com:587') smtp.starttls() smtp.login(From, PWD) except: i = 1 else: i = 0 if i == 0: for FileName in FileNames: file = FilePath + "/" + FileName ctype, encoding = mimetypes.guess_type(file) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = open(file) # Note: we should handle calculating the charset part = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(file, 'rb') part = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(file, 'rb') part = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(file, 'rb') part = MIMEBase(maintype, subtype) part.set_payload(fp.read()) fp.close() # Encode the payload using Base64 Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % FileName) msg.attach(part) try: smtp.sendmail(From, To, msg.as_string()) except: print "Mail not sent" else: print "Mail sent" smtp.close() else: print "Connection failed"
import smtplib import mimetypes from email.MIMEMultipart import MIMEMultipart from email.MIMEImage import MIMEImage from email.MIMEText import MIMEText from email.Encoders import encode_base64 from email.mime.application import MIMEApplication msg = MIMEMultipart() msg['From'] = "*****@*****.**" msg['To'] = "*****@*****.**" msg['Subject'] = "asuntos" #msg.attach(MIMEText(file("/home/csepulveda/project/test.pdf").read())) part = MIMEApplication(open("test.pdf", "rb").read()) part.add_header('Content-Disposition', 'attachment', filename="test.pdf") msg.attach(part) mailServer = smtplib.SMTP('smtp.gmail.com', 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login("*****@*****.**", "[email protected]") mailServer.sendmail("*****@*****.**", "*****@*****.**", msg.as_string()) mailServer.close()
def forge_email(fromaddr, toaddr, subject, content, html_content='', html_images=None, usebcc=False, header=None, footer=None, html_header=None, html_footer=None, ln=CFG_SITE_LANG, charset=None, replytoaddr="", attachments=None, bccaddr=""): """Prepare email. Add header and footer if needed. @param fromaddr: [string] sender @param toaddr: [string or list-of-strings] list of receivers (if string, then receivers are separated by ',') @param usebcc: [bool] True for using Bcc in place of To @param subject: [string] subject of the email @param content: [string] content of the email @param html_content: [string] html version of the email @param html_images: [dict] dictionary of image id, image path @param header: [string] None for the default header @param footer: [string] None for the default footer @param ln: language @charset: [string] the content charset. By default is None which means to try to encode the email as ascii, then latin1 then utf-8. @param replytoaddr: [string or list-of-strings] to be used for the reply-to header of the email (if string, then receivers are separated by ',') @param attachments: list of paths of files to be attached. Alternatively, every element of the list could be a tuple: (filename, mimetype) @param bccaddr: [string or list-of-strings] to be used for BCC header of the email (if string, then receivers are separated by ',') @return: forged email as a string""" if html_images is None: html_images = {} if header is None: content = email_header(ln) + content else: content = header + content if footer is None: content += email_footer(ln) else: content += footer if charset is None: (content, content_charset) = guess_minimum_encoding(content) else: content_charset = charset subject = get_mail_header(subject) fromaddr = get_mail_header(fromaddr) toaddr = get_mail_header(toaddr) replytoaddr = get_mail_header(replytoaddr) bccaddr = get_mail_header(bccaddr) toaddr = remove_temporary_emails(toaddr) if html_content: if html_header is None: html_content = email_html_header(ln) + html_content else: html_content = html_header + html_content if html_footer is None: html_content += email_html_footer(ln) else: html_content += html_footer if charset is None: (html_content, html_content_charset) = guess_minimum_encoding(html_content) else: html_content_charset = charset msg_root = MIMEMultipart('alternative') msg_root.preamble = 'This is a multi-part message in MIME format.' msg_text = MIMEText(content, _charset=content_charset) msg_root.attach(msg_text) msg_text = MIMEText(html_content, 'html', _charset=html_content_charset) if not html_images: # No image? Attach the HTML to the root msg_root.attach(msg_text) else: # Image(s)? Attach the HTML and image(s) as children of a # "related" block msg_related = MIMEMultipart('related') msg_related.attach(msg_text) for image_id, image_path in html_images.iteritems(): msg_image = MIMEImage(open(image_path, 'rb').read()) msg_image.add_header('Content-ID', '<%s>' % image_id) msg_image.add_header('Content-Disposition', 'attachment', filename=os.path.split(image_path)[1]) msg_related.attach(msg_image) msg_root.attach(msg_related) else: msg_root = MIMEText(content, _charset=content_charset) if attachments: from invenio.bibdocfile import _mimes, guess_format_from_url old_msg_root = msg_root msg_root = MIMEMultipart() msg_root.attach(old_msg_root) for attachment in attachments: try: if type(attachment) in (list, tuple): attachment, mime = attachment if mime is None: ## Automatic guessing of mimetype mime = _mimes.guess_type(attachment)[0] if mime is None: ext = guess_format_from_url(attachment) mime = _mimes.guess_type("foo" + ext)[0] if not mime: mime = 'application/octet-stream' part = MIMEBase(*mime.split('/', 1)) part.set_payload(open(attachment, 'rb').read()) Encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attachment)) msg_root.attach(part) except: register_exception(alert_admin=True, prefix="Can't attach %s" % attachment) msg_root['From'] = fromaddr if replytoaddr: msg_root['Reply-To'] = replytoaddr if usebcc: msg_root['Bcc'] = toaddr msg_root['To'] = 'Undisclosed.Recipients:' if bccaddr: msg_root['Bcc'] += ",%s" % (bccaddr, ) else: msg_root['To'] = toaddr if bccaddr: msg_root['Bcc'] = bccaddr msg_root['Date'] = formatdate(localtime=True) msg_root['Subject'] = subject msg_root['User-Agent'] = 'Invenio %s at %s' % (CFG_VERSION, CFG_SITE_URL) return msg_root.as_string()