def getAttachments(msg, attachmentDirPath): for filename in os.listdir(attachmentDirPath): path = os.path.join(attachmentDirPath, filename) if not os.path.isfile(path): continue contentType, encoding = mimetypes.guess_type(path) if contentType is None or encoding is not None: contentType = 'application/octet-stream' mainType, subType = contentType.split('/', 1) fp = open(path, 'rb') if mainType == 'text': attachment = MIMEText(fp.read()) elif mainType == 'image': attachment = MIMEImage(fp.read(), _subType=subType) elif mainType == 'audio': attachment = MIMEAudio(fp.read(), _subType=subType) else: attachment = MIMEBase(mainType, subType) attachment.set_payload(fp.read()) encode_base64(attachment) fp.close() attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(path)) msg.attach(attachment)
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 _FILE(file_name): """Guess the content type based on the file's extension. Encoding will be ignored, altough we should check for simple things like gzip'd or compressed files.""" base_name = str(Header(os.path.basename(file_name))) file_type, encoding = mimetypes.guess_type(file_name) if file_type 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. file_type = "application.octet-stream" maintype, subtype = file_type.split("/", 1) if maintype == "text": fp = open(file_name) # Note : we should handle calculating the charset msg = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == "image": fp = open(file_name, "rb") msg = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == "audio": fp = open(file_name, "rb") msg = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(file_name, "rb") msg = MIMEBase(maintype, subtype) # , name=base_name) msg.set_payload(fp.read()) fp.close() # Encode the payload using Base64 Encoders.encode_base64(msg) # Set the filename parameter msg.add_header("Content-Disposition", "attachment", filename=base_name) return msg
def sendMail(self, filename, server="localhost"): msg = MIMEMultipart() msg['From'] = self.fro msg['To'] = ', '.join(self.to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = self.subject fileToSend = filename text = self.text # Set text/plain text_part = MIMEText(text, 'plain') msg.attach(text_part) ctype, encoding = mimetypes.guess_type(fileToSend) if ctype is None or encoding is not None: ctype = "application/octet-stream" maintype, subtype = ctype.split("/", 1) if maintype == "text": fp = open(fileToSend) attachment = MIMEText(fp.read(), _subtype=subtype) fp.close() attachment.add_header("Content-Disposition", "attachment", \ filename=fileToSend.split('/')[-1]) msg.attach(attachment) message = msg.as_string() message = message + text server = smtplib.SMTP('localhost', 25) server.set_debuglevel(1) server.ehlo server.sendmail(self.fro, self.to, message) server.quit()
def send_email(my_obj, f_name): # create message msg = MIMEMultipart('alternative') # generate a pickled object pik_ob = cPickle.dumps(my_obj) # attach the object file filename = f_name # f = file(pik_ob) attachment = MIMEText(pik_ob) attachment.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(attachment) # add content to log message msg['Subject'] = "This is the subject" msg['From'] = '*****@*****.**' body = """This is the body of the message""" content = MIMEText(body, 'plain') msg.attach(content) # email the message server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login('*****@*****.**', 'pythonsend') server.sendmail('*****@*****.**', '*****@*****.**', msg.as_string()) server.quit()
def get_mail_text(self, fields, request, **kwargs): """ Get header and body of e-amil as text (string) This will create both parts of the e-mail: text and the XML file """ headerinfo, additional_headers, body = self.get_header_body_tuple(fields, request, **kwargs) body_xml = self.get_mail_text_in_xml(fields, request, **kwargs) self.safe_xml_in_filesystem(body_xml) mime_text = MIMEText(body, _subtype=self.body_type or 'html', _charset=self._site_encoding()) attachments = self.get_attachments(fields, request) outer = MIMEMultipart() outer.attach(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) ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) p = MIMEBase(maintype, subtype) p.set_payload(body_xml) p.add_header('content-disposition', 'attachment', filename='form.xml') Encoders.encode_base64(p) outer.attach(p) return outer.as_string()
def send_email(sender_name, sender_email, receiver_emails, subject, body, attachment_filename, smtpserver='localhost'): """email utility function""" msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = sender_email msg['To'] = ','.join(receiver_emails) content = MIMEText(body, 'plain') msg.attach(content) f = file(attachment_filename) attachment = MIMEText(f.read()) attachment.add_header('Content-Disposition', 'attachment', filename=attachment_filename) msg.attach(attachment) try: #print msg smtp_obj = smtplib.SMTP(smtpserver) smtp_obj.sendmail(sender_email, receiver_emails, msg.as_string()) print 'Successfully sent email' except smtplib.SMTPException: print 'Error: unable to send email'
def _getAttachment(self, attachmentFilePath): contentType, encoding = mimetypes.guess_type(attachmentFilePath) if contentType is None or encoding is not None: contentType = 'application/octet-stream' mainType, subType = contentType.split('/', 1) file = open(attachmentFilePath, 'rb') if mainType == 'text': attachment = MIMEText(file.read()) elif mainType == 'message': attachment = email.message_from_file(file) elif mainType == 'image': attachment = MIMEImage(file.read(),_subType=subType) elif mainType == 'audio': attachment = MIMEAudio(file.read(),_subType=subType) else: attachment = MIMEBase(mainType, subType) attachment.set_payload(file.read()) encode_base64(attachment) file.close() attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachmentFilePath)) return attachment
def enviarMailConResultadoGeneracion(toAddr, subject, message, adjuntos=[]): global log """Sends mail""" server = smtplib.SMTP("smtp.indra.es", 25) server.starttls() ## server.set_debuglevel(1) server.login("tgcmteam", "tgcm1234") outer = MIMEMultipart() outer['To']= toAddr outer['Subject']= subject mensaje = MIMEText(message) outer.attach(mensaje) for path in adjuntos: if os.path.exists(path): fp = open(path) adj = MIMEText (fp.read(), 'html') fp.close() adj.add_header('Content-Disposition', 'attachment', filename=path) outer.attach(adj) server.sendmail("*****@*****.**", toAddr, outer.as_string()) server.close() return
def mail(to, subject, html,attach): msg = MIMEMultipart() gmail_pwd = getpass.getpass(stream=sys.stderr) msg['From'] = gmail_user msg['To'] = to msg['Subject'] = subject part = MIMEText(html, 'html') msg.attach(part) if attach!="": 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) try: 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() print 'Mail sent!' except : print 'Failure!'
def send_mail(address, attachments, title=""): msg = MIMEMultipart() msg['Subject'] = 'Mail from MicrobesFlux --' + title msg['From'] = '*****@*****.**' msg['To'] = address fromaddr = "*****@*****.**" toaddrs = [ address, ] content = MIMEText( "Dear MicrobesFlux User: Thank you for using our website. -- MicrobesFlux" ) msg.attach(content) fs = FileSystemStorage() for fname in attachments: fp = fs.open(fname, "rb") content = MIMEText(fp.read()) content.add_header('Content-Disposition', 'attachment; filename="' + fname + '"') fp.close() msg.attach(content) server = smtplib.SMTP('localhost') server.sendmail(fromaddr, toaddrs, msg.as_string()) server.quit()
def getAttachments(msg,attachmentDirPath): for filename in os.listdir(attachmentDirPath): path = os.path.join(attachmentDirPath, filename) if not os.path.isfile(path): continue contentType, encoding = mimetypes.guess_type(path) if contentType is None or encoding is not None: contentType = 'application/octet-stream' mainType, subType = contentType.split('/', 1) fp = open(path, 'rb') if mainType == 'text': attachment = MIMEText(fp.read()) elif mainType == 'image': attachment = MIMEImage(fp.read(),_subType=subType) elif mainType == 'audio': attachment = MIMEAudio(fp.read(),_subType=subType) else: attachment = MIMEBase(mainType, subType) attachment.set_payload(fp.read()) encode_base64(attachment) fp.close() attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(path)) msg.attach(attachment)
def construct_email_message(sender, to_list, cc_list, subject, mtext, attachment_list): """ # """ outer = MIMEMultipart() outer['From'] = sender outer['To'] = ', '.join(to_list) outer['Cc'] = ', '.join(cc_list) outer['Subject'] = subject outer.preample = 'You will not see this in a MIME-aware mail reader.\n' outer.epilogue = '' # plain text body msg = MIMEText(mtext + '\n\n') msg.add_header('Content-Disposition', 'inline') outer.attach(msg) # file attachments # outer.add_header('Content-Transfer-Encoding', 'base64') for att in attachment_list: if not os.path.isfile(att): continue ctype, encoding = mimetypes.guess_type(att) maintype, subtype = ctype.split('/', 1) fp = open(att, 'rb') msg = MIMEBase(maintype, subtype) # msg = MIMEBase('application', 'octet-stream') msg.set_payload(fp.read()) Encoders.encode_base64(msg) basename = att.split('/')[-1] msg.add_header('Content-Disposition', 'attachment', filename=basename) outer.attach(msg) return outer
def testGetMessage(self): from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText self.test_add('Test <tal:x replace="options/body"/>') self.MailHost.setExpected(mfrom='*****@*****.**', mto=('*****@*****.**','*****@*****.**'), filename='mail_SendAttachment.txt') for name,type,value in ( ('mfrom','string','*****@*****.**'), ('mto','string','*****@*****.**'), ('mcc','lines',('*****@*****.**',)), ('mbcc','lines',('*****@*****.**',)), ('subject','string','Hello %s there'), ): self.mt.manage_addProperty(name,value,type) msg = self.mt.as_message(subject=self.mt.subject % 'out', headers={ 'To':('*****@*****.**','*****@*****.**'), 'Subject':'cheese', }, body='Body', boundary='111', subtype='alternative') self.assertTrue(isinstance(msg,MIMEMultipart)) attachment = MIMEText('A Test Attachment',_subtype='plain') attachment.add_header('Content-Disposition', 'attachment', filename='test.txt') msg.attach(attachment) msg.send() self.MailHost.checkSent()
def testGetMessage(self): from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText self.test_add('Test <tal:x replace="options/body"/>') self.MailHost.setExpected(mfrom='*****@*****.**', mto=('*****@*****.**','*****@*****.**'), filename='mail_SendAttachment.txt') for name,type,value in ( ('mfrom','string','*****@*****.**'), ('mto','string','*****@*****.**'), ('mcc','lines',('*****@*****.**',)), ('mbcc','lines',('*****@*****.**',)), ('subject','string','Hello %s there'), ): self.mt.manage_addProperty(name,value,type) msg = self.mt.as_message(subject=self.mt.subject % 'out', headers={ 'To':('*****@*****.**','*****@*****.**'), 'Subject':'cheese', }, body='Body', boundary='111', subtype='alternative') self.failUnless(isinstance(msg,MIMEMultipart)) attachment = MIMEText('A Test Attachment',_subtype='plain') attachment.add_header('Content-Disposition', 'attachment', filename='test.txt') msg.attach(attachment) msg.send() self.MailHost.checkSent()
def getAttachment(attachmentFilePath): contentType, encoding = mimetypes.guess_type(attachmentFilePath) if contentType is None or encoding is not None: contentType = 'application/octet-stream' mainType, subType = contentType.split('/', 1) file = open(attachmentFilePath, 'rb') if mainType == 'text': attachment = MIMEText(file.read()) elif mainType == 'message': attachment = email.message_from_file(file) elif mainType == 'image': attachment = MIMEImage(file.read(), _subType=subType) elif mainType == 'audio': attachment = MIMEAudio(file.read(), _subType=subType) else: attachment = MIMEBase(mainType, subType) attachment.set_payload(file.read()) encode_base64(attachment) file.close() ## 设置附件头 attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachmentFilePath)) return attachment
def mail_closures(bugs): """Send the list of closed bugs.""" text = "" max_package = 0 max_bug = 0 bugs.sort() for bug_severity, package, bug, title in bugs: if len(package) > max_package: max_package = len(package) if len(str(bug)) > max_bug: max_bug = len(str(bug)) for idx, severity in enumerate(SEVERITY): closures = [bug for bug in bugs if bug[0] == idx] if not len(closures): continue text += "%s\n" % severity text += ("-" * len(severity)) + "\n\n" for bug_severity, package, bug, title in closures: text += "%-*s %-*d %s\n" \ % (max_package, package, max_bug, bug, title) text += "\n" message = MIMEText(text) message.add_header("From", "Tanglu Merge-o-Matic <*****@*****.**>") message.add_header("To", "Tanglu Merge-o-Matic <*****@*****.**>") message.add_header("Date", formatdate()) message.add_header("Subject", "Bugs closed in Debian") message.add_header("Message-ID", make_msgid()) send_message(message, RECIPIENTS)
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 create_message_with_attachment(params, subject, message_text, file_dir, filename): """ Create the message with an attachment """ # create a message to send message = MIMEMultipart() message['to'] = params['to'] message['from'] = params['sender'] message['subject'] = subject msg = MIMEText(message_text) message.attach(msg) path = os.path.join(file_dir, filename) content_type, encoding = mimetypes.guess_type(path) main_type, sub_type = content_type.split('/', 1) fp = open(path, 'rb') msg = MIMEImage(fp.read(), _subtype=sub_type) fp.close() msg.add_header('Content-Disposition', 'attachment', filename=filename) message.attach(msg) return {'raw': base64.urlsafe_b64encode(message.as_string())}
def send_email(from_addr, to_addr_list, cc_addr_list, subject, smtpsrv, username, password, msg_content, msg_type='plain', attchmentList=[]): #First, we compose some of the basic message headers: msg = MIMEMultipart() msg['From'] = from_addr msg['To'] = to_addr_list msg['Cc'] = cc_addr_list msg['Subject'] = subject msg_type = msg_type.lower() if msg_type == 'plain': msg.attach(MIMEText(msg_content, 'plain')) elif msg_type == 'html': msg.attach(MIMEText(msg_content, 'html')) else: return false for attachment in attchmentList: #Attach an attachment if attachment is not None: att = MIMEText(open(attachment, 'rb').read(), 'base64', 'gb2312') att["Content-Type"] = 'application/octet-stream' att.add_header("Content-Disposition", "attachment", filename = os.path.basename(attachment)) msg.attach(att) server = smtplib.SMTP() server.connect(smtpsrv) server.login(username, password) text = msg.as_string() server.sendmail(from_addr, to_addr_list, text) server.quit()
def send_mail(script_code,log_file): jsonstr=read_file("email.cfg") email_cfg=json.JSONDecoder().decode(jsonstr) import smtplib import mimetypes from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.MIMEAudio import MIMEAudio from email.MIMEImage import MIMEImage from email.Encoders import encode_base64 from email import Encoders from email.utils import COMMASPACE, formatdate #sg_root = MIMEMultipart('related') msg_root = MIMEMultipart() msg_root['From'] = os.environ["MAIL_FROM"] smtp_server = os.environ["SMTP_SERVER"] smtp_username = os.environ["SMTP_USERNAME"] smtp_password = os.environ["SMTP_PASSWORD"] mail_from = os.environ["MAIL_FROM"] mail_to_str = email_cfg["recipions"][script_code] mail_to = mail_to_str.split(";") msg_root['To'] = mail_to msg_root['Subject'] = " Batch job [%s] is done" % script_code html_mail_body=read_file(log_file) msg = MIMEMultipart() msg['Subject'] = " Batch job [%s] is done" % script_code msg.attach(MIMEText(html_mail_body,'plain','utf-8')) msg_root.attach(msg) #msg_root.attach(MIMEText(html_mail_body,'plain','utf-8')) log("script_code is %s" % script_code) if str(script_code) == '011': wbName = 'company_scores_' + str(get_last_date()) + '.xls' filePath = '/app/gmbatch/scripts/miles/statScript/xls/' + wbName fd = file(filePath,"rb") mimetype,mimeencoding = mimetypes.guess_type(filePath) if mimeencoding or (mimetype is None): mimetype = "application/octet-stream" maintype,subtype = mimetype.split("/") if maintype == "text": retval = MIMEText(fd.read(), _subtype = subtype) else: retval = MIMEBase(maintype,subtype) retval.set_payload(fd.read()) Encoders.encode_base64(retval) retval.add_header("Content-Disposition","attachment",filename = wbName) fd.close() msg.attach(retval) mailServer = smtplib.SMTP(smtp_server, 25) mailServer.ehlo() mailServer.ehlo() mailServer.login(smtp_username, smtp_password) mailServer.sendmail(mail_from, mail_to, msg.as_string()) mailServer.close() log("email send to %s" % mail_to)
def mail_closures(bugs): """Send the list of closed bugs.""" text = "" max_package = 0 max_bug = 0 bugs.sort() for bug_severity, package, bug, title in bugs: if len(package) > max_package: max_package = len(package) if len(str(bug)) > max_bug: max_bug = len(str(bug)) for idx, severity in enumerate(SEVERITY): closures = [ bug for bug in bugs if bug[0] == idx ] if not len(closures): continue text += "%s\n" % severity text += ("-" * len(severity)) + "\n\n" for bug_severity, package, bug, title in closures: text += "%-*s %-*d %s\n" \ % (max_package, package, max_bug, bug, title) text += "\n" message = MIMEText(text) message.add_header("From", "Tanglu Merge-o-Matic <*****@*****.**>") message.add_header("To", "Tanglu Merge-o-Matic <*****@*****.**>") message.add_header("Date", formatdate()) message.add_header("Subject", "Bugs closed in Debian") message.add_header("Message-ID", make_msgid()) send_message(message, RECIPIENTS)
def sendEMailMessage(data): sent_from = getProperty("email_info", "email_sent_from") + "@" + socket.gethostname() email_recipient_list = getProperty("email_info", "email_recipient_list").split(",") output_filename = getProperty("log_fileinfo", "output_filename") msg = MIMEMultipart('alternative') msg['Subject'] = getProperty( "email_info", "email_subject_header") + " " + time.strftime("%x %X") msg['From'] = sent_from msg['To'] = ",".join(email_recipient_list) msgType = MIMEText(data, 'html') msg.attach(msgType) if not getProperty("messages", "info_no_data_found") in data: fileName = output_filename f = file(fileName) attachFile = MIMEText(f.read()) attachFile.add_header('Content-Disposition', 'attachment', filename=fileName) msg.attach(attachFile) s = smtplib.SMTP("localhost") s.sendmail(sent_from, email_recipient_list, msg.as_string()) print getProperty("messages", "info_type") + " " + getProperty( "messages", "info_email_sent") s.quit()
def attach_files(msg): filename = raw_input('File name: ') try: f = open(filename, 'rb') except IOError: print 'Attachment not found' return msg ctype, encoding = mimetypes.guess_type(filename) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': part = MIMEText(f.read(), _subtype=subtype) elif maintype == 'image': part = MIMEImage(f.read(), _subtype=subtype) elif maintype == 'audio': part = MIMEAudio(f.read(), _subtype=subtype) else: part = MIMEBase(maintype, subtype) msg.set_payload(f.read()) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(filename)) msg.attach(part) f.close() return msg
def send_email(message, subject, email_to_list, files_for_attachment, email_from, password, smtp_server): msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = email_from msg['To'] = ', '.join(email_to_list) part = MIMEText(message, "plain", "utf-8") msg.attach(part) for filename in files_for_attachment: part = MIMEApplication(open(filename, 'rb').read(), "octet-stream") part.add_header('Content-Disposition', 'attachment; filename="' + filename.encode('utf-8') + '"') msg.attach(part) server = smtplib.SMTP(smtp_server) server.starttls() server.login(email_from, password) server.sendmail(msg['From'], email_to_list, msg.as_string()) server.quit() print 'Mail was sent'
def make_attach(path): path = os.path.abspath(path) contentType, encoding = mimetypes.guess_type(path) if contentType is None or encoding is not None: contentType = "application/octet-stream" main_type, sub_type = contentType.split("/", 1) f = open(path, "rb") bytes = f.read() f.close() if main_type == "text": attachment = MIMEText(bytes) elif main_type == "message": attachment = email.message_from_string(bytes) elif main_type == "image": attachment = MIMEImage(bytes, sub_type) attachment.add_header("Content-ID", "".join(("<", os.path.basename(path), ">"))) elif main_type == "audio": print sub_type attachment = MIMEAudio(bytes, sub_type) else: attachment = MIMEBase(main_type, sub_type) attachment.set_payload(bytes) encode_base64(attachment) attachment.add_header("Content-Disposition", "attachment", filename=os.path.basename(path)) return attachment
def send_email(): email_user = "******" email_pwd = "password" msg = MIMEMultipart() msg['From'] = '*****@*****.**' msg['To'] = '*****@*****.**' msg['Subject'] = 'FTP Job Failed!' body = MIMEText("Please look at attached ftpfile.log to see why the Job failed") msg.attach(body) body = MIMEApplication(open("ftpfile.log", "rb").read(), 'log', name ='ftpfile.log') body.add_header('Content-Disposition', 'attachment', filename ='ftpfile %s.log' % (datetime.now().strftime('%Y-%m-%d %H:%M:%S'))) msg.attach(body) try: server = smtplib.SMTP("smtp.gmail.com", 587) #or port 465 doesn't seem to work! server.ehlo() server.starttls() server.login(gmail_user, gmail_pwd) server.sendmail(msg['From'], msg['To'], msg.as_string()) #server.quit() server.close() print 'Successfully sent the mail' except Exception, e: print 'Failed to send email' logging.error('Email related: %s',e)
def send_email(self, attach_list, html=None): if self._path is None: return " Please set the path to email object" msg = MIMEMultipart('alternative') msg['Subject'] = self._subject msg['From'] = self._from msg['To'] = self._to if html: body = MIMEText(html, 'html') msg.attach(body) for _file in attach_list: fp = open(self._path + '/' + _file, 'rb') a = fp.read().rstrip() attachment = MIMEText(a) fp.close() attachment.add_header('Content-Disposition', 'attachment', filename=_file) msg.attach(attachment) s = smtplib.SMTP(self._smtp) s.sendmail(self._from, self._to, msg.as_string()) s.quit() print " Email has been successfully delivered"
def send_email(strMailContent): import smtplib import base64 from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText with open("strMailContent.txt","w") as outfile: outfile.write(strMailContent) recipient = "*****@*****.**" msg = MIMEMultipart() msg['Subject'] = "Testlink Polling Script Output" msg['From'] = '*****@*****.**' msg['To'] = recipient filename = "strMailContent.txt" f = file(filename) attachment = MIMEText(f.read()) attachment.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(attachment) try: smtpObj = smtplib.SMTP('mail.arubanetworks.com') smtpObj.sendmail(msg['From'], msg['To'], msg.as_string()) print "Successfully sent email" except SMTPException: print "Error: unable to send email" finally: smtpObj.quit()
def attach_files(msg): filename = raw_input('File name: ') try: f = open(filename,'rb') except IOError: print 'Attachment not found' return msg ctype, encoding = mimetypes.guess_type(filename) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': part = MIMEText(f.read(), _subtype=subtype) elif maintype == 'image': part = MIMEImage(f.read(), _subtype=subtype) elif maintype == 'audio': part = MIMEAudio(f.read(), _subtype=subtype) else: part = MIMEBase(maintype, subtype) msg.set_payload(f.read()) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(filename)) msg.attach(part) f.close() return msg
def append(self, content=None, content_file_path=None, content_encondig=None, filename=None, content_type=None, **kwargs): if content_file_path: if content_type == None: (content_type, content_encondig) = mimetypes.guess_type(content_file_path, strict=False) if content == None: with open(content_file_path, 'r') as fh: content = fh.read() content_class = content.__class__.__name__ if content_class in self.mapper: message = self.mapper[content_class](self, content, **kwargs) else: if not content_type: content_type = guess_mime_type(content, 'binary/octet-stream') (maintype, subtype) = content_type.split('/') if maintype == 'text': message = MIMEText(content, _subtype=subtype) else: message = MIMEBase(maintype, subtype) message.set_payload(content) #Dont base64 encode rfc822 message, they will not be parsed if not content_type == 'message/rfc822': Encoders.encode_base64(message) if content_encondig != None: message['Content-Encoding'] = content_encondig if filename != None: message.add_header('Content-Disposition', 'attachment', filename=filename) if message != None: self.message.attach(message) else: raise OSLibError("Empty part added to user_data")
def test_mail(request): msg = MIMEMultipart() msg['Subject'] = 'Test Multipart from tanglab' msg['From'] = '*****@*****.**' msg['To'] = '[email protected],[email protected]' msg.preamble = 'This is a test message again' fromaddr = "*****@*****.**" toaddrs = ['*****@*****.**', '*****@*****.**'] content = MIMEText( "Dear Tanglab User: Attached are the AMPL and SBML files we generated for you. -- Tanglab" ) msg.attach(content) fp = open('/research-www/engineering/tanglab/flux/temp/rak1.ampl', 'rb') ampl = MIMEText(fp.read()) ampl.add_header('Content-Disposition', 'attachment; filename="rak1.ampl"') fp.close() msg.attach(ampl) fp = open('/research-www/engineering/tanglab/flux/temp/ilo1.sbml', 'rb') sbml = MIMEText(fp.read()) sbml.add_header('Content-Disposition', 'attachment; filename="ilo1.sbml"') fp.close() msg.attach(sbml) server = smtplib.SMTP('localhost') server.sendmail(fromaddr, toaddrs, msg.as_string()) server.quit() return HttpResponse(content=" Even New Email sent. ", status=200, content_type="text/html")
def test_mail(request): msg = MIMEMultipart() msg['Subject'] = 'Test Multipart from tanglab' msg['From'] = '*****@*****.**' msg['To'] = '[email protected],[email protected]' msg.preamble = 'This is a test message again' fromaddr = "*****@*****.**" toaddrs = ['*****@*****.**', '*****@*****.**'] content = MIMEText("Dear Tanglab User: Attached are the AMPL and SBML files we generated for you. -- Tanglab") msg.attach(content) fp = open('/research-www/engineering/tanglab/flux/temp/rak1.ampl', 'rb') ampl = MIMEText(fp.read()) ampl.add_header('Content-Disposition', 'attachment; filename="rak1.ampl"') fp.close() msg.attach(ampl) fp = open('/research-www/engineering/tanglab/flux/temp/ilo1.sbml', 'rb') sbml = MIMEText(fp.read()) sbml.add_header('Content-Disposition', 'attachment; filename="ilo1.sbml"') fp.close() msg.attach(sbml) server = smtplib.SMTP('localhost') server.sendmail(fromaddr, toaddrs, msg.as_string()) server.quit() return HttpResponse(content = " Even New Email sent. ", status = 200, content_type = "text/html")
def send_mail(recipients, sender, subject, text, reply_to=None, files=[], server="localhost"): import smtplib from email.header import Header 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 if type(recipients) != list: raise UsageError("recipients must be a list") if type(files) != list: raise UsageError("files must be a list") msg = MIMEText(text.encode('utf-8'), 'plain', 'utf-8') msg['From'] = sender msg['To'] = COMMASPACE.join(recipients) msg['Date'] = formatdate(localtime=True) msg['Subject'] = Header(subject, 'utf-8') if reply_to: msg.add_header('reply-to', reply_to) 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(sender, recipients, msg.as_string() ) smtp.close()
def send_email(strMailContent): import smtplib import base64 from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText with open("strMailContent.txt", "w") as outfile: outfile.write(strMailContent) recipient = "*****@*****.**" msg = MIMEMultipart() msg['Subject'] = "Testlink Polling Script Output" msg['From'] = '*****@*****.**' msg['To'] = recipient filename = "strMailContent.txt" f = file(filename) attachment = MIMEText(f.read()) attachment.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(attachment) try: smtpObj = smtplib.SMTP('mail.arubanetworks.com') smtpObj.sendmail(msg['From'], msg['To'], msg.as_string()) print "Successfully sent email" except SMTPException: print "Error: unable to send email" finally: smtpObj.quit()
def email_logfile(log_file, subject='pyabm Log'): msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = rcParams['email_log.from'] msg['To'] = rcParams['email_log.to'] msg.preamble = 'This is a multi-part message in MIME format.' try: f = open(log_file, 'r') except IOError: logger.warning('Error reading logfile %s'%log_file) return 1 file_content = f.read() f.close() # Include the log in the body of the email and as an attachment msg.attach(MIMEText(file_content, 'plain')) attachment = MIMEText(file_content, 'plain') attachment.add_header('Content-Disposition', 'attachment', filename=log_file) msg.attach(attachment) try: if 'email_log.smtp_ssl': server = smtplib.SMTP_SSL(rcParams['email_log.smtp_server']) else: server = smtplib.SMTP(rcParams['email_log.smtp_server']) server.login(rcParams['email_log.smtp_username'], rcParams['email_log.smtp_password']) server.sendmail(rcParams['email_log.from'], rcParams['email_log.to'], msg.as_string()) server.quit() except smtplib.SMTPException: logger.warning('Error sending logfile %s via email. Check the email_log rcparams.'%log_file) return 1 return 0
def enviarMailConResultadoGeneracion(toAddr, subject, message, adjuntos=[]): """Sends mail""" server = smtplib.SMTP("smtp.indra.es", 25) server.starttls() ## server.set_debuglevel(1) server.login("tgcmteam", "tgcm2012") outer = MIMEMultipart() outer['To'] = ', '.join(toAddr) outer['Subject'] = subject mensaje = MIMEText(message) outer.attach(mensaje) for path in adjuntos: if os.path.exists(path): fp = open(path) adj = MIMEText(fp.read(), 'html') fp.close() adj.add_header('Content-Disposition', 'attachment', filename=path) outer.attach(adj) server.sendmail("*****@*****.**", toAddr, outer.as_string()) server.close() return
def createEmail(self, msgdict, builderName, title, results, build, patch=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 type in ('plain', 'html'), "'%s' message type must be 'plain' or 'html'." % type if patch 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 patch: a = MIMEText(patch[1].encode(ENCODING), _charset=ENCODING) a.add_header('Content-Disposition', "attachment", filename="source patch") 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): a = MIMEText(log.getText().encode(ENCODING), _charset=ENCODING) a.add_header('Content-Disposition', "attachment", filename=name) m.attach(a) # Add any extra headers that were requested, doing WithProperties # interpolation if necessary if self.extraHeaders: properties = build.getProperties() for k,v in self.extraHeaders.items(): k = properties.render(k) if k in m: twlog.msg("Warning: Got header " + k + " in self.extraHeaders " "but it already exists in the Message - " "not adding it.") continue m[k] = properties.render(v) return m
def __createMultipartMail(self): """ Private method to create a multipart mail message. @return string containing the mail message """ try: import sipconfig sip_version_str = sipconfig.Configuration().sip_version_str except ImportError: sip_version_str = "sip version not available" mpPreamble = ( "This is a MIME-encoded message with attachments. " "If you see this message, your mail client is not " "capable of displaying the attachments." ) msgtext = "%s\r\n----\r\n%s----\r\n%s----\r\n%s" % ( unicode(self.message.toPlainText()), Utilities.generateVersionInfo("\r\n"), Utilities.generatePluginsVersionInfo("\r\n"), Utilities.generateDistroInfo("\r\n"), ) # first part of multipart mail explains format msg = MIMEMultipart() msg["From"] = unicode(Preferences.getUser("Email")) msg["To"] = self.__toAddress msg["Subject"] = "[eric4] %s" % unicode(self.subject.text()) msg.preamble = mpPreamble msg.epilogue = "" # second part is intended to be read att = MIMEText(msgtext, _charset=unicode(Preferences.getSystem("StringEncoding"))) msg.attach(att) # next parts contain the attachments for index in range(self.attachments.topLevelItemCount()): itm = self.attachments.topLevelItem(index) maintype, subtype = str(itm.text(1)).split("/", 1) fname = unicode(itm.text(0)) name = os.path.basename(fname) if maintype == "text": att = MIMEText(open(fname, "rb").read(), _subtype=subtype) elif maintype == "image": att = MIMEImage(open(fname, "rb").read(), _subtype=subtype) elif maintype == "audio": att = MIMEAudio(open(fname, "rb").read(), _subtype=subtype) else: att = MIMEBase(maintype, subtype) att.set_payload(open(fname, "rb").read()) Encoders.encode_base64(att) att.add_header("Content-Disposition", "attachment", filename=name) msg.attach(att) return msg.as_string()
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') mime_text = MIMEText(body.encode(email_charset , 'replace'), _subtype=self.body_type or 'html', _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 Mailer(to_list, new_df=None, th1=None, Subject=None, unipath=None): mail_host = 'smtp.exmail.qq.com' mail_user = '******' mail_pwd = 'll543623711' s = smtplib.SMTP_SSL(mail_host, 465, timeout=5) s.login(mail_user, mail_pwd) def HTML_with_style(df, style=None, random_id=None): html = ''' <style> .df thead tr:first-child { background-color: #FF9224; } </style> ''' + df.to_html(justify='mid', show_dimensions=False, formatters=None, classes='df', index=False) return html if new_df is None: HTML1 = u'' else: HTML1 = HTML_with_style(new_df) header = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head>' mid = u'<br>' \ u'<br>' body = u'<img width="500" height="120" src="https://hzapp-10006163.image.myqcloud.com/hzapp1510714944" /> <br/>' \ u'<br>' tail = u'Thanks! <br/>' \ u'Nic Fang<br/>' \ '</table></body></html>' mail = header + th1 + HTML1 + mid + body + tail msg = MIMEMultipart() msgtext = MIMEText(mail.encode('utf8'), _subtype='html', _charset='utf8') msg['From'] = mail_user msg['Subject'] = Subject msg['To'] = ",".join(to_list) # msg['Cc'] = ",".join(cc_list) if unipath is not None: att1 = MIMEText(open(unipath, 'rb').read(), 'base64', 'gb2312') att1["Content-Type"] = 'application/octet-stream' att1.add_header('Content-Disposition', 'attachment', filename=(Subject + '.xlsx').encode('gb2312')) msg.attach(att1) msg.attach(msgtext) print msg['To'] print msg['Cc'] try: s.sendmail(mail_user, to_list, msg.as_string()) s.close() print '发送成功' except Exception, e: print e
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 httprequest(self, postdata): if not self.anubisURL.startswith("http://"): raise "Invalid URL, only http:// URLs are allowed: url='%s'" % ( self.anubisURL) if not postdata: raise "Invalid/No POST data supplied: postdata='%s'" % (postdata) headers = {} headers["Content-Type"] = "multipart/form-data" message = MIMEMultipart(_subtype="form-data") ### notification element part = MIMEText(None) part.set_payload(postdata["notification"], "us-ascii") part.add_header("Content-Disposition", "form-data", name="notification") message.attach(part) ### email element part = MIMEText(None) part.set_payload(postdata["email"], "us-ascii") part.add_header("Content-Disposition", "form-data", name="email") message.attach(part) ### type element part = MIMEText(None) part.set_payload(postdata["analysisType"], "us-ascii") part.add_header("Content-Disposition", "form-data", name="analysisType") message.attach(part) ### file data element part = MIMEBase('application', "octet-stream") part.set_payload(postdata['executable']['content']) ### Add content-disposition header. dispHeaders = postdata["executable"].get("headers", {}) part.add_header("Content-Disposition", "form-data", name="executable", filename=postdata["executable"]["filename"]) for dhName, dhValue in dispHeaders: part.add_header(dhName, dhValue) message.attach(part) message.epilogue = "" headerBlock, body = message.as_string().split("\n\n", 1) for hName, hValue in message.items(): headers[hName] = hValue ### Make the HTTP request and get the response. ### Precondition: 'url', 'method', 'headers', 'body' are all setup properly. scheme, netloc, path, parameters, query, fragment = urlparse.urlparse( self.anubisURL) if parameters or query or fragment: raise "Unexpected URL: parameters=%r, query=%r, fragment=%r" % ( parameters, query, fragment) try: conn = httplib.HTTPConnection(netloc) conn.request("POST", path, body, headers) response = conn.getresponse() except socket.error, e: response = ConnRes(404, e)
def createEmail(self, msgdict, builderName, projectName, results, patch=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': projectName, 'builder': builderName, } assert type in ('plain', 'html'), "'%s' message type must be 'plain' or 'html'." % type if patch 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 patch: a = MIMEText(patch[1].encode(ENCODING), _charset=ENCODING) a.add_header('Content-Disposition', "attachment", filename="source patch") 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): a = MIMEText(log.getText().encode(ENCODING),_subtype="html", _charset=ENCODING) a.add_header('Content-Disposition', "attachment", filename=name) m.attach(a) # Add any extra headers that were requested, doing WithProperties # interpolation if necessary if self.extraHeaders: for k,v in self.extraHeaders.items(): k = properties.render(k) if k in m: twlog("Warning: Got header " + k + " in self.extraHeaders " "but it already exists in the Message - " "not adding it.") continue m[k] = properties.render(v) return m
def sendAttach(msgSubject, emailBody, eventTime, endTime, cancel, msg2): CRLF = "\r\n" attendees = [msgTo] #RECIEVERS EMAIL HERE fro = re.search(r"\w*@\w*.{2,}\b", msgFrom) fro = fro.group(0) organizer = "ORGANIZER;CN="+fro+":mailto:"+fro ddtstart = eventTime dtend = endTime dtstamp = datetime.datetime.now().strftime("%Y%m%dT%H%M%S") dtstart = ddtstart.strftime("%Y%m%dT%H%M%S") dtend = dtend.strftime("%Y%m%dT%H%M%S") if cancel: inviteType = "CANCEL" seq = "1" status = "CANCELLED" else: inviteType = "REQUEST" seq = "0" status = "CONFIRMED" attendee = "" for att in attendees: attendee += "ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;RSVP=TRUE;CN="+att+";X-NUM-GUESTS=0:mailto:"+att+CRLF ical = "BEGIN:VCALENDAR"+CRLF+"PRODID:pyICSParser"+CRLF+"VERSION:2.0"+CRLF+"CALSCALE:GREGORIAN"+CRLF+"METHOD:"+inviteType+CRLF ical+="BEGIN:VTIMEZONE"+CRLF+"TZID:America/Los_Angeles"+CRLF+"BEGIN:STANDARD"+CRLF+"DTSTART:"+dtstart+CRLF+"TZOFFSETFROM:-0700"+CRLF+"TZOFFSETTO:-0800"+CRLF ical+="TZNAME:PDT"+CRLF+"END:STANDARD"+CRLF+"END:VTIMEZONE"+CRLF ical+="BEGIN:VEVENT"+CRLF+"DTSTART;TZID=America/Los_Angeles:"+dtstart+CRLF+"DTEND;TZID=America/Los_Angeles:"+dtend+CRLF+"DTSTAMP:"+dtstamp+CRLF+organizer+CRLF ical+= "UID:"+dtstart+dtend+CRLF ical+= attendee+"CREATED:"+dtstamp+CRLF+msgSubject+CRLF+"LAST-MODIFIED:"+dtstamp+CRLF+"LOCATION:"+CRLF+"SEQUENCE:"+seq+CRLF+"STATUS:"+status+CRLF ical+= "SUMMARY:"+msgSubject+CRLF+"TRANSP:OPAQUE"+CRLF+"END:VEVENT"+CRLF+"END:VCALENDAR"+CRLF part_cal = MIMEText(ical,'calendar;method=REQUEST') ical_atch = MIMEBase('application/ics',' ;name="%s"'%("invite.ics")) ical_atch.set_payload(ical) Encoders.encode_base64(ical_atch) ical_atch.add_header('Content-Disposition', 'attachment; filename="%s"'%("invite.ics")) eml_atch = MIMEBase('text/plain','') Encoders.encode_base64(eml_atch) eml_atch.add_header('Content-Transfer-Encoding', "") eml_body = MIMEText(emailBody, "plain") eml_body.add_header('Content-Disposition', 'inline') part_cal.add_header('Content-Disposition', 'inline') msg2.attach(eml_body) msg2.attach(part_cal) msg2.attach(ical_atch) #print msg.as_string() sys.stdout.write(msg2.as_string())
def send_email(TOWHO,LOG): dp = xbmcgui.DialogProgress() dp.create(".Kodi Log Emailer",'Logging Into Your Email') dp.update(0) THESMTP ,THEPORT = Servers() logging.warning(THESMTP) logging.warning(THEPORT) fromaddr=ADDON.getSetting('email') if TOWHO =='ME': toaddr=fromaddr else: toaddr=getOther() if toaddr =='[COLOR red]Cancel[/COLOR]': Show_Dialog('No Email Sent','','Email Cancelled') else: import datetime TODAY=datetime.datetime.today().strftime('[%d-%m-%Y %H:%M]') from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText fromaddr = '"Hi Message From Yourself" <%s>'% (fromaddr) msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "Your Kodi Log "+str(TODAY) body = open(THEHTML).read() content = MIMEText(body, 'html') msg.attach(content) try:filename = LOG.rsplit('\\', 1)[1] except:filename = LOG.rsplit('/', 1)[1] f = file(LOG) attachment = MIMEText(f.read()) attachment.add_header('Content-Disposition', 'attachment', filename=filename.replace('log','txt')) msg.attach(attachment) import smtplib server = smtplib.SMTP(str(THESMTP), int(THEPORT)) dp.update(50, 'Attaching Your Email',filename.replace('log','txt')) server.ehlo() server.starttls() server.ehlo() try:server.login(ADDON.getSetting('email').encode('UTF-8'),ADDON.getSetting('password').encode('UTF-8')) except Exception as e: if 'gmail' in THESMTP: if '/answer/787' in str(e): e=getMessage() return showText('[COLOR red]ERROR !![/COLOR]',str(e).replace('\\n','[CR]')) text = msg.as_string() dp.update(75, 'Sending........',filename.replace('log','txt')) server.sendmail(fromaddr, toaddr, text) dp.close() Show_Dialog('Email Sent To','[COLOR green]'+toaddr+'[/COLOR]','Also Check Junk Folder')
def sendAPI(sender, to, subject, body, attachment=None): try: service = authAPI() message = MIMEMultipart() message['to'] = to message['from'] = sender message['subject'] = subject msg = MIMEText(body, 'html') message.attach(msg) if attachment != None: mime = MimeTypes() content_type, encoding = mime.guess_type(attachment) if content_type is None or encoding is not None: content_type = 'application/octet-stream' main_type, sub_type = content_type.split('/', 1) if main_type == 'text': fp = open(attachment, 'rb') msg = MIMEText(fp.read(), _subtype=sub_type) fp.close() elif main_type == 'image': fp = open(attachment, 'rb') msg = MIMEImage(fp.read(), _subtype=sub_type) fp.close() elif main_type == 'audio': fp = open(attachment, 'rb') msg = MIMEAudio(fp.read(), _subtype=sub_type) fp.close() else: fp = open(attachment, 'rb') msg = MIMEBase(main_type, sub_type) msg.set_payload(fp.read()) fp.close() filename = os.path.basename(attachment) msg.add_header('Content-Disposition', 'attachment', filename=filename) message.attach(msg) message = { 'raw': base64.urlsafe_b64encode(message.as_string()), 'payload': { 'mimeType': 'text/html' } } message = (service.users().messages().send(userId=sender, body=message).execute()) return True, '' except Exception, error: return False, error
def mailHtmlAsAttachement(self, fileName, subject): print 'mailHtmlAsAttachement with subject "%s"' % subject import mimetypes from email import encoders from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase # getting address & smtp servers fromA, toA, smtpServ = self.getMailData() # building email mail = MIMEMultipart() mail['From'] = fromA mail['To'] = toA mail['Subject'] = subject #mail.preamble = 'Battery result in attachement \n' machineName = socket.gethostname() from email.MIMEText import MIMEText text = "Battery result on %s in attachement ...\n" % machineName msg = MIMEText(text, 'html','iso-8859-1') msg['From'] = fromA msg['To'] = toA msg['Subject'] = subject mail.attach(msg) ctype, encoding = mimetypes.guess_type(fileName) 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) try: file = open(fileName,'r') print "file %s correctly opened for mailing" % fileName msg = MIMEBase(maintype, subtype) msg.set_payload(file.read()) file.close() print "file %s correctly closed after mailing" % fileName except smtplib.SMTPException: text="file %s not found"%fileName # Encode the payload using Base64 encoders.encode_base64(msg) (head, tail) = os.path.split(fileName) newFileName = "%s-%s" %(machineName,tail) msg.add_header('Content-Disposition', 'attachment', filename=newFileName) mail.attach(msg) try: print "opening smtp" import smtplib smtp = smtplib.SMTP(smtpServ) #smtp.set_debuglevel(True) smtp.sendmail(fromA, toA, mail.as_string()) smtp.close() print "closing smtp" except smtplib.SMTPException, e: print "mailHtmlAsAttachement: error during smtp sendmail !!!" print "smtplib.SMTPException returned: %s"%e
def send_mail(filename): dat = MIMEText(file(filename).read()) dat.add_header('Content-Disposition', 'attachment', filename=filename) msg.attach(dat) session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) session.ehlo() session.starttls() session.ehlo session.login(config.sender, config.password) session.sendmail(config.sender, config.recipient,msg.as_string()) session.quit()
def _paramsToMime(params, filenames, files): """ """ mimeMsg = MIMEMultipart("form-data") for name, value in params.iteritems(): mimeItem = MIMEText(value) mimeItem.add_header("Content-Disposition", "form-data", name=name) # TODO: Handle this better...? for hdr in [ 'Content-Type', 'MIME-Version', 'Content-Transfer-Encoding' ]: del mimeItem[hdr] mimeMsg.attach(mimeItem) if filenames or files: filenames = filenames or [] files = files or [] for idx, item in enumerate(filenames + files): # TODO: This is messy, tidy it... if isinstance(item, str): # We assume it's a file path... filename = item contentType = mimetypes.guess_type(filename)[0] payload = open(filename, "rb").read() else: # We assume it's an `email.Message.Message` instance... # TODO: Make more use of the pre-encoded information? filename = item.get_filename() contentType = item.get_content_type() payload = item.get_payload(decode=True) if not contentType: contentType = "application/octet-stream" mimeItem = MIMEBase(*contentType.split("/")) mimeItem.add_header("Content-Disposition", "form-data", name="file%s" % idx, filename=filename) # TODO: Encode the payload? mimeItem.set_payload(payload) # TODO: Handle this better...? for hdr in ['MIME-Version', 'Content-Transfer-Encoding']: del mimeItem[hdr] mimeMsg.attach(mimeItem) del mimeMsg['MIME-Version'] return mimeMsg
def createAttachments(self, filenames): attachments = [] for name in filenames: path, base = os.path.split(name) source = file(name, "r") attachment = MIMEText(source.read()) attachment.add_header('Content-disposition', 'attachment', filename=base) attachments.append(attachment) return attachments
def pir(): time.sleep(2) current_state = GPIO.input(13) if current_state == 0: print "No intruders",current_state GPIO.output(3, 0) time.sleep(0.5) if current_state == 1: GPIO.output(3, 1) time.sleep(0.5) print "Intruder detected",current_state subprocess.call("fswebcam -d /dev/video0 + /home/pi/project -r 1024x768 -S 3 + pic.jpg" ,shell=True) print("pic captured") time.sleep(0.5) filePath = "pic.jpg" smtp = smtplib.SMTP('smtp.gmail.com:587') smtp.starttls() smtp.login('*****@*****.**', 'pimcp3008') ctype, encoding = mimetypes.guess_type(filePath) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = open(filePath) part = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(filePath, 'rb') part = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(filePath, 'rb') part = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(filePath, 'rb') part = MIMEBase(maintype, subtype) part.set_payload(fp.read()) fp.close() Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % filePath) 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"
def diff_part(distro, this): """Construct an e-mail part containing the current diff.""" diff_filename = diff_file(distro, this) if os.path.isfile(diff_filename): part = MIMEText(open(diff_filename).read()) elif os.path.isfile(diff_filename + ".bz2"): part = MIMEText(bz2.BZ2File(diff_filename + ".bz2").read()) else: return None part.add_header("Content-Disposition", "attachment", filename="%s" % os.path.basename(diff_filename)) return part