def sendEmail(send_from, send_to, subject, text, cc_to=[], files=[], server="192.168.42.13"): assert type(send_to)==list assert type(files)==list msg=MIMEMultipart() msg.set_charset("utf-8") msg['From']=send_from msg['To']=COMMASPACE.join(send_to) if cc_to: assert type(cc_to)==list msg['cc']=COMMASPACE.join(cc_to) send_to.extend(cc_to) msg['Date']=formatdate(localtime=True) msg['Subject']=subject msg.attach(MIMEText(text)) for f in files: part=MIMEBase('application', "octet-stream") part.set_payload(open(f, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"'%Header(os.path.basename(f), 'utf-8')) msg.attach(part) smtp=smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send_mail(send_to, subject, text, file): msg = MIMEMultipart() msg['From'] = 'ITLand.Root <*****@*****.**>' msg['To'] = send_to msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) 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) #server = smtplib.SMTP('smtp.gmail.com:587') #server.starttls() #server.login('jenko.kov', 'efi42dekut') #server.sendmail(send_from, send_to, msg.as_string()) #server.quit() server = smtplib.SMTP('172.16.10.254:25') server.sendmail(send_from, send_to, msg.as_string()) server.quit()
def _doemail(request): cgiParams = request.GET assert 'recipients' in cgiParams and 'url' in cgiParams and 'title' in cgiParams, "Incomplete doemail, requires recipients, url, and title" import smtplib, httplib, urlparse from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage url = cgiParams['url'] title = cgiParams['title'] recipients = cgiParams['recipients'].split(',') proto, server, path, query, frag = urlparse.urlsplit(url) if query: path += '?' + query conn = httplib.HTTPConnection(server) conn.request('GET',path) resp = conn.getresponse() assert resp.status == 200, "Failed HTTP response %s %s" % (resp.status, resp.reason) rawData = resp.read() conn.close() message = MIMEMultipart() message['Subject'] = "Graphite Image" message['To'] = ', '.join(recipients) message['From'] = 'frontend@%s' % socket.gethostname() text = MIMEText( "Image generated by the following graphite URL at %s\r\n\r\n%s" % (time.ctime(),url) ) image = MIMEImage( rawData ) image.add_header('Content-Disposition', 'attachment', filename=title + time.strftime("_%b%d_%I%M%p.png")) message.attach(text) message.attach(image) server = smtplib.SMTP(settings.SMTP_SERVER) server.sendmail('frontend@%s' % socket.gethostname(),recipients,message.as_string()) server.quit() return stdout("Successfully sent %s to %s" % (url,cgiParams['recipients']))
def send_mail(send_from, send_to, subject, text, files=[], server="localhost"): import smtplib import os 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 assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for f in files: 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)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def mail(to, subject, text, attach): msg = MIMEMultipart() print gmail_user msg['From'] = gmail_user realToString='' for s in to: realToString = realToString + s + "," # print realToString,to, [gmail_user]+[]+to msg['To'] = gmail_user#realToString msg['Subject'] = subject msg.attach(MIMEText(text)) #attach each file in the list for file in attach: 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) mailServer = smtplib.SMTP("smtp.gmail.com", 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(gmail_user, gmail_pwd) mailServer.sendmail(gmail_user, [gmail_user]+[]+to, msg.as_string()) # Should be mailServer.quit(), but that crashes... mailServer.close()
def sendEmail(to, subject, text, files=[]): assert type(to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = USERNAME msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) 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) server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo_or_helo_if_needed() server.starttls() server.ehlo_or_helo_if_needed() server.login(USERNAME,PASSWORD) server.sendmail(USERNAME, MAILTO, msg.as_string()) server.quit()
def SendEmail(authInfo, fromAdd, toAdd, subject, htmlText): 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 # 设定root信息 msgRoot = MIMEMultipart('related') msgRoot['Subject'] = subject msgRoot['From'] = strFrom msgRoot['To'] = strTo msgRoot.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText(htmlText, 'html', 'utf-8') msgAlternative.attach(msgText) #发送邮件 smtp = smtplib.SMTP() #设定调试级别,依情况而定 # smtp.set_debuglevel(1) smtp.connect(server) smtp.login(user, passwd) smtp.sendmail(strFrom, strTo, msgRoot.as_string()) smtp.quit()
def send_mail(html_part, to, subject = 'CLAT account registration email'): if html_part and to: try: import smtplib import codecs from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText server = smtplib.SMTP('smtp.gmail.com', 587) #Next, log in to the server server.ehlo() server.starttls() server.ehlo() server.login("*****@*****.**", '9999504540') msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = '*****@*****.**' msg['To'] = str(to) if html_part: part2 = MIMEText(html_part, 'html') msg.attach(part2) BODY = msg.as_string() # msg = "\nHello!" # The /n separates the message from the headers print server.sendmail("*****@*****.**", str(to), BODY) server.quit() except Exception as e: # logger.error('under edx_lms.tasks.send_mail '+str(e.args)) print '/Exception in sendng email',e.args # send_mail.retry(countdown = 2, exc = e, max_retries = 2) else: print 'E-Mail Body not define'
def notify_host(query, ip_str, action, extra_body_text): if NOTIFY_MAIL and ip_str: csvcontent = "'Last modified','IP', 'Hostname', 'Transport', 'Port', 'ASN', 'Org', 'Country', 'Product', 'Device type', 'Shodanmodule','VendorID'\n" cur = conn.cursor() cur.execute("SELECT ip_str, port, transport, modified, product, devicetype, hostname, asn, org, country_code, shodanmodule, vendorid FROM host_items WHERE ip_str = ? ORDER BY modified DESC", [ip_str]) row_result = cur.fetchall() for rec in row_result: #0:=ip_str 1:port 2: transport 3: timestamp 4:product 5:devicetype 6:hostname, 7:asn, 8:org 9:country 10:shodanmodule 11:vendorid csvcontent = csvcontent + "'%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'\n" % (rec[3], rec[0], rec[6], rec[2], rec[1], rec[7], rec[8], rec[9], rec[4], rec[5], rec[10], rec[11]) msg = MIMEMultipart() host_mailinfo = "Timestamp: %s \n IP: %s \n Hostname: %s \n ASN: %s \n Org: %s \n Country: %s" % (rec[3], ip_str, rec[6], rec[7], rec[8], rec[9]) host_mailinfo = host_mailinfo + "\n Shodan URL: https://www.shodan.io/host/%s" % ip_str query = unicode(query, 'utf-8') if action == "new": msg["Subject"] = "%s - %s - New Host : %s" % (MAIL_SUBJECT, query, ip_str) body = "New host found by Shodan monitor: \n " + host_mailinfo else: msg["Subject"] = "%s - %s - Changed Host : %s" % (MAIL_SUBJECT, query, ip_str) body = "Changed host found by Shodan monitor: \n " + host_mailinfo body = body + extra_body_text msg["From"] = MAIL_FROM msg["To"] = MAIL_RCPT attachment = MIMEText(csvcontent.encode('utf-8')) attachment.add_header("Content-Disposition", "attachment", filename="shodan-asset.csv") msg.attach(MIMEText(body, "plain")) msg.attach(attachment) server = smtplib.SMTP(MAIL_SMTP) text = msg.as_string() server.sendmail(MAIL_FROM, MAIL_RCPT, text) server.quit()
def sendmail(to_list,sub,con): """发送邮件 """ # 设置服务器名称、用户名、密码以及邮件后缀 mail_host="smtp.139.com" mail_user="******" mail_pass="******" mail_postfix="mail.139.com" me = mail_user+"<"+mail_user+"@"+mail_postfix+">" msg = MIMEMultipart('related') msg['Subject'] = email.Header.Header(sub,'utf-8') msg['From'] = me msg['To'] = ";".join(to_list) msg.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgText = MIMEText(con, 'plain', 'utf-8') msgAlternative.attach(msgText) msg.attach(msgAlternative) try: s = smtplib.SMTP() s.connect(mail_host) s.login(mail_user,mail_pass) s.sendmail(me, to_list, msg.as_string()) s.quit() except Exception,e: return False
def mail(to, subject, text, attach): msg = MIMEMultipart() msg['From'] = gmail_user msg['To'] = to msg['Subject'] = subject msg.attach(MIMEText(text)) 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)) print os.path.basename msg.attach(part) 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 send_email_csv_attach(toaddrs, mail, csv_fn, fromaddr=EMAIL_SENDER_ADDR): msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddrs msg['Subject'] = 'please check attached csv file for cr status' msg.preamble = 'You will not see this in a MIME-aware mail reader.\n' # To guarantee the message ends with a newline msg.epilogue = '' #body text = MIMEText(mail) msg.attach(text) #attachment csv = MIMEBase('text', 'x-comma-separated-values') fp = open(csv_fn, 'rb') csv.set_payload(fp.read()) Encoders.encode_base64(csv) csv.add_header('Content-Disposition', 'attachment', filename=os.path.basename(csv_fn)) msg.attach(csv) server = smtplib.SMTP('remotesmtp.mot.com') server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, msg.as_string()) server.quit()
def send_file_via_mail(file, subject, message, mail_to, mail_from, smtp_server, smtp_port, mail_password_env_name): msg = MIMEMultipart() msg['From'] = mail_from msg['To'] = mail_to msg['Subject'] = subject body = message msg.attach(MIMEText(body, 'plain')) filename = file attachment = open(filename, "rb") part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % filename) msg.attach(part) server = smtplib.SMTP(smtp_server, smtp_port) server.starttls() server.login(mail_from, os.getenv(mail_password_env_name)) text = msg.as_string() server.sendmail(mail_from, mail_to, text) server.quit()
def send_email(event): email_headers = MIMEMultipart() email_headers['From'] = '' email_headers['To'] = '' if (event == 'start'): email_headers['Subject'] = "DEV AWS: Instance has been started" elif (event == 'stop'): email_headers['Subject'] = "DEV AWS: Instance has been stopped" email_body = "This email was generated automatically by Infra team" email_headers.attach(MIMEText(email_body, 'plain')) smtp = smtplib.SMTP('outlook.office365.com', '587') smtp.starttls() smtp.login('', '') email = email_headers.as_string() smtp.sendmail(email_headers['From'], email_headers['To'], email) smtp.quit()
def emailPerson(self,person,message=""): #send an email with all information of due items, account info, and overdue items self.items=items() if not type(person)==type({}): raise TypeError("You MUST send in a person dict") message="MIRL CHECKOUT SYSTEM UPDATE EMAIL\nPlease read over the information for correctness\n\n"+person['name']+' - '+person["room"]+'\n'+message+'\n' message+="Due Items:\n" cost=0 for x in self.dueItems(person): date=x[1][:10] #get a sensible date from the item message+=" due "+date+" -- cost: "+self.items.getitem(x[0])['price']+" -- "+x[0]+'\n' cost+=float(self.items.getitem(x[0])['price']) message+='\nCharges Due If Not Returned: '+str(cost) message+="\n\nPlease contact [email protected] for any questions or concerns\n\n" fullMessage=MIMEMultipart() fullMessage['From']="*****@*****.**" fullMessage["To"]=person['email'] fullMessage["Subject"]="MIRL TOOLS UPDATE" fullMessage.attach(MIMEText(message,'plain')) try: server=smtplib.SMTP() server.connect('smtp.gmail.com',587) server.starttls() server.login("*****@*****.**","labmanager232") server.sendmail("*****@*****.**",person['email'],fullMessage.as_string()) #from,to,message except Exception,r: print "UNABLE TO SEND EMAIL!!!!" print r
def __sendMail(self, sToEMail, sSubject, sContent, sFromTitle): """ 发送邮件 :param sToEMail: 目标email,多个email可以采用英文分号分开 :param sSubject: 邮件主题,utf-8编码 :param sContent: 邮件内容,utf-8编码 :param sFromTitle: 发件人名称,utf-8编码 :return: 无 """ # print 'sFromTitle', sFromTitle msg = MIMEMultipart() msg['From'] = sFromTitle.decode('utf-8').encode("gbk","ignore") + "<%s>" % (self.sAccoutFull) # sSubject = sSubject.decode('utf-8').encode("gbk","ignore") sContent = sContent.decode('utf-8').encode("gbk","ignore") msg['Subject'] = sSubject #.encode("gbk","ignore") txt = MIMEText(sContent,'html','gbk') msg.attach(txt) # send email if self.sMailHost.upper() in ['QQ.COM']: #QQ邮箱要采用SSL登录 smtp = smtplib.SMTP_SSL('smtp.qq.com', timeout=30)#连接smtp邮件服务器,端口默认是25 else: smtp = smtplib.SMTP(self.sSMTPHost) # smtp.set_debuglevel(1) #会打印邮件发送日志 smtp.login(self.sAccout,self.sPassword) for sTo in sToEMail.split(';'): if sTo: smtp.sendmail(self.sAccoutFull, sTo, msg.as_string()) smtp.quit() PrintTimeMsg('SendMail.sToEMail(%s) successfully!' % sToEMail)
def send_email(en, email_server, to): """ Send out an email copy of the note with the issues extracted""" from_name = "*****@*****.**" body = "" msg = MIMEMultipart("alternative") msg["Subject"] = "Exploratory Test Session on %s" % en.title.strip() msg["From"] = from_name msg["To"] = to issues = [] for val in en.activity: if val[2].upper() == "I": issues.append(val[1]) if len(issues) > 0: body = "<p>The following issues where identified during the test session</p>" body += "<ul>" for issue in issues: body += "<li>%s</li>" % issue body += "</ul>" body = body.encode("ascii", "ignore") en_string = en.tostring().decode("utf8") en_string = en_string.encode("ascii", "ignore") msg_body = MIMEText(body + en_string, "html") msg.attach(msg_body) # SEND THE MAIL s = smtplib.SMTP(email_server) s.sendmail(from_name, to, msg.as_string()) s.quit()
def mail(to, frm, subject, text, attach, smtphost, smtpuser, smtppass): msg = MIMEMultipart() msg['From'] = frm msg['To'] = to msg['Subject'] = subject 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) mailServer = smtplib.SMTP(smtphost, 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(smtpuser, smtppass) mailServer.sendmail(smtpuser, to, msg.as_string()) # todo, we should keep server open if we send a list of emails, do this on a to user bases for lists # Should be mailServer.quit(), but that crashes... mailServer.close()
def send_mail(send_from, send_to, subject, text, files=[], server="localhost"): assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for f in files: 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)) msg.attach(part) #Set Email smtp parameters smtp = smtplib.SMTP('smtp.gmail.com:587') smtp.starttls() smtp.login('*****@*****.**', 'pythonheat1') smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send_email(subject,message,reciver): from_email = "*****@*****.**" server = "smtp.gmail.com" port = "25" user_name = "*****@*****.**" user_passwd = '264eba9a86c5e3107310ae07757bdc2b' # формирование сообщения msg = MIMEMultipart('mixed') msg['Subject'] = subject msg['From'] = from_email msg['To'] = ', '.join(reciver) # Формируем письмо part1 = MIMEText(message, 'html','utf-8') msg.attach(part1) # отправка s = smtplib.SMTP(server, port) s.ehlo() s.starttls() s.ehlo() s.login(user_name, user_passwd) s.sendmail(from_email, msg['To'], msg.as_string()) s.quit()
def mail(to, subject, text): try: user = read_config("SMTP_USERNAME") pwd = read_config("SMTP_PASSWORD") smtp_address = read_config("SMTP_ADDRESS") # port we use, default is 25 smtp_port = int(read_config("SMTP_PORT")) smtp_from = read_config("SMTP_FROM") msg = MIMEMultipart() msg['From'] = smtp_from msg['To'] = to msg['Subject'] = subject msg.attach(MIMEText(text)) # prep the smtp server mailServer = smtplib.SMTP("%s" % (smtp_address), smtp_port) # send ehlo mailServer.ehlo() # if we aren't using open relays if user != "": # tls support? mailServer.starttls() # some servers require ehlo again mailServer.ehlo() mailServer.login(user, pwd) # send the mail mailServer.sendmail(smtp_from, to, msg.as_string()) mailServer.close() except: write_log("[!] %s: Error, Artillery was unable to log into the mail server" % (grab_time()))
def repr_mimemessage(self): from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText outer = MIMEMultipart() items = self._headers.items() items.sort() reprs = {} for name, value in items: assert ':' not in name chars = map(ord, name) assert min(chars) >= 33 and max(chars) <= 126 outer[name] = str(value) if not isinstance(value, str): typename = type(value).__name__ assert typename in vars(py.std.__builtin__) reprs[name] = typename outer['_reprs'] = repr(reprs) for name in self._blocknames: text = self._blocks[name] m = MIMEText(text) m.add_header('Content-Disposition', 'attachment', filename=name) outer.attach(m) return outer
def flush(self,Nmin): res=[] with locker.lock('accumulating_notifcations'): for key in self.cache.keys(): (subject,sender,addressee)=key if self.cache[key]['N'] <= Nmin: ## flush only above a certain amount of messages continue destination = addressee.split(COMMASPACE) text = self.cache[key]['Text'] msg = MIMEMultipart() msg['From'] = sender msg['To'] = addressee msg['Date'] = formatdate(localtime=True) new_msg_ID = make_msgid() msg['Message-ID'] = new_msg_ID msg['Subject'] = subject ## add a signature automatically text += '\n\n' text += 'McM Announcing service' #self.logger.log('Sending a message from cache \n%s'% (text)) try: msg.attach(MIMEText(text)) smtpObj = smtplib.SMTP() smtpObj.connect() smtpObj.sendmail(sender, destination, msg.as_string()) smtpObj.quit() self.cache.pop(key) res.append( subject ) except Exception as e: print "Error: unable to send email", e.__class__ return res
def mail(to, cc, subject, text, attach): '''Sends email from [email protected]''' username = "******" password = "******" msg = MIMEMultipart() msg['From'] = username msg['To'] = ", ".join(to) msg['Subject'] = subject msg['Cc'] = ", ".join(cc) msg.attach(MIMEText(text)) 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) mailServer = smtplib.SMTP("smtp.fordfound.org", 25) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() mailServer.login(username, password) mailServer.sendmail(username, to+cc, msg.as_string()) mailServer.close()
def send_mail(self, user, password, recipient, subject, message): """Method for seding mail from a a gmail account.""" server = None # MIME data msg = MIMEMultipart() msg['From'] = user msg['To'] = recipient msg['Subject'] = subject msg.attach(MIMEText(message)) # Server connection and sending email try: server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() # Not really necesary but just in case server.starttls() server.ehlo() server.login(user, password) server.sendmail(user, recipient, msg.as_string()) except: print("/!\ We got an error here, see the traceback below for more info!") print(traceback.format_exc()) else: print("The message have been successfully sent to gmail adress %s!" % recipient) finally: if server: server.close()
def send_mail(send_to, subject, text, files=[], server='localhost', username=None, password=None): send_from = '*****@*****.**' msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) for f in files: part = MIMEBase('application', 'octet-stream') part.set_payload(open(f, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % basename(f)) msg.attach(part) smtp = SMTP(server) if username is not None: smtp.login(str(username), str(password)) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def main(): msgRoot = MIMEMultipart('alternative') msgRoot.preamble = 'This is a multi-part message in MIME format.' with open(TEXT_FILE, 'r') as txt_f: text = txt_f.read() msgRoot.attach(MIMEText(text)) with open(HTML_FILE,'r') as html_f: html = html_f.read() if IMAGES: msgRelated = MIMEMultipart('related') msgRelated.attach(MIMEText(html, 'html')) for image in IMAGES: with open(image, 'rb') as img: msgImage = MIMEImage(img.read()) msgImage.add_header('Content-ID', os.path.split(image)[1]) ## clean up to remove the folder location in the for cid msgRelated.attach(msgImage) msgRoot.attach(msgRelated) else: msgRoot.attach(MIMEText(html, 'html')) if SEND: msgRoot['To'] = SEND[0] msgRoot['From'] = SEND[1] msgRoot['Subject'] = SEND[2] smtp = smtplib.SMTP('localhost') smtp.sendmail(SEND[0], SEND[1], msgRoot.as_string()) smtp.quit() print(msgRoot.as_string())
def send_mail(self, subject, body): c = self.config['gmail'] recipients = c['recipients'] mmsg = MIMEMultipart() if isinstance(recipients, list): mmsg['To'] = ", ".join(recipients) else: mmsg['To'] = recipients recipients = [recipients] mmsg['From'] = c['email'] mmsg['Subject'] = subject mmsg.attach(MIMEText(body, 'plain')) try: conn = smtplib.SMTP(c['server'], c['port']) conn.starttls() conn.login(c['email'], c['password']) conn.sendmail(c['email'], recipients, mmsg.as_string()) conn.quit() msg = "Successfully sent email: {0}" logging.info(msg.format(mmsg['Subject'])) except smtplib.SMTPException as e: msg = "Error sending email: {0} {1}" logging.info(msg.format(mmsg['Subject']), e) return False return True
def send_email(percentage): import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEImage import MIMEImage from email.MIMEText import MIMEText # Prepare actual message msg = MIMEMultipart() msg['From'] = "*****@*****.**" # change to your mail msg['To'] = "*****@*****.**" # change to your mail msg['Subject'] = "RPi Camera Alarm!" imgcv = Image("image.jpg") imgcv.save("imagesend.jpg", quality=50) # reducing quality of the image for smaller size img1 = MIMEImage(open("imagesend.jpg","rb").read(), _subtype="jpg") img1.add_header('Content-Disposition', 'attachment; filename="image.jpg"') msg.attach(img1) part = MIMEText('text', "plain") part.set_payload(("Raspberry Pi camera alarm activated with level {:f}").format(percentage)) msg.attach(part) try: server = smtplib.SMTP("mail.htnet.hr", 25) #change to your SMTP provider server.ehlo() server.starttls() server.sendmail(msg['From'], msg['To'], msg.as_string()) server.quit() print 'Successfully sent the mail' except smtplib.SMTPException as e: print(e)
def sendmail(self, destination, subject, message, attach = None): try: msg = MIMEMultipart() msg['From'] = self.username msg['Reply-to'] = self.username msg['To'] = destination msg['Subject'] = subject msg.attach(MIMEText(message)) 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) mailServer = SMTP("smtp.gmail.com", 587) mailServer.ehlo() mailServer.starttls() mailServer.ehlo() try: mailServer.login(self.username, self.password) mailServer.sendmail(self.username, destination, msg.as_string()) finally: mailServer.close() except Exception, exc: sys.exit("Failed to send mail; %s" % str(exc))
to_addr = config.get('message', 'to') if (message == MSG_TXT) and config.has_option('message', 'message'): message = config.get('message', 'message') try: msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = from_addr msg['To'] = to_addr msg.preamble = message part = MIMEBase('application', 'octet-stream') part.set_payload(open(filename, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(filename)) msg.attach(part) smtp = smtplib.SMTP(host, port) if not no_login: smtp.login(username, password) smtp.sendmail(from_addr, [to_addr], msg.as_string()) smtp.quit() except socket.gaierror: print "Can't find SMTP host %s" % HOST sys.exit(1) except IOError: print "Can't find file %s" % filename sys.exit(1)
if __name__ == '__main__': panelId_list = [ ('<PANEL_NAME>?', '<GRAPH_ID>'), ('<PANEL_NAME>?', '<GRAPH_ID>'), ] for panelId in panelId_list: download(panelId, last_day()[0], last_day()[1]) msgRoot = prepare() msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText('<TEXT>') msgAlternative.attach(msgText) msgStr = '<TEXT><br>' for panelId in panelId_list: msgStr += '<img src="cid:' + panelId[1] + '"><br>' msgText = MIMEText(msgStr, 'html') msgAlternative.attach(msgText) for panelId in panelId_list: attach_img(msgRoot, panelId[1]) send(msgRoot, '<YOUR_MAIL_ADDRESS') send(msgRoot, '<MAIL_ADDRESS2>') for panelId in panelId_list: os.remove('/tmp/img' + panelId[1] + '.png')
def sendLogs(self): import datetime import os from datetime import date, timedelta import time import socket import subprocess import Queue import urllib2 import json import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email import Encoders import gzip import shutil import subprocess sendLogsDebugMode = True noResults = True #host=socket.gethostname() host = self.host_lower if (sendLogsDebugMode): print "Verifying if there are any logs to be sent from %s..." % host with open("mainClassLog.txt", "a") as myfile: myfile.write( "\nVerifying if there are any logs to be sent from %s..." % host) url = "http://myplace.qtdev.x10.mx/api/log_delivery_date?server=%s" % host response = json.load(urllib2.urlopen(url)) #response = urllib2.urlopen(url).read() print response for units in response: noResults = False #print response[0].items() #print response[0]["UA"] unit = units["UA"] startDate = units["START_DATE"] endDate = units["END_DATE"] logYear = '17' ivgMode = unit.startswith('108') print unit if (startDate == "" or endDate == ""): SUBJECTSW = "SW logs for %s" % unit SUBJECTHW = "HW logs for %s" % unit else: SUBJECTSW = "SW logs for %s from %s to %s" % (unit, startDate, endDate) SUBJECTHW = "HW logs for %s from %s to %s" % (unit, startDate, endDate) print SUBJECTSW with open("mainClassLog.txt", "a") as myfile: myfile.write("SW logs for %s" % unit) msg = MIMEMultipart() msg['Subject'] = SUBJECTSW msg['From'] = "Truck" msg['To'] = units["EMAIL"] #msg['To'] = '*****@*****.**' hwMsg = MIMEMultipart() hwMsg['Subject'] = SUBJECTHW hwMsg['From'] = "Truck" hwMsg['To'] = units["EMAIL"] #hwMsg['To'] = '*****@*****.**' part = MIMEBase('application', "octet-stream") hwPart = MIMEBase('application', "octet-stream") if (startDate == "" or endDate == ""): #script = "./Users/" + self.host_lower + "/winlogs/myplace/main/create_temp.sh" #print(os.path.isdir("/Users/" + self.host_lower + "/winlogs/myplace/main/")) #subprocess.check_call(["sh",script, unit, "SW"], shell=True) try: subprocess.check_call([ "sh", "/Users/" + self.host_lower + "/winlogs/myplace/main/create_temp.sh", unit, "SW" ]) print "Created temp SW file..." swTempFile = True except: print "Failed to create a SW temp file... Will not be sending SW log" swTempFile = False try: subprocess.check_call([ "sh", "/Users/" + self.host_lower + "/winlogs/myplace/main/create_temp.sh", unit, "HW" ]) print "Created temp HW file..." hwTempFile = True except: print "Failed to create a HW temp file... Will not be sending HW log" hwTempFile = False #output = process.communicate()[0] else: print "NOTHING" file = "/Users/" + self.host_lower + "/winlogs/temp_" + unit + "SW.txt" hwFile = "/Users/" + self.host_lower + "/winlogs/temp_" + unit + "HW.txt" #Renaming Files fileTime = time.strftime("%H%M%S") fileDate = date.today().strftime("%m%d%Y") newFileSw = "/Users/" + self.host_lower + "/winlogs/" + unit + "SW_Pulled_" + fileDate + "_" + fileTime + "_PST.txt" newFileHw = "/Users/" + self.host_lower + "/winlogs/" + unit + "HW_Pulled_" + fileDate + "_" + fileTime + "_PST.txt" print newFileSw print newFileHw os.rename(hwFile, newFileHw) if swTempFile: #Compressing log file os.rename(file, newFileSw) print "Compressing SW log file..." with open(newFileSw, 'rb') as f_in, gzip.open(newFileSw + '.gz', 'wb') as f_out: shutil.copyfileobj(f_in, f_out) compressedFile = newFileSw + '.gz' part.set_payload(open(compressedFile, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%sSW.gz"' % unit) msg.attach(part) if hwTempFile: #Compressing log file os.rename(hwFile, newFileHw) print "Compressing HW log file..." with open(newFileHw, 'rb') as hwf_in, gzip.open(newFileHw + '.gz', 'wb') as hwf_out: shutil.copyfileobj(hwf_in, hwf_out) compressedHWFile = newFileHw + '.gz' hwPart.set_payload(open(compressedHWFile, "rb").read()) Encoders.encode_base64(hwPart) hwPart.add_header('Content-Disposition', 'attachment; filename="%sHW.gz"' % unit) hwMsg.attach(hwPart) #server = smtplib.SMTP("127.0.0.1:1025") server = smtplib.SMTP("smtp.gmail.com:587") #server.sendmail(host, "*****@*****.**", msg.as_string()) server.starttls() #server.ehlo() #server.login('qualitestx', 'Qualitest123!') server.login('qualitestx', 'Qualitest1!') if swTempFile: print "Sending SW log..." server.sendmail(host, units["EMAIL"], msg.as_string()) if hwTempFile: print "Sending HW log..." server.sendmail(host, units["EMAIL"], hwMsg.as_string()) if (sendLogsDebugMode): if (noResults): print "No logs needs to be sent." with open("mainClassLog.txt", "a") as myfile: myfile.write("\nNo logs needs to be sent.")
def write_mime(self, file, attach_treshold=5, extra_headers={}, skip_keys=None): '''Write MIME/Multipart RFC 2822 formatted data into file. file must be a file-like object, not a path. If a value is a string or a CompressedValue, it is written directly. Otherwise it must be a tuple containing the source file and an optional boolean value (in that order); the first argument can be a file name or a file-like object, which will be read and its content will become the value of this key. The file will be gzip compressed, unless the key already ends in .gz. attach_treshold specifies the maximum number of lines for a value to be included into the first inline text part. All bigger values (as well as all non-ASCII ones) will become an attachment. Extra MIME preamble headers can be specified, too, as a dictionary. skip_keys is a set/list specifying keys which are filtered out and not written to the destination file. ''' keys = self.data.keys() keys.sort() text = '' attachments = [] if 'ProblemType' in keys: keys.remove('ProblemType') keys.insert(0, 'ProblemType') for k in keys: if skip_keys and k in skip_keys: continue v = self.data[k] attach_value = None # compressed values are ready for attaching in gzip form if isinstance(v, CompressedValue): attach_value = v.gzipvalue # if it's a tuple, we have a file reference; read the contents # and gzip it elif not hasattr(v, 'find'): attach_value = '' if hasattr(v[0], 'read'): f = v[0] # file-like object else: f = open(v[0]) # file name if k.endswith('.gz'): attach_value = f.read() else: io = StringIO() gf = gzip.GzipFile(k, mode='wb', fileobj=io) while True: block = f.read(1048576) if block: gf.write(block) else: gf.close() break attach_value = io.getvalue() f.close() # binary value elif self._is_binary(v): if k.endswith('.gz'): attach_value = v else: attach_value = CompressedValue(v, k).gzipvalue # if we have an attachment value, create an attachment if attach_value: att = MIMEBase('application', 'x-gzip') if k.endswith('.gz'): att.add_header('Content-Disposition', 'attachment', filename=k) else: att.add_header('Content-Disposition', 'attachment', filename=k + '.gz') att.set_payload(attach_value) encode_base64(att) attachments.append(att) else: # plain text value if type(v) == type(u''): # convert unicode to UTF-8 str v = v.encode('UTF-8') lines = len(v.splitlines()) if lines == 1: v = v.rstrip() text += '%s: %s\n' % (k, v) elif lines <= attach_treshold: text += '%s:\n ' % k if not v.endswith('\n'): v += '\n' text += v.strip().replace('\n', '\n ') + '\n' else: # too large, separate attachment att = MIMEText(v, _charset='UTF-8') att.add_header('Content-Disposition', 'attachment', filename=k + '.txt') attachments.append(att) # create initial text attachment att = MIMEText(text, _charset='UTF-8') att.add_header('Content-Disposition', 'inline') attachments.insert(0, att) msg = MIMEMultipart() for k, v in extra_headers.iteritems(): msg.add_header(k, v) for a in attachments: msg.attach(a) print >> file, msg.as_string()
#importing the necessary classes from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText #composing email headers fromaddr = "*****@*****.**" toaddr = "*****@*****.**" msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "Python email" # body of the email to the MIME message body = "Python test mail" msg.attach(MIMEText(body, 'plain')) #For sending the mail, we have to convert the object to a string server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.ehlo() server.login("youremailusername", "password") text = msg.as_string() server.sendmail(fromaddr, toaddr, text) #Next, log in to the server server.login("youremailusername", "password") #Send the mail msg = "\nHello!" # The /n separates the message from the headers
def createEmail(self, msgdict, builderName, title, results, builds=None, patches=None, logs=None): text = msgdict['body'].encode(ENCODING) type = msgdict['type'] if 'subject' in msgdict: subject = msgdict['subject'].encode(ENCODING) else: subject = self.subject % { 'result': Results[results], 'projectName': title, 'title': title, 'builder': builderName, } assert '\n' not in subject, \ "Subject cannot contain newlines" assert type in ('plain', 'html'), \ "'%s' message type must be 'plain' or 'html'." % type if patches or logs: m = MIMEMultipart() m.attach(MIMEText(text, type, ENCODING)) else: m = Message() m.set_payload(text, ENCODING) m.set_type("text/%s" % type) m['Date'] = formatdate(localtime=True) m['Subject'] = subject m['From'] = self.fromaddr # m['To'] is added later if patches: for (i, patch) in enumerate(patches): a = self.patch_to_attachment(patch, i) m.attach(a) if logs: for log in logs: name = "%s.%s" % (log.getStep().getName(), log.getName()) if (self._shouldAttachLog(log.getName()) or self._shouldAttachLog(name)): text = log.getText() if not isinstance(text, unicode): # guess at the encoding, and use replacement symbols # for anything that's not in that encoding text = text.decode(LOG_ENCODING, 'replace') a = MIMEText(text.encode(ENCODING), _charset=ENCODING) a.add_header('Content-Disposition', "attachment", filename=name) m.attach(a) #@todo: is there a better way to do this? # Add any extra headers that were requested, doing WithProperties # interpolation if only one build was given if self.extraHeaders: if len(builds) == 1: d = builds[0].render(self.extraHeaders) else: d = defer.succeed(self.extraHeaders) @d.addCallback def addExtraHeaders(extraHeaders): for k, v in extraHeaders.items(): if k in m: twlog.msg("Warning: Got header " + k + " in self.extraHeaders " "but it already exists in the Message - " "not adding it.") m[k] = v d.addCallback(lambda _: m) return d return defer.succeed(m)
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(user1, 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, (user1, to, msg.as_string())) except Exception, e: #print "\n It appears your password was incorrect.\nPrinting response: "+(str(e)) ReturnContinue()
import smtplib from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart from email.Header import make_header from email.Utils import formatdate import os import sys import subprocess if len(sys.argv) > 1: subj = sys.argv[1] mess = sys.argv[2] else: print("Not messge") exit(0) msg = MIMEMultipart() msg['From'] = '' msg['To'] = '' msg['Subject'] = subj message = mess msg.attach(MIMEText(message)) mailserver = smtplib.SMTP_SSL('smtp.yandex.ru:465') #mailserver.ehlo() #mailserver.starttls() #mailserver.ehlo() mailserver.login('wa@wa', 'm_*******') mailserver.sendmail('', '', msg.as_string()) mailserver.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() 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)
server.starttls() server.login(fromaddr, passwd) msg = MIMEMultipart() #msg = email.message.Message() msg['From'] = "EmbeddedPi" msg['To'] = toaddr msg['Subject'] = "Embedded Pi - Features" msg.add_header('Content-Type', 'text/html') init = """ <html><head><meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1, user-scalable=no"><title>Embedded Pi - Features</title><style type="text/css"> a {color: #d80a3e;}body, #header h1, #header h2, p {margin: 0; padding: 0;} #main {border: 1px solid #cfcece;} img {display: block;} #top-message p, #bottom p {color: #3f4042; font-size: 12px; font-family: Arial, Helvetica, sans-serif; } #header h1 {color: #ffffff !important; font-family: "Lucida Grande", sans-serif; font-size: 24px; margin-bottom: 0!important; padding-bottom: 0; } #header p {color: #ffffff !important; font-family: "Lucida Grande", "Lucida Sans", "Lucida Sans Unicode", sans-serif; font-size: 12px; } h5 {margin: 0 0 0.8em 0;} h5 {font-size: 18px; color: #444444 !important; font-family: Arial, Helvetica, sans-serif; }h2 {color: #000000 !important; font-family: "Lucida Grande", sans-serif; font-size: 24px; margin-bottom: 0!important; padding-bottom: 0;} p {font-size: 12px; color: #444444 !important; font-family: "Lucida Grande", "Lucida Sans", "Lucida Sans Unicode", sans-serif; line-height: 1.5;}</style></head> """ msg.attach(MIMEText(init, 'html')) meio = """ <body><table width="100%" cellpadding="0" cellspacing="0" bgcolor="e4e4e4"><tr><td><table id="main" width="600" align="center" cellpadding="0" cellspacing="15" bgcolor="ffffff"><tr><td><table id="header" cellpadding="10" cellspacing="0" align="center" bgcolor="8fb3e9"><tr><td width="570" align="center" bgcolor="#00000000"><h1>Embedded Pi - Features</h1></td></tr></table></td></tr><tr><td><table id="content-3" cellpadding="0" cellspacing="0" align="center"><tr><h2>Historico de Temperatura</h2><img src="cid:temp" /> """ msg.attach(MIMEText(meio, 'html')) img = open('/home/pi/EmbeddedPi/scripts/graph/temp.png', 'rb').read() msgImg = MIMEImage(img, 'png') msgImg.add_header('Content-ID', '<temp>') msgImg.add_header('Content-Disposition', 'inline', filename='temp.png') msg.attach(msgImg) meio2 = """ <h2>Historico de Umidade</h2><img src="cid:umidade" />
attachHtml += attachEnd # EMAIL from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage # Define these once; use them twice! strFrom = emaiParams[0] strTo = emaiParams[1] # Create the root message and fill in the from, to, and subject headers msgRoot = MIMEMultipart('mixed') msgRoot['X-Priority'] = '2' msgRoot['Subject'] = hostname + '. DHCP server report' msgRoot['From'] = strFrom msgRoot['To'] = strTo msgRoot.preamble = 'This is a multi-part message in MIME format.' msgText = MIMEText(mailBodyHtml, 'html') msgRoot.attach(msgText) msgImage = MIMEText(attachHtml, _subtype="html") msgImage.add_header('Content-Disposition', 'attachment', filename='conectedPerDHCPServer.html') msgRoot.attach(msgImage) # SMTP # Send the email import smtplib smtp = smtplib.SMTP() #smtp.connect(smtp.mydomain.com) smtp.connect(emaiParams[2], emaiParams[3]) smtp.sendmail(strFrom, strTo.split(','), msgRoot.as_string()) smtp.quit()
# Define these once; use them twice! strFrom = '*****@*****.**' strTo = '*****@*****.**' # Create the root message and fill in the from, to, and subject headers msgRoot = MIMEMultipart('related') msgRoot['Subject'] = 'test message' 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.') msgAlternative.attach(msgText) # 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"><br>Nifty!', 'html') msgAlternative.attach(msgText) # This example assumes the image is in the current directory fp = open('test.jpg', 'rb') msgImage = MIMEImage(fp.read()) fp.close()
def send(self, torcpts, ccrcpts, mime_headers={}): from email.MIMEText import MIMEText from email.Utils import formatdate attach_diff = self.config.getbool('wiki-notification', 'attach_diff') if attach_diff: from email.MIMEMultipart import MIMEMultipart self.data["wikidiff"] = None charset = str(self._charset) stream = self.template.generate(**self.data) # don't translate the e-mail stream t = deactivate() try: body = stream.render('text', encoding=charset) finally: reactivate(t) # self.env.log.debug('Email Contents: %s', body) public_cc = self.config.getbool('wiki-notification', 'use_public_cc') headers = {} headers['X-Mailer'] = 'Trac %s, by Edgewall Software' % __version__ headers['X-Trac-Version'] = __version__ headers['X-Trac-Project'] = self.env.project_name headers['X-URL'] = self.env.project_url headers['Precedence'] = 'bulk' headers['Auto-Submitted'] = 'auto-generated' headers['Subject'] = self.subject headers['From'] = ( self.from_name, self.from_email) if self.from_name else self.from_email headers['Reply-To'] = self.replyto_email def build_addresses(rcpts): """Format and remove invalid addresses""" return filter(lambda x: x, [self.get_smtp_address(addr) for addr in rcpts]) blocked_addresses = [] def remove_dup(rcpts, all): """Remove duplicates""" tmp = [] for rcpt in rcpts: if rcpt in self.banned_addresses: self.env.log.debug("Banned Address: %s", rcpt) blocked_addresses.append(rcpt) elif not rcpt in all: tmp.append(rcpt) all.append(rcpt) return (tmp, all) toaddrs = build_addresses(torcpts) ccaddrs = build_addresses(ccrcpts) accaddrs = build_addresses( self.config.getlist('wiki-notification', 'smtp_always_cc', [])) bccaddrs = build_addresses( self.config.getlist('wiki-notification', 'smtp_always_bcc', [])) recipients = [] (toaddrs, recipients) = remove_dup(toaddrs, recipients) (ccaddrs, recipients) = remove_dup(ccaddrs, recipients) (accaddrs, recipients) = remove_dup(accaddrs, recipients) (bccaddrs, recipients) = remove_dup(bccaddrs, recipients) self.env.log.debug("Not notifying the following addresses: %s", ', '.join(blocked_addresses)) # if there is not valid recipient, leave immediately if len(recipients) < 1: self.env.log.info('no recipient for a wiki notification') return dest = self.change_author or 'anonymous' headers['X-Trac-Wiki-URL'] = self.data['link'] pcc = accaddrs if public_cc: pcc += ccaddrs if toaddrs: headers['To'] = ', '.join(toaddrs) if pcc: headers['Cc'] = ', '.join(pcc) headers['Date'] = formatdate() if attach_diff: # With MIMEMultipart the charset has to be set before any parts # are added. msg = MIMEMultipart('mixed', None, [], charset=charset) msg.preamble = 'This is a multi-part message in MIME format.' # The text Message mail = MIMEText(body, 'plain', charset) mail.add_header('Content-Disposition', 'inline', filename="message.txt") msg.attach(mail) try: # The Diff Attachment attach = MIMEText(self.wikidiff.encode('utf-8'), 'x-patch', charset) attach.add_header('Content-Disposition', 'inline', filename=self.page.name + '.diff') msg.attach(attach) except AttributeError: # We don't have a wikidiff to attach pass else: msg = MIMEText(body, 'plain', charset) self.add_headers(msg, headers) self.add_headers(msg, mime_headers) self.env.log.info("Sending notification to %s" % (recipients, )) try: NotificationSystem(self.env).send_email(self.from_email, recipients, msg.as_string()) except Exception, err: self.env.log.debug('Notification could not be sent: %r', err)
import datetime import commands # Change to your own account information to = '*****@*****.**' gmail_user = '******' gmail_password = '******' smtpserver = smtplib.SMTP('smtp.gmail.com', 587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo smtpserver.login(gmail_user, gmail_password) today = datetime.date.today() output = commands.getoutput('curl ifconfig.me') ipaddr = output.split()[-1] my_ip = 'Esta es la sala ahora mismo' msg = MIMEMultipart(my_ip) msg['Subject'] = 'Autofoto RasPi' msg['From'] = gmail_user msg['To'] = to file = open("/home/pi/jerbos.JPG", "rb") attach_image = MIMEImage(file.read()) attach_image.add_header('Content-Disposition', 'attachment; filename = "/home/pi/jerbos.PNG"') msg.attach(attach_image) smtpserver.sendmail(gmail_user, [to], msg.as_string()) smtpserver.quit()
def main(): # read in config #pdb.set_trace() try: with open(configfile, 'r') as f: configs = f.readlines() configs = [item.strip().split() for item in configs] dconfig = {} for i in configs: dconfig[i[0]] = i[1] fromaddr = dconfig['fromaddr'] toaddr = dconfig['toaddr'] user = dconfig['user'] password = dconfig['password'] smtp = dconfig['smtp'] print(dconfig) except: print("please check the format of your config.txt file") print( "if it's your first run, plese modify the config file accordingly") print("the config file is located at :%s" % (configfile)) print("-------") print(__doc__) sys.exit(0) #============================================= # add the attachment # attachment file attachments = sys.argv[1:] if len(attachments) < 1: print('check your inputs') print(__doc__) sys.exit(0) try: #pdb.set_trace() msg = MIMEMultipart() msg['Subject'] = 'convert' for file in attachments: fp = open(file, 'rb') part = MIMEBase('application', "octet-stream") part.set_payload((fp).read()) encoders.encode_base64(part) fp.close() part.add_header('Content-Transfer-Encoding', 'base64') part.add_header('Content-Disposition', 'attachment; filename="%s"' % file) msg.attach(part) # msg is an instance of MIMEMultipart() print('sending document ...') # send the attachment via email smtp = smtplib.SMTP(smtp) smtp.ehlo() smtp.starttls() smtp.login(user, password) smtp.sendmail(fromaddr, toaddr, msg.as_string()) smtp.quit() print('done! please sync your kindle') except: print("error, please check your input for config file: %s" % (configfile)) print(__doc__)
if not args.address or not args.file: print "Error: Not enough arguments. Program aborted.\n" parser.print_help() sys.exit(1) # Global debugging option DEBUG = 1 outer = MIMEMultipart() outer['From'] = args.sender outer['To'] = args.recipient outer['Subject'] = "SMTP Multipart Test message" outer.preamble = 'You will not see this in a MIME-aware mail reader.\n' body = "This is a test mail body." outer.attach(MIMEText(body, 'plain')) path = args.file filename = os.path.basename(path) # Guess the content type based on the file's extension. Encoding # will be ignored, although we should check for simple things like # gzip'd or compressed files. ctype, encoding = mimetypes.guess_type(path) 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(path) # Note: we should handle calculating the charset
def sendMail(self, destination, subject, text, sender=None, reply_msg_ID=None, accumulate=False): if not isinstance(destination, list): print "Cannot send email. destination should be a list of strings" return destination.sort() msg = MIMEMultipart() #it could happen that message are send after forking, threading and there's no current user anymore msg['From'] = sender if sender else '*****@*****.**' msg['To'] = COMMASPACE.join(destination) msg['Date'] = formatdate(localtime=True) new_msg_ID = make_msgid() msg['Message-ID'] = new_msg_ID if reply_msg_ID is not None: msg['In-Reply-To'] = reply_msg_ID msg['References'] = reply_msg_ID ## add a mark on the subjcet automatically if locator().isDev(): msg['Subject'] = '[McM-dev] ' + subject else: msg['Subject'] = '[McM] ' + subject ### accumulate messages prior to sending emails com__accumulate = settings().get_value('com_accumulate') force_com_accumulate = settings().get_value('force_com_accumulate') if force_com_accumulate or (accumulate and com__accumulate): with locker.lock('accumulating_notifcations'): # get a subject where the request name is taken out subject_type = " ".join( filter(lambda w: w.count('-') != 2, msg['Subject'].split())) addressees = msg['To'] sendee = msg['From'] key = (subject_type, sendee, addressees) if key in self.cache: self.cache[key]['Text'] += '\n\n' self.cache[key]['Text'] += text self.cache[key]['N'] += 1 else: self.cache[key] = {'Text': text, 'N': 1} #self.logger.log('Got a message in cache %s'% (self.cache.keys())) return new_msg_ID ## add a signature automatically text += '\n\n' text += 'McM Announcing service' try: msg.attach(MIMEText(text)) smtpObj = smtplib.SMTP() smtpObj.connect() smtpObj.sendmail(sender, destination, msg.as_string()) smtpObj.quit() return new_msg_ID except Exception as e: print "Error: unable to send email", e.__class__
toaddr = raw_input('To: ') sub = raw_input('Subject: ') text = raw_input('Body: ') # email account info from where we'll be sending the email from smtp_host = 'smtp.gmail.com' smtp_port = 587 user = '******' password = "******" # parts of the actual email msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = sub msg.attach(MIMEText(text)) # connect to the server server = smtplib.SMTP() server.connect(smtp_host,smtp_port) # initiate communication with server server.ehlo() # use encryption server.starttls() # login to the server server.login(user, password) # send the email
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()
template = Template(file_.read()) else: with open('/templates/quota.tpl') as file_: template = Template(file_.read()) html = template.render(username=username, percent=percent) text = html2text.html2text(html) try: msg = MIMEMultipart('alternative') msg['From'] = r.get('QW_SENDER') or "quota-warning@localhost" msg['Subject'] = r.get('QW_SUBJ') or "Quota warning" msg['Date'] = formatdate(localtime=True) text_part = MIMEText(text, 'plain', 'utf-8') html_part = MIMEText(html, 'html', 'utf-8') msg.attach(text_part) msg.attach(html_part) msg['To'] = username p = Popen([ '/usr/local/libexec/dovecot/dovecot-lda', '-d', username, '-o', '"plugin/quota=maildir:User quota:noenforcing"' ], stdout=PIPE, stdin=PIPE, stderr=STDOUT) p.communicate(input=msg.as_string()) except Exception as ex: print 'Failed to send quota notification: %s' % (ex) sys.exit(1)
dataout = pynmea2.NMEAStreamReader() while True: newdata = ser.readline() #print ("getting new lat") if newdata[0:6] == '$GPGGA': newmsg = pynmea2.parse(newdata) newlat = newmsg.latitude print(newlat) newlong = newmsg.longitude print(newlong) lat = str(newlat) lon = str(newlong) content = "http://maps.google.com/maps?q=" + lat + "," + lon Email = content msg.attach(MIMEText(Email, 'plain')) try: server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(fromaddr, pword) text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit() print("mail sent!") except: print( "error, couldnt send mail, be sure to enable non secure apps login on sender's email" ) time.sleep(1800)
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 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
class mail: def __init__(self, sender=None, server=None, port=None, sendfile=None, filepath=None, password=None): """ Sort out the given variables and if neccessary fill in default variables or give all parameters: instance = mail(sender, mailserver, port, true, "/path/to/file", password) """ self.server = server if server is not None else default_mail_server self.port = port if port is not None else default_mail_port self.sendfile = sendfile if sendfile is not None else default_sendfile self.filepath = filepath if filepath is not None else default_filepath self.sender = sender if sender is not None else default_sender self.password = password if password is not None else default_mail_password self.server = smtplib.SMTP(self.server, self.port) self.msg = MIMEMultipart() # If a password is given, use it to login to the mailserver if self.password != None: server.starttls() self.server.ehlo() server.login(self.sender, self.password) self.msg["From"] = self.sender # Check if user wants to send a file, if so read the specified file if self.sendfile.lower() == "true": fp = open(self.filepath) attachment = MIMEText(fp.read()) fp.close() # Attach the file to the message self.msg.attach(attachment) def send(self, subject, text, receipient): """ Send the mail Usage: instance.send(subject, text, [receipient1, receipent2]) """ #.subject = subject #self.text = text #self.receipient = receipient # Set subject to mail self.msg["Subject"] = subject # Set actual text of the email #body = text self.msg.attach(MIMEText(text, "plain")) # If given receipients is a list object cycle through list of receipients if type(receipient) == list: for email in receipient: # Set receipient in email header self.msg["To"] = self.email # Built the massage object message = self.msg.as_string() # Try to send mail try: self.server.sendmail(self.sender, email, message) self.server.quit() print "Success: Sent email \""+subject+"\" from \""+self.sender+"\" to \""+email+"\"" except: print "Error: Unable to send email \""+subject+"\" from \""+self.sender+"\" to \""+email+"\"" # If given receipients is not a list, just try to send the mail else: email = receipient # Set receipient in email header self.msg["To"] = email # Built the massage object message = self.msg.as_string() try: self.server.sendmail(self.sender, email, message) self.server.quit() print "Success: Sent email \""+subject+"\" from \""+self.sender+"\"" to \""+email+"\"" except: print "Error: Unable to send email \""+subject+"\" from \""+self.sender+"\" to \""+email+"\""
# Fetch records for query to get total of new users this year new_users_this_year = len(db.fetch_records(query_results, "all")) # Email summary email_summary_msg = "-" * 47 email_summary_msg += "\nSWAT Tools new user summary\n" email_summary_msg += "-" * 47 email_summary_msg += "\nLast Week (%s - %s):\t%s" % ( start_date_formatted, todays_date_formatted, str(new_users_this_week)) email_summary_msg += "\nCurrent Month (%s-%s):\t\t\t%s" % (str( todays_date.year), str( todays_date.month).zfill(2), str(new_users_this_month)) email_summary_msg += "\nCurrent Year (%s):\t\t\t\t%s\n" % (str( todays_date.year), str(new_users_this_year)) email_summary_msg += "-" * 47 # Construct MIME obj msg = MIMEMultipart() msg["From"] = EMAIL_HOST_USER msg["To"] = "*****@*****.**" msg["Subject"] = "Weekly SWAT Tools user report" msg.attach(MIMEText(email_summary_msg, "plain")) # Connect to email server, construct message elements, and send email_server = smtplib.SMTP(EMAIL_HOST) email_server.starttls() email_server.login(EMAIL_HOST_USER, EMAIL_HOST_PASSWORD) email_server.sendmail(EMAIL_HOST_USER, "*****@*****.**", msg.as_string()) email_server.quit()
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()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % filename) message.attach(part) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() print "Please enter your gmail password" password = getpass.getpass()
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 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)")
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 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