def sendMail(self, to_list, sub, content): me = "Admin <admin@" + self.mail_postfix + ">" msg = MIMEMultipart() msg["Accept-Charset"]="ISO-8859-1,utf-8" msg['Subject'] = sub msg['From'] = me msg['To'] = to_list txt=MIMEText(content, 'html') txt.set_charset("utf-8") msg.attach(txt) if self.attachment_path !="": msg.attach(self.attach()) try: s = smtplib.SMTP_SSL() s.connect(self.mail_host, self.mail_port) s.login(self.mail_user, self.mail_pass) s.sendmail(me, to_list, msg.as_string()) s.close() print '发送成功!' return True except Exception, e: print '发送失败!' print str(e)
def sendMail(RECIPIENT,SUBJECT,TEXT): import sys import os import re from smtplib import SMTP_SSL as SMTP # this invokes the secure SMTP protocol (port 465, uses SSL) # from smtplib import SMTP # use this for standard SMTP protocol (port 25, no encryption) from email.MIMEText import MIMEText SMTPserver = 'smtp.gmail.com' sender = '*****@*****.**' destination = [RECIPIENT] USERNAME = "******" PASSWORD = "******" # typical values for text_subtype are plain, html, xml text_subtype = 'plain' try: msg = MIMEText(TEXT, text_subtype) msg['Subject']= SUBJECT msg['From'] = sender # some SMTP servers will do this automatically, not all conn = SMTP(SMTPserver) conn.set_debuglevel(False) conn.login(USERNAME, PASSWORD) try: conn.sendmail(sender, destination, msg.as_string()) finally: conn.close() except Exception, exc: sys.exit( "mail failed; %s" % str(exc) ) # give a error message
def sendEmail(to, subject, content): retval = 1 if not(hasattr(to, "__iter__")): to = [to] destination = to text_subtype = 'plain' try: msg = MIMEText(content, text_subtype) msg['Subject'] = subject msg['From'] = sender # some SMTP servers will do this automatically, not all conn = SMTP(host=smtpHost, port=smtpPort) conn.set_debuglevel(True) #conn.login(smtpUsername, smtpPassword) try: if smtpUsername is not False: conn.ehlo() if smtpPort != 25: conn.starttls() conn.ehlo() if smtpUsername and smtpPassword: conn.login(smtpUsername, smtpPassword) else: print("::sendEmail > Skipping authentication information because smtpUsername: %s, smtpPassword: %s" % (smtpUsername, smtpPassword)) conn.sendmail(sender, destination, msg.as_string()) retval = 0 except Exception, e: print("::sendEmail > Got %s %s. Showing traceback:\n%s" % (type(e), e, traceback.format_exc())) retval = 1 finally: conn.close()
def secureSend(self, message, mto, mfrom, subject='[No Subject]', mcc=None, mbcc=None, subtype='plain', charset='us-ascii', debug=False, **kwargs): """Deprecated method attempting to maintain backwards compatibility for code depending on the SecureMailHost API.""" # Convert all our address list inputs mfrom = email_list_to_string(mfrom, charset) mto = email_list_to_string(mto, charset) mcc = email_list_to_string(mcc, charset) mbcc = email_list_to_string(mbcc, charset) # Convert to a message for adding headers. If it's already a # message, copy it to be safe. if not isinstance(message, Message): if isinstance(message, unicode): message.encode(charset) message = MIMEText(message, subtype, charset) else: message = deepcopy(message) # Add extra headers _addHeaders(message, Subject=Header(subject, charset), To=mto, Cc=mcc, From=mfrom, **dict((k, Header(v, charset)) for k, v in kwargs.iteritems())) all_recipients = [formataddr(pair) for pair in getaddresses((mto, mcc, mbcc))] # Convert message back to string for sending self._send(mfrom, all_recipients, message.as_string(), immediate=True)
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 sendEmail(text, email_class, identity_dict, email_dict, state, solved_pq = False): retries, count = 3, 0 while count < retries: try: message = composeMessage(text, email_class, identity_dict, email_dict, state, solved_pq) own_addr = identity_dict['Email'] own_name = ' '.join([identity_dict['First_name'], identity_dict['Last_name']]) destination_addr = email_dict['Reply-To'] text_subtype = 'plain' mime_msg = MIMEText(message, text_subtype) mime_msg['Subject'] = composeSubject(email_dict) mime_msg['From'] = own_name + '<' + own_addr + '>' if destination_addr in getIdentityEmails(): break mime_msg['To'] = destination_addr server_addr = identity_dict['SMTP'] conn = SMTP_SSL(server_addr) conn.set_debuglevel(False) conn.login(identity_dict['Username'], identity_dict['Password']) try: conn.sendmail(own_addr, destination_addr, mime_msg.as_string()) finally: print "Send email!" conn.close() syncGuardian(mime_msg, identity_dict) except Exception: count += 1 continue pq_status, pq_result = hasPQ(text), None if pq_status: pq_result = hasPQ(text).values()[0] return {'Date': time.ctime(), 'Sender': own_addr, 'Receiver': destination_addr, 'Subject': composeSubject(email_dict), 'Body': message, 'First_name': identity_dict['First_name'], 'Last_name': identity_dict['Last_name'], 'Origin': 'SYSTEM', 'PQ': pq_result} return None
def send_email(sender, recipient, subject, body): from smtplib import SMTP from email.MIMEText import MIMEText from email.Header import Header from email.Utils import parseaddr, formataddr # Header class is smart enough to try US-ASCII, then the charset we # provide, then fall back to UTF-8. header_charset = 'ISO-8859-1' # We must choose the body charset manually for body_charset in 'UTF-8', 'ISO-8859-1', 'US-ASCII' : try: body.encode(body_charset) except UnicodeError: pass else: break # Split real name (which is optional) and email address parts sender_name, sender_addr = parseaddr(sender) recipient_name, recipient_addr = parseaddr(recipient) # We must always pass Unicode strings to Header, otherwise it will # use RFC 2047 encoding even on plain ASCII strings. sender_name = str(Header(unicode(sender_name), header_charset)) recipient_name = str(Header(unicode(recipient_name), header_charset)) # Make sure email addresses do not contain non-ASCII characters sender_addr = sender_addr.encode('ascii') recipient_addr = recipient_addr.encode('ascii') # Create the message ('plain' stands for Content-Type: text/plain) msg = MIMEText(body.encode(body_charset), 'plain', body_charset) msg['From'] = formataddr((sender_name, sender_addr)) msg['To'] = formataddr((recipient_name, recipient_addr)) msg['Subject'] = Header(unicode(subject), header_charset) # Send the message via SMTP to localhost:25 smtp = SMTP("localhost") smtp.sendmail(sender, recipient, msg.as_string()) smtp.quit()
def sendmail(step=None, err_msg=None): from_name, to_name = _get_config() if step is None: step = '' if err_msg is None or '[ERROR]' not in err_msg: msgstr = 'Daily docs %s completed successfully' % step subject = "DOC: %s successful" % step else: msgstr = err_msg subject = "DOC: %s failed" % step import smtplib from email.MIMEText import MIMEText msg = MIMEText(msgstr) msg['Subject'] = subject msg['From'] = from_name msg['To'] = to_name server_str, port, login, pwd = _get_credentials() server = smtplib.SMTP(server_str, port) server.ehlo() server.starttls() server.ehlo() server.login(login, pwd) try: server.sendmail(from_name, to_name, msg.as_string()) finally: server.close()
def send_server_crash_mail(h): # send mail to notify that the service is crash current_time = datetime.datetime.now().strftime("%I:%M %p on %B %d, %Y") subject = "{time}, LTP on host {host} is crash.".format( time = current_time, host=h["name"]) content = mail_content_header content += "Report time : {time}\n".format(time = current_time) content += "Report host : {host}\n".format(host = h["name"]) content += "Report content : LTP on {host} is crash.\n".format( host = h["name"]) content += "\n" if h["case"] is not None: detail = "case : \"{case}\"\n".format(case = h["case"]) else: detali = "case : problem case was not detected.\n" if h["msg"] is not None: detail = "message : {msg}\n".format(msg = h["msg"]) else: detali = "message : no message is left.\n" content += detail content += "\n" content += mail_content_tail msg = MIMEText(content) msg['Subject']= subject msg['From'] = from_addr try: conn.sendmail(from_addr, to_addrs, msg.as_string()) except: logging.warning("failed to send mail.")
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 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 send(self, subject, body): try: server = smtplib.SMTP(config_email.SMTP, config_email.SMTP_PORT) server.ehlo() server.esmtp_features['auth'] = 'LOGIN PLAIN' if config_email.SMTP != 'localhost': server.login(config_email.SMTP_USERNAME, config_email.SMTP_PASSWORD) enc = 'utf-8' format = 'plain' msg = MIMEText(body, format, enc) msg['Subject'] = Header(subject, enc) #sender_name = str(Header(sender_name, enc)) #msg['From'] = formataddr((sender_name, sender)) msg['From'] = config_email.SENDER_MAIL #recipient_name = str(Header(recipient_name, enc)) #msg['To'] = formataddr((recipient_name, recipient)) recipient = ",".join(self.address_list) msg['To'] = recipient server.sendmail(config_email.SENDER_MAIL, recipient, msg.as_string()) self.logger.info("sent %s " % (subject)) except Exception, e: self.logger.exception(e) self.logger.error("cannot send %s " % (subject))
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_mail(subject, mailto, content, subtype='html', charset='euc_kr'): ''' ARA 서버에서 E-Mail을 전송하는 함수 @type subject: string @param subject: 제목 @type mailto: string @param mailto: 받는 사람 @type content: string @param content: 메일 내용 @type subtype: string @param subtype: Content-Type minor type @type charset: string @param charset: Character Set ''' from etc.arara_settings import MAIL_SENDER, MAIL_HOST try: msg = MIMEText(content, _subtype=subtype, _charset=charset) msg['Subject'] = subject msg['From'] = MAIL_SENDER msg['To'] = mailto s = smtplib.SMTP() s.connect(MAIL_HOST) s.sendmail(MAIL_SENDER, [mailto], msg.as_string()) s.quit() except Exception: raise
def _send_html(self): mhost = component.getUtility(IMailDelivery, 'cc_engine') email_addr = self.request.form.get('email', '') license_name = self.license.name license_html = self.rdfa() message_body = u""" Thank you for using a Creative Commons License for your work. You have selected %s. You should include a reference to this license on the web page that includes the work in question. Here is the suggested HTML: %s Further tips for using the supplied HTML and RDF are here: http://creativecommons.org/learn/technology/usingmarkup Thank you! Creative Commons Support [email protected] """ % (license_name, license_html) message = MIMEText(message_body.encode('utf-8'), 'plain', 'utf-8') message['Subject'] = 'Your Creative Commons License Information' message['From'] = '*****@*****.**' message['To'] = email_addr mhost.send('*****@*****.**', (email_addr,), message.as_string())
def _send(to, subject, message): if MAIL_SERVER == 'logging': from gluon.tools import Mail mail = Mail() mail.settings.server = MAIL_SERVER mail.settings.sender = MAIL_SENDER mail.settings.login = MAIL_LOGIN return mail.send(to=to, subject=subject, message=message) else: import smtplib from email.MIMEText import MIMEText from email.Utils import formatdate msg = MIMEText(message) msg['Subject'] = subject msg['From'] = MAIL_SENDER msg['To'] = to msg['Date'] = formatdate() s = smtplib.SMTP(MAIL_SERVER) try: s.sendmail(MAIL_SENDER, [to], msg.as_string()) return True finally: s.close() return False
def mail(directory): subject="[ CS 260 ][ Grade ][ REVIEW ] - Homework 3 Written" i = 0 for root, dirs, filenames in os.walk(directory): for f in filenames: content= open(os.path.join(root,f) ).read() destination = [] rex = re.compile("(.*)hw3") destination.append(rex.search(f).groups()[0] + "@drexel.edu") print "Mailing to Destination " , rex.search(f).groups()[0] try: msg = MIMEText(content, text_subtype) msg['Subject']= subject msg['From'] = "TA Nagesh<*****@*****.**>" # some SMTP servers will do this automatically, not all conn = SMTP(SMTPserver) conn.set_debuglevel(False) conn.login(USERNAME, PASSWORD) try: conn.sendmail(sender, destination, msg.as_string()) finally: conn.close() except Exception, exc: sys.exit( "mail failed; %s" % str(exc) ) # give a error message
def sendmail(to, app, attach0=False, attach1=False): from smtplib import SMTP_SSL as SMTP from email.MIMEText import MIMEText destination = [to] # read attach contentattach = '' if attach0 and not os.stat("%s" % attach0).st_size == 0: fp = open(attach0,'rb') contentattach += '------------------ Error begin\n\n' contentattach += fp.read() contentattach += '\n------------------ Error end' fp.close() if attach1 and not os.stat("%s" % attach1).st_size == 0: fp = open(attach1,'rb') contentattach += '\n\n------------------ Success begin\n\n' contentattach += fp.read() contentattach += '\n------------------ Success end' fp.close() msg = MIMEText(contentattach, 'plain') msg['Subject'] = "Mr.Script %s" % app msg['From'] = sender try: conn = SMTP(smtpserver) conn.set_debuglevel(False) conn.login(username, password) conn.sendmail(sender, destination, msg.as_string()) conn.close() except: print ' *** Error trying send a mail. Check settings.'
def PushwithMail(_msglist, _sendto): global logger import smtplib from email.MIMEText import MIMEText from email.Utils import formatdate from email.Header import Header smtpHost = 'smtp.qq.com' fromMail = username = '******' password = '******' subject = u'[%s] 自动推荐'%datetime.today().strftime('%Y/%m/%d') body = '\n'.join(_msglist) mail = MIMEText(body,'plain','utf-8') mail['Subject'] = Header(subject,'utf-8') mail['From'] = fromMail mail['To'] = _sendto mail['Date'] = formatdate() try: smtp = smtplib.SMTP_SSL(smtpHost) smtp.ehlo() smtp.login(username,password) smtp.sendmail(fromMail,_sendto,mail.as_string()) smtp.close() logger.warning('Push to %s successfully.'%_sendto) except Exception as e: logger.warning(str(e) + ' when pushing the msg with Mail.')
def enviaemail(mensagem): #Usado os site abaixo como referencia #http://www.vivaolinux.com.br/dica/Enviando-email-com-Python-e-autenticacao-no-SMTP-pelo-Linux #http://rafapinheiro.wordpress.com/2009/02/22/enviando-e-mail-com-python-pelo-gmail/ #Cria a mensagem a ser enviada msg1 = MIMEText("%s"% mensagem) #Titulo da mensagem msg1['Subject']='Aqui vai o titulo do e-mail Ex. Conversa no canal #OeSC-Livre' #Destino e destinatario msg1['From']="*****@*****.**" msg1['To']="*****@*****.**" #ativando o ssl #O caminho SMTP é do gmail(Mas pode ser alterado para o de sua preferencia) smtp = smtplib.SMTP('smtp.gmail.com:587') #inicia a troca de dados om o servidor smtp.ehlo() #ativa o tls smtp.starttls() #reinicia a troca de dados smtp.ehlo() #Efetua o login smtp.login('*****@*****.**', 'senha') #Envia o e-mail smtp.sendmail('*****@*****.**','*****@*****.**',msg1.as_string()) #Fecha a conexao smtp.quit()
def sendEmail(mailUser, mailPass, toList , topic , htmlContent): ''' toList : send to who topic : the mail subject htmlContent : the mail content ''' if htmlContent == '': print "htmlContent is null!!!" return False msg = MIMEText(htmlContent,"html","utf-8") msg["Subject"] = topic msg["From"] = sender msg["To"] = ";".join(toList.split(",")) try: s = smtplib.SMTP() s.connect(mailHost,mailPort) s.login(mailUser,mailPass) s.sendmail(sender,toList.split(","),msg.as_string()) s.close return True except Exception,e: print str(e) return False
def send_text_and_attachment_email(self, from_address, to_addresses, subject, message, attachment_text, attachment_filename='patch.diff'): """Send a Unicode message and an 8-bit attachment. See create_email for common parameter definitions. :param attachment_text: This is assumed to be an 8-bit text attachment. This assumes you want the attachment to be shown in the email. So don't use this for binary file attachments. :param attachment_filename: The name for the attachement. This will give a default name for email programs to save the attachment. """ msg, from_email, to_emails = self.create_email(from_address, to_addresses, subject, message) # Must be an 8-bit string assert isinstance(attachment_text, str) diff_payload = MIMEText(attachment_text, 'plain', '8-bit') # Override Content-Type so that we can include the name content_type = diff_payload['Content-Type'] content_type += '; name="%s"' % (attachment_filename,) diff_payload.replace_header('Content-Type', content_type) diff_payload['Content-Disposition'] = ('inline; filename="%s"' % (attachment_filename,)) msg.attach(diff_payload) self.send_email(msg, from_email, to_emails)
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 spider_closed(self, spider): if not self.result_check: me = '*****@*****.**' you = '*****@*****.**' text = u'MADELEINE_SPIDER\nНе все данные собираются с сайта (есть пустые поля), см. log.txt на сервере' subj = 'MADELEINE_SPIDER' # SMTP-сервер server = "smtp.gmail.com" port = 25 user_name = "*****@*****.**" user_passwd = "madeleine78" # формирование сообщения msg = MIMEText(text, "", "utf-8") msg['Subject'] = subj msg['From'] = me msg['To'] = you # отправка s = smtplib.SMTP(server, port) s.ehlo() s.starttls() s.ehlo() s.login(user_name, user_passwd) s.sendmail(me, you, msg.as_string()) s.quit()
def main(): msg = MIMEMultipart() msg['Subject'] = sys.argv[2] msg['To'] = recipient msg['From'] = sender part = MIMEText('text', "plain") part.set_payload(message) msg.attach(part) session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT) session.ehlo() session.starttls() session.ehlo session.login(sender, password) # Now send or store the message qwertyuiop = msg.as_string() session.sendmail(sender, recipient, qwertyuiop) session.quit() os.system('notify-send "Email sent"')
def send_email(str_to_address,\ int_email_type,\ dict_information = {}): if not _obj_smtp_server: _build_smtp_server() #Create body str_body = _list_type_body[int_email_type] if dict_information.has_key('dut_id'): str_body = str_body.replace('#DUT_ID', dict_information['dut_id']) if dict_information.has_key('port_info'): str_body = str_body.replace('#PORT_INFO', dict_information['port_info']) obj_body = MIMEText(str_body,'html') obj_body['subject'] = _list_type_subject[int_email_type] obj_body['from'] = _str_from_name obj_body['to'] = str_to_address log('INFO', 'Sending email: : subject(%s), to(%s)' % (obj_body['subject'], str_to_address)) try: _obj_smtp_server.sendmail(_str_from_address, \ str_to_address,\ obj_body.as_string()) except: log('WARNING', 'Failed to send email: subject(%s), to(%s)' % (obj_body['subject'], str_to_address)) log('ERROR', traceback.format_exc()) _build_smtp_server() else: log('INFO', 'email sent:: subject(%s), to(%s)' % (obj_body['subject'], str_to_address))
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(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 mail_feedback(search, yes_no, message): """ take the info, send it to INSPIRE feedback """ if yes_no == 'true': yes_no = 'yes' elif yes_no == 'false': yes_no = 'no' message = """ Dear INSPIRE feedback folks, A SPIRES user interacted with your box in SPIRES! They were trying the search %(search)s What they said was Did INSPIRE give results you expected? %(yes_no)s Comments: %(message)s """ % { 'search' : search, 'message' : message, 'yes_no' : yes_no } msg = MIMEText(message) msg['Subject'] = 'INSPIRE feedback originating from SPIRES:' + yes_no msg['To'] = FEEDBACK msg['From'] = CRAZYSPIRESMACHINE s = smtplib.SMTP('cernmx.cern.ch') s.sendmail(CRAZYSPIRESMACHINE, [FEEDBACK], msg.as_string()) s.quit() return True
def send_email(self, from_address, to_addresses, cc_addresses, bcc_addresses, subject, body): """ Send an email Args: to_addresses: must be a list cc_addresses: must be a list bcc_addresses: must be a list """ try: # Note: need Python 2.6.3 or more conn = SMTP_SSL(self.smtp_host, self.smtp_port) conn.login(self.user, self.password) msg = MIMEText(body, 'plain', self.email_default_encoding) msg['Subject'] = Header(subject, self.email_default_encoding) msg['From'] = from_address msg['To'] = ', '.join(to_addresses) if cc_addresses: msg['CC'] = ', '.join(cc_addresses) if bcc_addresses: msg['BCC'] = ', '.join(bcc_addresses) msg['Date'] = Utils.formatdate(localtime=True) # TODO: Attached file conn.sendmail(from_address, to_addresses, msg.as_string()) except: raise finally: conn.close()
db.session.remove() for solver_binary in db.session.query(db.SolverBinary): if solver_binary.solver.user is None: continue # only consider solvers from users solver = solver_binary.solver if db.session.query(db.SolverConfiguration).filter_by( solver_binary=solver_binary).count() == 0: print solver.name + " appears to be a new solver. Adding to all test experiments based on its competition cateogries." testing_solvers.add(solver_binary.idSolverBinary) pickle.dump(testing_solvers, open(STATE_FILE, "wb")) for competition_category in solver.competition_categories: create_test_jobs(competition_category, solver_binary) # send mail to admin account msg = MIMEText( 'Solver with ID ' + str(solver.idSolver) + ' was added and test jobs generated.'.encode('utf8'), 'plain', 'utf8') msg['Subject'] = '[SAT Challenge 2012][Admin] A solver was added' msg.set_charset('utf8') send_mail(msg, config.DEFAULT_MAIL_SENDER) testing_solvers = pickle.load(open(STATE_FILE)) done_solvers = set() for solver_binary_id in testing_solvers: solver_binary = db.session.query(db.SolverBinary).get(solver_binary_id) if not solver_binary: continue all_done = True for solver_config in solver_binary.solver_configurations: print solver_config.name, db.session.query(db.ExperimentResult).filter_by(solver_configuration=solver_config)\ .filter(db.ExperimentResult.status.in_([-1, 0])).count()
for i in range( 1, len( rows ) ): cells = rows[ i ].cells() print "Sending Email to: %s at %s" % ( cells[ 2 ].value(), cells[ 1 ].value() ) netid = cells[ 2 ].value() studentEmail = cells[ 1 ].value() msg = MIMEMultipart() msg[ 'Subject' ] = SUBJECT % netid msg[ 'From' ] = fro msg[ 'To' ] = studentEmail if netid not in submissions: print netid, studentEmail, "did not submit this homework" text = UNSUBMITTED_MAIL else: text = SUBMITTED_MAIL gradesheetName = "%s/FALL2015_HW<X>_Grading-%s.pdf" % ( netid, netid ) print "Sending file:", gradesheetName pdfFile = open( gradesheetName, 'rb' ).read() msgPdf = MIMEApplication( pdfFile, 'pdf' ) msgPdf.add_header( 'Content-Disposition', 'attachment', filename=gradesheetName ) msgPdf.add_header( 'Content-Disposition', 'inline', filename=gradesheetName ) msg.attach( msgPdf ) body = MIMEMultipart( 'alternative' ) part1 = MIMEText( text, 'plain' ) body.attach( part1 ) msg.attach( body ) mailer.sendmail(fro, studentEmail, msg.as_string()) mailer.close()
select=raw_input("Do you need to send an attachment? yes or no\n") if(select=='yes'): filename=raw_input("enter the file name to be attached make sure this file is present in same directory as this script\n") 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) print("please wait the message is being sent......") msg.attach(MIMEText(body, 'plain')) try: server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(fromaddr, password) text = msg.as_string() if(multiple=='no'): msg['To'] = toaddr server.sendmail(fromaddr, toaddr, text) else: for toaddr in flattened:
do = False for email, profile_id, fio in dbconn.query( Userprofile.email, Userprofile.id, Userprofile.fio).filter( sqlalchemy.or_(Userprofile.system_id == 2, Userprofile.id.in_((54, 29, 30, 31)))): threads = [ str(r[0]) for r in dbconn.query(Threads.id_global).filter( Threads.performer_id == profile_id).filter( Threads.id_local != 1).filter(Threads.status == Status.text). filter(Status.id == 1).filter(Threads.title_id == Tasktype.id).filter( Tasktype.system_id == 0 # ).filter(sqlalchemy.or_(Threads.creation_date < now.strftime('%Y-%m-%d'), sqlalchemy.and_(Threads.creation_date == now.strftime('%Y-%m-%d'), Threads.creation_time < delta.strftime('%H:%M:%S'))) ) ] if threads: do = True mess += """ <tr><td>%s</td><td>%s</td></tr> """ % (fio.encode('utf-8'), ','.join(threads)) mess += """ </table> """ if do: msg.attach(MIMEText(mess, 'html', _charset='utf-8')) smtp = smtplib.SMTP() smtp.connect() smtp.sendmail('*****@*****.**', em, msg.as_string()) smtp.sendmail('*****@*****.**', '*****@*****.**', msg.as_string()) smtp.close()
from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email import Encoders msg = MIMEMultipart() user_name = raw_input("Enter your user_name: ") passwd = raw_input("Enter your password: "******"Enter the From email id: ") to_email = raw_input("Enter the sending/TO email id: ") msg['From'] = form_email msg['To'] = to_email msg['Subject'] = 'this is automated email' msg.attach(MIMEText("this is the body of email")) part = MIMEBase('application', "octet-stream") fo = open('video.mp4', "rb") part.set_payload(fo.read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="attachment_videos.mp4"') msg.attach(part) server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(user_name, passwd) server.sendmail(from_email, to_email, msg.as_string()) server.close()
def send(sender, recipient, subject, body, contenttype, extraheaders=None, smtpserver=None): """Send an email. All arguments should be Unicode strings (plain ASCII works as well). Only the real name part of sender and recipient addresses may contain non-ASCII characters. The email will be properly MIME encoded and delivered though SMTP to localhost port 25. This is easy to change if you want something different. The charset of the email will be the first one out of the list that can represent all the characters occurring in the email. """ # Header class is smart enough to try US-ASCII, then the charset we # provide, then fall back to UTF-8. header_charset = 'ISO-8859-1' # We must choose the body charset manually for body_charset in CHARSET_LIST: try: body.encode(body_charset) except (UnicodeError, LookupError): pass else: break # Split real name (which is optional) and email address parts sender_name, sender_addr = parseaddr(sender) recipient_name, recipient_addr = parseaddr(recipient) # We must always pass Unicode strings to Header, otherwise it will # use RFC 2047 encoding even on plain ASCII strings. sender_name = str(Header(unicode(sender_name), header_charset)) recipient_name = str(Header(unicode(recipient_name), header_charset)) # Make sure email addresses do not contain non-ASCII characters sender_addr = sender_addr.encode('ascii') recipient_addr = recipient_addr.encode('ascii') # Create the message ('plain' stands for Content-Type: text/plain) msg = MIMEText(body.encode(body_charset), contenttype, body_charset) msg['To'] = formataddr((recipient_name, recipient_addr)) msg['Subject'] = Header(unicode(subject), header_charset) for hdr in extraheaders.keys(): try: msg[hdr] = Header(unicode(extraheaders[hdr], header_charset)) except: msg[hdr] = Header(extraheaders[hdr]) fromhdr = formataddr((sender_name, sender_addr)) msg['From'] = fromhdr msg_as_string = msg.as_string() #DEPRECATED if QP_REQUIRED: #DEPRECATED ins, outs = SIO(msg_as_string), SIO() #DEPRECATED mimify.mimify(ins, outs) #DEPRECATED msg_as_string = outs.getvalue() if VERBOSE: print 'Sending:', unu(subject) if SMTP_SEND: if not smtpserver: import smtplib try: if SMTP_SSL: smtpserver = smtplib.SMTP_SSL() else: smtpserver = smtplib.SMTP() smtpserver.connect(SMTP_SERVER) except KeyboardInterrupt: raise except Exception, e: print >> warn, "" print >> warn, ( 'Fatal error: could not connect to mail server "%s"' % SMTP_SERVER) print >> warn, ( 'Check your config.py file to confirm that SMTP_SERVER and other mail server settings are configured properly' ) if hasattr(e, 'reason'): print >> warn, "Reason:", e.reason sys.exit(1) if AUTHREQUIRED: try: smtpserver.ehlo() if not SMTP_SSL: smtpserver.starttls() smtpserver.ehlo() smtpserver.login(SMTP_USER, SMTP_PASS) except KeyboardInterrupt: raise except Exception, e: print >> warn, "" print >> warn, ( 'Fatal error: could not authenticate with mail server "%s" as user "%s"' % (SMTP_SERVER, SMTP_USER)) print >> warn, ( 'Check your config.py file to confirm that SMTP_SERVER and other mail server settings are configured properly' ) if hasattr(e, 'reason'): print >> warn, "Reason:", e.reason sys.exit(1)
body += "<h2>Historic Risk Index by Team</h2><img src=\"cid:image1\"><br>\n" # finish up the email message body += "</body>\n</html>" # set up multipart email message msgRoot = MIMEMultipart("related") msgRoot["Subject"] = "Weekly Client Security Bug secbugs_Stats Report" msgRoot["From"] = EMAIL_FROM msgRoot["To"] = ",".join(EMAIL_TO) msgRoot.preamble = "This is a multi-part message in MIME format." # Plaintext body msgAlternative = MIMEMultipart("alternative") msgRoot.attach(msgAlternative) msgText = MIMEText("Plain text alternative not supported.") msgAlternative.attach(msgText) # HTML body msgText = MIMEText(body, "html") msgAlternative.attach(msgText) # image attachment files = os.popen("find %s -name '*.png'" % JSONLOCATION) img = files.readline().strip() if img: fp = open(img, "rb") msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header("Content-ID", "<image1>") msgRoot.attach(msgImage)
while r != 4 : r = r+1 time.sleep(1) if grovepi.digitalRead(button)==1 : recommencer() r=4 time.sleep(.1) setRGB(0,250,0) setText("Vous avez\ntermine !") time.sleep(0.1) msg = MIMEMultipart() msg['From'] = '*****@*****.**' msg['To'] = '*****@*****.**' msg['Subject'] = 'Felicitation pour votre session' message = "Ci-joint, vos resultats de votre session d'aujourd'hui ainsi que les precedentes \n \nBonne continuation." msg.attach(MIMEText(message)) filename = "valeur.txt" attachment = open("/home/pi/Desktop/ProjetFaso/CodePrincipal/valeur.txt", "rb") part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read() part.add_header("Content-Disposition", "attachment; filename= %s" % filename) msg.attach(part) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login("*****@*****.**", "pushupcoachIG3") text = msg.as_string() server.sendmail("*****@*****.**", '*****@*****.**', msg.as_string()) server.quit() time.sleep(2) textCommand(0x01) time.sleep(.1)
def sendAggregateMail(self, cachedResults): # cachedResults is a list of dicts: {'name':name, 'build':build, 'results':results} projectName = self.status.getProjectName() # build will be the same for all messages, so just use the first one build = cachedResults[0]['build'] sourcestamp = build.getSourceStamp() source = sourcestamp.revision # Delimiting wht "," causes email subject line to contain a TAB character for some reason blamelist = "|".join(build.getResponsibleUsers()) p = re.compile( " <[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?>" ) blamelist = p.sub("", blamelist) slaves = [] results = [] for result in cachedResults: slaves.append(result['name']) results.append(result['results']) # If _any_ build failed, then we do not send this email (failure emails are dealt with separately) if FAILURE in results: return text = '' text += 'Congratulations, your %s build has passed all acceptance tests!\n' % self.branch text += '\n' text += self.getChangesText(sourcestamp.changes) m = Message() m.set_payload(text) m['Date'] = formatdate(localtime=True) m['Subject'] = self.subject % { 'result': 'pass', 'blamelist': blamelist, 'branch': self.branch, 'src': source, } m['From'] = self.fromaddr # m['To'] is added later if self.addLogs: for result in cachedResults: build = result['build'] for log in build.getLogs(): name = "%s.%s" % (log.getStep().getName(), log.getName()) a = MIMEText(log.getText()) a.add_header('Content-Disposition', "attachment", filename=name) m.attach(a) # now, who is this message going to? dl = [] recipients = self.extraRecipients[:] if self.sendToInterestedUsers and self.lookup: for u in build.getInterestedUsers(): d = defer.maybeDeferred(self.lookup.getAddress, u) d.addCallback(recipients.append) dl.append(d) d = defer.DeferredList(dl) d.addCallback(self._gotRecipients, recipients, m) return d
def dropEmail(self, fromAddress, addresses, subject, body): """ drop emails to the DropmailHost pool. """ if not addresses: return portal_url = getToolByName(self, 'portal_url') portal = portal_url.getPortalObject() charset = portal.getProperty('email_charset', None) if charset is None or charset == '': charset = plone_utils.getSiteEncoding() # using MIMEMultipart for the message. email = MIMEMultipart('mixed') email.epilogue = '' # from, to, subject email['From'] = fromAddress if isinstance(subject, unicode): subject = subject.encode(charset, 'replace') email['Subject'] = subject email['To'] = '' # adding this to make both plain text and html available, using the same boundary textMessage = MIMEMultipart('alternative') # preparing the email message if isinstance(body, unicode): body = body.encode(charset, 'replace') textPart = MIMEText(body, 'plain', charset) textMessage.attach(textPart) # the html format. htmlPart = MIMEText(body, 'html', charset) textMessage.attach(htmlPart) email.attach(textMessage) ## the attachment. fileField = self.getField('xpcm_emessage_attachment') filename = fileField.getFilename(self) if (filename != None) & (filename != ''): self.log.debug("trying to attach the attachment: %s ..." % filename) attachment = MIMEBase('application', 'octet-stream', name=filename) attachment.set_payload(fileField.get(self, raw=True).data) Encoders.encode_base64(attachment) # set up the header. attachment.add_header('Content-Disposition', 'attachment; filename="%s"' % filename) email.attach(attachment) for address in addresses: if isinstance(address, unicode): address = address.encode(charset, 'replace') try: email._headers.pop() email['To'] = address msg = Email(fromAddress, address, email.as_string()) msg.send() except: self.log.error('Sending email error for %s!' % (address)) raise self.setSendingLog(len(addresses))
print 'Config file has wrong format' exit() fromaddr = params['sender'] toaddr = params['recipient'] msgRoot = MIMEMultipart('related') msgRoot['Subject'] = params['subject'] msgRoot['From'] = fromaddr msgRoot['To'] = toaddr msgRoot.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText('This is the alternative plain text message.') msgAlternative.attach(msgText) msgText = "" if options.photo != None and 'message_photo' in params: msgText = MIMEText(params['message_photo'], 'html') else: msgText = MIMEText(params['message'], 'html') msgAlternative.attach(msgText) if options.photo != None: fp = open(options.photo, 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image1>')
def send_email(toaddr, subject, body, cc = [], bcc = []): global email_from, smtp_server, smtp_port, \ email_username, email_pass # TODO: something check if not smtp_server: return False fromaddr = email_from # Header class is smart enough to try US-ASCII, then the charset we # provide, then fall back to UTF-8. header_charset = 'ISO-8859-1' # We must choose the body charset manually for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8': try: body.encode(body_charset) except UnicodeError: pass else: break from_name, from_addr = parseaddr(fromaddr) to_name, to_addr = parseaddr(toaddr) from_name = str(Header(unicode(from_name), header_charset)) to_name = str(Header(unicode(to_name), header_charset)) from_addr = from_addr.encode('ascii') to_addr = to_addr.encode('ascii') msg = MIMEText(body.encode(body_charset), 'plain', body_charset) msg['From'] = formataddr((from_name, from_addr)) msg['To'] = formataddr((to_name, to_addr)) if cc: L = [] for x in cc: x_name, x_addr = parseaddr(x) L.append( formataddr((x_name, x_addr)) ) msg['CC'] = ', '.join(L) if bcc: L = [] for x in bcc: x_name, x_addr = parseaddr(x) L.append( formataddr((x_name, x_addr)) ) msg['BCC'] = ', '.join(L) msg['Subject'] = Header(unicode(subject), header_charset) msg['date']=time.strftime('%a, %d %b %Y %H:%M:%S %z') toaddrs = [toaddr] + cc + bcc smtp = SMTP(smtp_server, smtp_port) #smtp.ehlo() if smtp_server.endswith('gmail.com'): smtp.starttls() #smtp.ehlo() if not ( smtp_server.endswith('127.0.0.1') or smtp_server.endswith('localhost') ): smtp.login(email_username, email_pass) smtp.sendmail(fromaddr, toaddrs, msg.as_string()) smtp.quit() return True
from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText from email.MIMEImage import MIMEImage TO = USEREMAIL #TO = '*****@*****.**' msgRoot = MIMEMultipart('related') msgRoot['Subject'] = SUBJECTMESSAGE msgRoot['From'] = FROM msgRoot['To'] = TO msgRoot.preamble = 'This is a multi-part message in MIME format.' msgAlternative = MIMEMultipart('alternative') msgRoot.attach(msgAlternative) msgText = MIMEText(TEXT) msgAlternative.attach(msgText) msgText = MIMEText(HTML, 'html') msgAlternative.attach(msgText) # Logo for Icinga2 <= 2.5.x #fp = open('/usr/share/icingaweb2/public/img/logo_icinga-inv.png', 'rb') # Logo for Icinga2 >= 2.6.x fp = open('/usr/share/icingaweb2/public/img/icinga-logo.png', 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<icinga2_logo>') msgRoot.attach(msgImage)
def sendAggregateMail(self, cachedResults): # cachedResults is a list of dicts: {'name':name, 'build':build, 'results':results} projectName = self.status.getProjectName() # build will be the same for all messages, so just use the first one build = cachedResults[0]['build'] sourcestamp = build.getSourceStamp() source = sourcestamp.revision # Delimiting wht "," causes email subject line to contain a TAB character for some reason blamelist = "|".join(build.getResponsibleUsers()) p = re.compile( " <[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?>" ) blamelist = p.sub("", blamelist) slaves = [] results = [] for result in cachedResults: slaves.append(result['name']) results.append(result['results']) text = '' text += 'Slave(s): %s\n' % ', '.join(slaves) text += 'Branch: %s\n' % self.branch text += self.getChangesText(sourcestamp.changes) if FAILURE in results: text += "Log(s) of failed build steps:\n" for result in cachedResults: if result['results'] == FAILURE: build = result['build'] text += " Slave: %s\n" % result['name'] for step in build.getSteps(): if step.getResults()[0] == FAILURE: text += " %s\n" % ''.join( step.getResults()[1]) buildurl = "%sbuilders/%s/builds/%d" % ( self.status.getBuildbotURL(), result['name'], build.getNumber()) text += " %s/steps/%s/logs/stdio\n" % ( buildurl, ''.join(step.getResults()[1])) text += "\n" failSteps, buildinfo = self.getBuildsStatusFileinfo( build, blamelist, source) # add previous failures to email if failSteps: text += ' Buildsteps that were failing before this build:\n' for step in failSteps: text += ' %s Revision: %s Blamelist: %s\n' % ( step, buildinfo[step]['revision'], buildinfo[step]['blamelist']) text += "\n" m = Message() m.set_payload(text) m['Date'] = formatdate(localtime=True) m['Subject'] = self.subject % { 'result': 'fail', 'blamelist': blamelist, 'branch': self.branch, 'src': source, } m['From'] = self.fromaddr # m['To'] is added later if self.addLogs: for result in cachedResults: build = result['build'] for log in build.getLogs(): name = "%s.%s" % (log.getStep().getName(), log.getName()) a = MIMEText(log.getText()) a.add_header('Content-Disposition', "attachment", filename=name) m.attach(a) # now, who is this message going to? dl = [] recipients = self.extraRecipients[:] if self.sendToInterestedUsers and self.lookup: for u in build.getInterestedUsers(): d = defer.maybeDeferred(self.lookup.getAddress, u) d.addCallback(recipients.append) dl.append(d) d = defer.DeferredList(dl) d.addCallback(self._gotRecipients, recipients, m) return d
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=filename) fd.close() return retval message = """Hello, This is a test message from Chapter 9. I hope you enjoy it! -- Anonymous""" msg = MIMEMultipart() msg['To'] = '*****@*****.**' msg['From'] = 'Test Sender <*****@*****.**>' msg['Subject'] = 'Test Message, Chapter 9' msg['Date'] = Utils.formatdate(localtime=1) msg['Message-ID'] = Utils.make_msgid() body = MIMEText(message, _subtype='plain') msg.attach(body) for filename in sys.argv[1:]: msg.attach(attachment(filename)) print msg.as_string()
def intdomail(mailto, mailsub, mailbody, attach_files=[], sig=True, undisclosed=False, fromaddr = from_address, html=False): mailto = mailto.split() # print mailto badlist = ['cfa','harvard','at','cfa-wide','oir',' ','cfhelp','all',\ 'dot','@','dt','ssp','postdocs','faculty','grad'] mlist = [] for addr in mailto: #print addr[-3:] #print ((addr.lower() not in badlist), (addr.find("@") != -1), \ # (addr.find(".") != -1),(addr[-3:] == "edu")) if (addr.lower() not in badlist) and (addr.find("@") != -1) and \ (addr.find(".") != -1): mlist.append(addr) mailto = mlist if len(mailto) == 0: print "no valid email" return mailhost = defhost tolist = ", ".join(mailto) if undisclosed == True: tolist = "*****@*****.**" msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = tolist msg['Subject'] = mailsub if sig: mailbody += '\n\n----\nThis message was sent automatically. If you feel you received this message in error, please contact Adam Morgan at [email protected]' # attach the text; as either plain or html if html == False: msg.attach( MIMEText(mailbody,'plain') ) else: msg.attach( MIMEText(mailbody,'html') ) for attachpath in attach_files: # Re-write if you want to attach the files with a different file name # Right now, just take the actual name of the file. attachfilename = attachpath.split('/')[-1] attach = getAttachment(attachpath, attachfilename) msg.attach(attach) server = smtplib.SMTP(mailhost,587) ttt = server.ehlo() # print ttt if 1: a = server.starttls() # print a else: print 'could not start a secure SSL session for mail' b = server.ehlo() # print b try: c = server.login(gmail_username,gmail_password) # print c # print (fromaddr, mailto, msg) d = server.sendmail(fromaddr, mailto, msg.as_string()) # print d except: print "send mail failed" print traceback.format_exc() try: del server except: pass return
import smtplib from email.MIMEText import MIMEText emisor = "*****@*****.**" #Email para enviar receptor = "*****@*****.**" #Email para recibir # Configuracion del mail mensaje = MIMEText("Este correo ha sido enviado desde Python") mensaje['From'] = emisor mensaje['To'] = receptor mensaje['Subject'] = "Mi primer correo desde Python" # Nos conectamos al servidor SMTP de Gmail serverSMTP = smtplib.SMTP('smtp.gmail.com', 587) serverSMTP.ehlo() serverSMTP.starttls() serverSMTP.ehlo() serverSMTP.login(emisor, "Migueleldepredador5000") # Enviamos el mensaje serverSMTP.sendmail(emisor, receptor, mensaje.as_string()) # Cerramos la conexion serverSMTP.close()
def buildMessage(self, builder_name, build_status, results, step_name): """Send an email about the tree closing. Don't attach the patch as MailNotifier.buildMessage does. @type builder_name: string @type build_status: L{buildbot.status.builder.BuildStatus} @type step_name: name of this step """ # TODO(maruel): Update function signature to match # mail.MailNotifier.buildMessage(). if (self._last_time_mail_sent and self._last_time_mail_sent > time.time() - self.minimum_delay_between_alert): # Rate limit tree alerts. log.msg('Supressing repeat email') return log.msg('About to email') self._last_time_mail_sent = time.time() # TODO(maruel): Use self.createEmail(). blame_interested_users = self.shouldBlameCommitters(step_name) project_name = self.master_status.getTitle() revisions_list = build_utils.getAllRevisions(build_status) build_url = self.master_status.getURLForThing(build_status) waterfall_url = self.master_status.getBuildbotURL() status_text = self.status_header % { 'buildbotURL': waterfall_url, 'builder': builder_name, 'builderName': builder_name, 'buildProperties': build_status.getProperties(), 'buildURL': build_url, 'project': project_name, 'reason': build_status.getReason(), 'slavename': build_status.getSlavename(), 'steps': step_name, } # Use the first line as a title. status_title = status_text.split('\n', 1)[0] blame_list = ','.join(build_status.getResponsibleUsers()) revisions_string = '' latest_revision = 0 if revisions_list: revisions_string = ', '.join([str(rev) for rev in revisions_list]) latest_revision = max([rev for rev in revisions_list]) if results[0] == FAILURE: result = 'failure' else: result = 'warning' # Generate a HTML table looking like the waterfall. # WARNING: Gmail ignores embedded CSS style. I don't know how to fix that so # meanwhile, I just won't embedded the CSS style. html_content = ( """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>%s</title> </head> <body> <a href="%s">%s</a><p> %s<p> <a href="%s">%s</a><p> Revision: %s<br> """ % (status_title, waterfall_url, waterfall_url, status_text.replace('\n', "<br>\n"), build_url, build_url, revisions_string)) # Only include the blame list if relevant. if blame_interested_users: html_content += " Blame list: %s<p>\n" % blame_list html_content += build_utils.EmailableBuildTable(build_status, waterfall_url) html_content += "<p>" # Add the change list descriptions. getChanges() returns a tuple of # buildbot.changes.changes.Change for change in build_status.getChanges(): html_content += change.asHTML() html_content += "</body>\n</html>" # Simpler text content for non-html aware clients. text_content = ( """%s %s %swaterfall?builder=%s --=> %s <=-- Revision: %s Blame list: %s Buildbot waterfall: http://build.chromium.org/ """ % (status_title, build_url, urllib.quote(waterfall_url, '/:'), urllib.quote(builder_name), status_text, revisions_string, blame_list)) m = MIMEMultipart('alternative') # The HTML message, is best and preferred. m.attach(MIMEText(text_content, 'plain', 'iso-8859-1')) m.attach(MIMEText(html_content, 'html', 'iso-8859-1')) m['Date'] = formatdate(localtime=True) m['Subject'] = self.subject % { 'result': result, 'projectName': project_name, 'builder': builder_name, 'reason': build_status.getReason(), 'revision': str(latest_revision), 'buildnumber': str(build_status.getNumber()), 'date': str(datetime.date.today()), 'steps': step_name, } m['From'] = self.fromaddr if self.reply_to: m['Reply-To'] = self.reply_to recipients = list(self.extraRecipients[:]) if self.sheriffs: recipients.extend(BuildSheriffs.GetSheriffs(classes=self.sheriffs, data_dir=self.public_html)) dl = [] if self.sendToInterestedUsers and self.lookup and blame_interested_users: for u in build_status.getInterestedUsers(): d = defer.maybeDeferred(self.lookup.getAddress, u) d.addCallback(recipients.append) dl.append(d) defered_object = defer.DeferredList(dl) if not self.enable_mail: defered_object.addCallback(self._logMail, recipients, m) else: defered_object.addCallback(self._gotRecipients, recipients, m) defered_object.addCallback(self.getFinishedMessage, builder_name, build_status, step_name) return defered_object
def main(self): import cgi, cgitb, time, os, sys, shutil cgitb.enable() ## enable traceback, which reports non-syntax errors ## set jobid timetuple = time.gmtime(time.time()) timestr = str(timetuple[0]) + str(timetuple[1]).zfill(2) + str( timetuple[2]).zfill(2) + str(timetuple[3]).zfill(2) + str( timetuple[4]).zfill(2) + str(timetuple[5]).zfill(2) form = cgi.FieldStorage() if form.has_key("timestr"): timestr = form["timestr"].value ## set paths self.path_tmp = '/var/www/cgi-bin/goodvibes/tmp/' self.path_results = '/var/www/html/goodvibes/results/' self.path_pdbs = '/data/pdb/' self.path_python = '/var/www/cgi-bin/goodvibes/python/' ## initiate fasthtml print 'Content-type: text/html\n\n' print ''' <html> <head><title>UCD GoodVibes</title></head> <body> ''' ## check form for erros and terminate fasthtml if any errors self.errorcheckfile(form) ## if no errors then queue job if os.path.isfile(self.path_tmp + 'queue.txt'): fd = open(self.path_tmp + 'queue.txt', 'a') fd.write(timestr + '\n') fd.close() queuemanager = False else: fd = open(self.path_tmp + 'queue.txt', 'w') fd.write(timestr + '\n') fd.close() queuemanager = True ## if no errors and job queued, then write fast output and slow 1st temporary output sys.stdout.flush() sys.stderr.flush() pid = os.fork() if pid: htmlbody = 'Dear user. Your input data has been queued for processing. Your job is still in the queue.' self.slowhtml(htmlbody, timestr, self.path_results) htmlbody = 'Dear user. Your input data is being processed. Your results or an estimated time for the completion of your calculation will be available from <a href="http://polymerase.ucd.ie/goodvibes/results/' + timestr + '.html" target="_blank">http://polymerase.ucd.ie/goodvibes/results/' + timestr + '.html</a>' self.fasthtml(htmlbody) ## flush the output from fasthtml sys.stdout.flush() os._exit(0) sys.stdout.flush() # double flush used in pKD os.close(0) os.close(1) os.close(2) fd = open('junkout', 'w') sys.stderr = fd sys.stdout = fd ################################################################################ ## parse html form if form.has_key("cutoffs"): cutoffs = form.getlist("cutoffs") else: cutoffs = ['10'] if form.has_key("amplitude_average"): amplitude_average = form["amplitude"].value else: amplitude_average = 2 if form.has_key("mutations"): mutations = form["mutations"].value else: mutations = 0 if form.has_key("quarternary"): quarternary = form["quarternary"].value else: quarternary = 'monomeric' if form.has_key("frames"): frames = form['frames'].value else: frames = 50 calctype = form['calctype'].value if form["pdb1_id"].value != "": fd = open(self.path_pdbs + form["pdb1_id"].value.lower() + '.pdb', 'r') pdb_lines = fd.readlines() fd.close() fd = open(self.path_tmp + timestr + '_reference.pdb', 'w') fd.writelines(pdb_lines) fd.close() if form["pdb1_file"].value: fd = open(self.path_tmp + timestr + '_reference.pdb', 'w') fd.writelines(form["pdb1_file"].file.readlines()) fd.close() if form["pdb1_txt"].value: fd = open(self.path_tmp + timestr + '_reference.pdb', 'w') fd.writelines(form["pdb1_txt"].file.readlines()) fd.close() if form["chains1"].value: chains1 = form["chains1"].value.upper() else: chains1 = '' ## resranges need to refer to chains. resranges dont need to be updated when building biomolecules from remark350 because residues not parsed. ## self.residue_terminal_n = {'A':-9999, 'B':-9999, 'C':-9999, 'D':-9999, 'E':-9999, 'F':-9999, 'G':-9999, 'H':-9999, 'I':-9999, 'J':-9999, 'K':-9999, 'L':-9999, 'M':-9999, 'N':-9999, 'O':-9999, 'P':-9999, 'Q':-9999, 'R':-9999, 'S':-9999, 'T':-9999, 'U':-9999, 'V':-9999, 'W':-9999, 'X':-9999, 'Y':-9999, 'Z':-9999, ' ':-9999,} ## self.residue_terminal_c = {'A':9999, 'B':9999, 'C':9999, 'D':9999, 'E':9999, 'F':9999, 'G':9999, 'H':9999, 'I':9999, 'J':9999, 'K':9999, 'L':9999, 'M':9999, 'N':9999, 'O':9999, 'P':9999, 'Q':9999, 'R':9999, 'S':9999, 'T':9999, 'U':9999, 'V':9999, 'W':9999, 'X':9999, 'Y':9999, 'Z':9999, ' ':9999,} if form.has_key("resrange1start"): resrange1start = form["resrange1start"].value else: resrange1start = -99999 if form.has_key("resrange1end"): resrange1end = form["resrange1end"].value else: resrange1end = 99999 if form.has_key("model1"): model1 = form["model1"].value else: model1 = '' if not form.has_key("atoms"): atoms_hessian = ['CA'] else: l_atoms = form.getlist("atoms") import sets all = sets.Set(['OXT']) for chemical_symbol in ['C', 'O', 'H', 'N', 'S']: all.add(chemical_symbol) for remoteness_indicator in [ 'A', 'B', 'G', 'D', 'E', 'Z', 'H' ]: all.add(chemical_symbol + remoteness_indicator) for branch_designator in range(10): all.add(chemical_symbol + remoteness_indicator + str(branch_designator)) mainchain = sets.Set(['C', 'O', 'N', 'CA']) sidechain = all - mainchain alpha = sets.Set(['CA']) beta = sets.Set(['CB']) atoms_hessian = sets.Set() for s_atoms in l_atoms: if s_atoms == 'yall': atoms_hessian |= all break if s_atoms == 'ymainchain': atoms_hessian |= mainchain if s_atoms == 'ysidechain': atoms_hessian |= sidechain if s_atoms == 'yalpha': atoms_hessian |= alpha if s_atoms == 'ybeta': atoms_hessian |= beta for s_atoms in l_atoms: if s_atoms == 'nmainchain': atoms_hessian -= mainchain if s_atoms == 'nsidechain': atoms_hessian -= sidechain if s_atoms == 'nalpha': atoms_hessian -= alpha if s_atoms == 'nbeta': atoms_hessian -= beta atoms_hessian = list(atoms_hessian) if form.has_key("pdb2_id"): fd = open(self.path_pdbs + form["pdb2_id"].value.lower() + '.pdb', 'r') pdb_lines = fd.readlines() fd.close() fd = open(self.path_tmp + timestr + '_conformer.pdb', 'w') fd.writelines(pdb_lines) fd.close() if form.has_key("pdb2_file"): fd = open(self.path_tmp + timestr + '_conformer.pdb', 'w') fd.write(form["pdb2_file"].value) fd.close() if form.has_key("chains2"): chains2 = form["chains2"].value.upper() else: chains2 = '' if form.has_key("resrange2start"): resrange2start = form["resrange2start"].value else: resrange2start = -99999 if form.has_key("resrange2end"): resrange2end = form["resrange2end"].value else: resrange2end = 99999 if form.has_key("model2"): model2 = form["model2"].value else: model2 = '' ## write job input to job file lines_input = [] lines_input.append('%s;%s\n' % ('chains', chains1)) lines_input.append('%s;%s\n' % ('model', model1)) lines_input.append('%s;%s\n' % ('resrangestart', resrange1start)) lines_input.append('%s;%s\n' % ('resrangeend', resrange1end)) lines_input.append('%s;%s\n' % ('cutoffs', ','.join(cutoffs))) lines_input.append('%s;%s\n' % ('amplitude', amplitude_average)) lines_input.append('%s;%s\n' % ('atoms_hessian', ','.join(atoms_hessian))) lines_input.append('%s;%s\n' % ('mutations', mutations)) lines_input.append('%s;%s\n' % ('quarternary', quarternary)) lines_input.append('%s;%s\n' % ('frames', frames)) lines_input.append('%s;%s\n' % ('calctype', calctype)) fd = open(self.path_tmp + 'job_' + timestr + '.txt', 'w') fd.writelines(lines_input) fd.close() ## fd = open(self.path_tmp+'job_'+timestr+'.txt', 'w') ## fd.write( ## str(chains1)+'\n'+str(model1)+'\n'+str(resrange1start)+'\n'+str(resrange1end)+'\n'+ ## str(cutoffs)+'\n'+str(amplitude_average)+'\n'+str(atoms_hessian)+'\n'+str(mutations)+'\n'+str(quarternary)+'\n'+ ## str(frames)+'\n'+str(inputfiles)+'\n'+str(calctype)+'\n'+ ## str(chains2)+'\n'+str(model2)+'\n'+str(resrange2start)+'\n'+str(resrange2end)+'\n' ## ) ## fd.close() ## send mail via SMTP server to user about job being queued import smtplib from email.MIMEText import MIMEText mailfrom = 'GoodVibes' mailto = form['mail'].value msg = MIMEText( 'Dear user. Your input data is being processed. Your results or an estimated time for the completion of your calculation will be available from http://polymerase.ucd.ie/goodvibes/results/' + timestr + '.html <http://polymerase.ucd.ie/goodvibes/results/' + timestr + '.html>.') msg['Subject'] = 'Your GoodVibes job with the ID %s has been queued for processing' % timestr msg['From'] = mailfrom msg['Reply-To'] = '*****@*****.**' msg['To'] = mailto server = smtplib.SMTP('mail.ucd.ie') server.set_debuglevel(1) server.sendmail(mailfrom, mailto, msg.as_string()) server.close() ## delete timestr to avoid use of this variable beyond this point (not really necessary) del timestr ################################################################################ ## end if not queue manager if not queuemanager: return ################################################################################ ## process queue if queue manager ## change dir in case of any goodvibes outputs (dislin etc.) os.chdir(self.path_results) ## append the python library to sys.paths after change of dir sys.path.append(self.path_python) import goodvibes_dev instance_NMA = goodvibes_dev.vibration() ## process queue while it exists while os.path.isfile(self.path_tmp + 'queue.txt'): ## parse job id fd = open(self.path_tmp + 'queue.txt', 'r') job = fd.readline().strip() fd.close() ## write slow 2nd temporary output htmlbody = 'Dear user. Your input is being processed. Return to this page in a few seconds to get an estimate of the end time of the calculations.' self.slowhtml(htmlbody, job, self.path_results) ## parse parameters from job txt file to goodvibes fd = open(self.path_tmp + 'job_' + job + '.txt', 'r') lines_job = fd.readlines() fd.close() input_job = {} for line in lines_job: input_job[line.split(';')[0]] = line.split(';')[1][:-1] if input_job['chains'] != '': chains1 = input_job['chains'].split(',') else: chains1 = [] model1 = input_job['model'].strip() resrange1start = int(input_job['resrangestart'].strip()) resrange1end = int(input_job['resrangeend'].strip()) cutoffs = input_job['cutoffs'].split(',') for i in range(len(cutoffs)): cutoffs[i] = float(cutoffs[i]) amplitude_average = float(input_job['amplitude'].strip()) atoms_hessian = input_job['atoms_hessian'].split(',') quarternary = input_job['quarternary'].strip() frames = float(input_job['frames']) calctype = int(input_job['calctype'].strip()) fd = open(self.path_tmp + job + '_reference.pdb', 'r') pdblines1 = fd.readlines() fd.close() ## run goodvibes try: results = instance_NMA.main(pdblines1, chains1, model1, atoms_hessian, quarternary, job, frames, cutoffs, calctype, [1], path_html=self.path_results, path_python=self.path_python) ## except 'chainerror', error: ## ## if expected error then remove from queue and report to user ## self.slowhtml(error, job, self.path_results) ## self.queue() ## continue except IOError, (errno, strerror): self.slowhtml( str(errno) + str(strerror), job, self.path_results) self.queue() results = instance_NMA.main(pdblines1, chains1, model1, atoms_hessian, quarternary, job, frames, cutoffs, calctype, [1], path_html=self.path_results, path_python=self.path_python) continue except:
class Message(object): """Create new e-mail messages. Example:: msg = mail.Message( from_addr="root@localhost", to_addrs=["user1", "user2", "user3"], subject="Test, 123", message="Hello thar!", mime="text/html") """ def __init__(self, from_addr, to_addrs, subject, message, mime="text/plain", charset="utf-8"): self.subject = subject self.from_addr = from_addr if isinstance(to_addrs, types.StringType): self.to_addrs = [to_addrs] else: self.to_addrs = to_addrs self.msg = None self.__cache = None self.message = MIMEText(message, _charset=charset) self.message.set_type(mime) def attach(self, filename, mime=None, charset=None, content=None): """Attach files to this message. Example:: msg.attach("me.png", mime="image/png") It also supports fake attachments:: msg.attach("fake.txt", mime="text/plain", content="gotcha") """ base = os.path.basename(filename) if content is None: fd = open(filename) content = fd.read() fd.close() elif not isinstance(content, types.StringType): raise TypeError("Don't know how to attach content: %s" % repr(content)) part = MIMEBase("application", "octet-stream") part.set_payload(content) Encoders.encode_base64(part) part.add_header("Content-Disposition", "attachment", filename=base) if mime is not None: part.set_type(mime) if charset is not None: part.set_charset(charset) if self.msg is None: self.msg = MIMEMultipart() self.msg.attach(self.message) self.msg.attach(part) def __str__(self): return self.__cache or "cyclone email message: not rendered yet" def render(self): if self.msg is None: self.msg = self.message self.msg["Subject"] = self.subject self.msg["From"] = self.from_addr self.msg["To"] = COMMASPACE.join(self.to_addrs) self.msg["Date"] = formatdate(localtime=True) if self.__cache is None: self.__cache = self.msg.as_string() return StringIO(self.__cache) def add_header(self, key, value, **params): """Adds custom headers to this message. Example:: msg.add_header("X-MailTag", "foobar") """ if self.msg is None: self.msg = self.message self.msg.add_header(key, value, **params)
def build_email(self, email_from, email_to, subject, body, email_cc=None, email_bcc=None, reply_to=False, attachments=None, message_id=None, references=None, object_id=False, subtype='plain', headers=None, body_alternative=None, subtype_alternative='plain'): """Constructs an RFC2822 email.message.Message object based on the keyword arguments passed, and returns it. :param string email_from: sender email address :param list email_to: list of recipient addresses (to be joined with commas) :param string subject: email subject (no pre-encoding/quoting necessary) :param string body: email body, of the type ``subtype`` (by default, plaintext). If html subtype is used, the message will be automatically converted to plaintext and wrapped in multipart/alternative, unless an explicit ``body_alternative`` version is passed. :param string body_alternative: optional alternative body, of the type specified in ``subtype_alternative`` :param string reply_to: optional value of Reply-To header :param string object_id: optional tracking identifier, to be included in the message-id for recognizing replies. Suggested format for object-id is "res_id-model", e.g. "12345-crm.lead". :param string subtype: optional mime subtype for the text body (usually 'plain' or 'html'), must match the format of the ``body`` parameter. Default is 'plain', making the content part of the mail "text/plain". :param string subtype_alternative: optional mime subtype of ``body_alternative`` (usually 'plain' or 'html'). Default is 'plain'. :param list attachments: list of (filename, filecontents) pairs, where filecontents is a string containing the bytes of the attachment :param list email_cc: optional list of string values for CC header (to be joined with commas) :param list email_bcc: optional list of string values for BCC header (to be joined with commas) :param dict headers: optional map of headers to set on the outgoing mail (may override the other headers, including Subject, Reply-To, Message-Id, etc.) :rtype: email.message.Message (usually MIMEMultipart) :return: the new RFC2822 email message """ email_from = email_from or tools.config.get('email_from') assert email_from, "You must either provide a sender address explicitly or configure "\ "a global sender address in the server configuration or with the "\ "--email-from startup parameter." # Note: we must force all strings to to 8-bit utf-8 when crafting message, # or use encode_header() for headers, which does it automatically. headers = headers or {} # need valid dict later if not email_cc: email_cc = [] if not email_bcc: email_bcc = [] if not body: body = u'' email_body_utf8 = ustr(body).encode('utf-8') email_text_part = MIMEText(email_body_utf8, _subtype=subtype, _charset='utf-8') msg = MIMEMultipart() if not message_id: if object_id: message_id = tools.generate_tracking_message_id(object_id) else: message_id = make_msgid() msg['Message-Id'] = encode_header(message_id) if references: msg['references'] = encode_header(references) msg['Subject'] = encode_header(subject) msg['From'] = encode_rfc2822_address_header(email_from) del msg['Reply-To'] if reply_to: msg['Reply-To'] = encode_rfc2822_address_header(reply_to) else: msg['Reply-To'] = msg['From'] msg['To'] = encode_rfc2822_address_header(COMMASPACE.join(email_to)) if email_cc: msg['Cc'] = encode_rfc2822_address_header( COMMASPACE.join(email_cc)) if email_bcc: msg['Bcc'] = encode_rfc2822_address_header( COMMASPACE.join(email_bcc)) msg['Date'] = formatdate() # Custom headers may override normal headers or provide additional ones for key, value in headers.iteritems(): msg[ustr(key).encode('utf-8')] = encode_header(value) if subtype == 'html' and not body_alternative and html2text: # Always provide alternative text body ourselves if possible. text_utf8 = tools.html2text( email_body_utf8.decode('utf-8')).encode('utf-8') alternative_part = MIMEMultipart(_subtype="alternative") alternative_part.attach( MIMEText(text_utf8, _charset='utf-8', _subtype='plain')) alternative_part.attach(email_text_part) msg.attach(alternative_part) elif body_alternative: # Include both alternatives, as specified, within a multipart/alternative part alternative_part = MIMEMultipart(_subtype="alternative") body_alternative_utf8 = ustr(body_alternative).encode('utf-8') alternative_body_part = MIMEText(body_alternative_utf8, _subtype=subtype_alternative, _charset='utf-8') alternative_part.attach(alternative_body_part) alternative_part.attach(email_text_part) msg.attach(alternative_part) else: msg.attach(email_text_part) if attachments: for (fname, fcontent) in attachments: filename_rfc2047 = encode_header_param(fname) part = MIMEBase('application', "octet-stream") # The default RFC2231 encoding of Message.add_header() works in Thunderbird but not GMail # so we fix it by using RFC2047 encoding for the filename instead. part.set_param('name', filename_rfc2047) part.add_header('Content-Disposition', 'attachment', filename=filename_rfc2047) part.set_payload(fcontent) Encoders.encode_base64(part) msg.attach(part) return msg
def login(): """Render the website's login user page.""" secret= app.config['TOKEN_SECRET'] email= request.json['email'] password= request.json['password'] payload={"email": email,"password": password} encoded_token=jwt.encode({'logon_info': payload}, secret, algorithm='HS256' user = Person.query.filter_by(email_address=email, password=password).first() if user is not None: login_user(user) # Sends back the information along with the token generated response = jsonify(information={"error":"null","data":{'user':{'id':user.id,'email': user.email_address,'fname':user.first_name, 'lname': user.last_name, 'Authorization_token':encoded_token},"message":"Success"}}) else: response = jsonify({"error":"1","data":{},"message":'failed'}) response.status_code = 401 return response @app.route('/api/users/<userid>/wishlist', methods=["GET","POST"]) @login_required def apiadd(userid): if request.method == "POST": new_wish= Wish(wish_url=request.json['url'], user_id=userid , wish_descript=request.json['description'], wish_title=request.json['title'], thumbnail=request.json['image'], added=str(datetime.now())); db.session.add(new_wish) db.session.commit() response = jsonify({"error":"null","data":{},"message":"Success"}) return response else: user = Person.query.filter_by(id=userid).first() userwishes = Wish.query.filter_by(user_id=userid) wishlist = [] for wish in userwishes: wishlist.append({'id':wish.wish_id,'title': wish.wish_title,'description':wish.wish_descript,'url':wish.wish_url,'thumbnail':wish.thumbnail, 'added': wish.added}) if(len(wishlist)>0): response = jsonify({"error":"null","data":{"wishes":wishlist}}) else: response = jsonify({"error":"1","data":{}}) return response @app.route('/api/thumbnails', methods=['POST']) def thumbnail(): url = request.json['url'] imagelist = get_images(url) for each in imagelist: if not each.lower().endswith(('.png', '.jpg', '.jpeg')): imagelist.remove(each) imagelist= list(set(imagelist)); output = jsonify(thumbnails= imagelist) return output def get_images(url): result = requests.get(url) soup = BeautifulSoup(result.text, "html.parser") imgs=[] image = "%s" for img in soup.findAll("img", src=True): link = image % urlparse.urljoin(url, img["src"]) imgs+=[link] return imgs @app.route('/api/users/<userid>/wishlist/<itemid>', methods=['POST']) def deletewish(userid,itemid): item_id= request.json['itemid'] #because based on the db the wish id and the person/userid are always the same deleted_wish= Wish.query.filter_by(user_id=userid,wish_id= itemid).first() # use session.delete here instead of add db.session.delete(deleted_wish) db.session.commit() response = jsonify({"error":"null","data":{},"message":"Success"}) return response @app.route('/about/') def about(): """Render the website's about page.""" return render_template('about.html') # user_loader callback. This callback is used to reload the user object from # the user ID stored in the session @login_manager.user_loader def load_user(id): return Person.query.get(int(id)) # ### # # The functions below should be applicable to all Flask apps. # ### @app.route('/share/', methods = ['POST']) def send_email(): firstname = request.json['firstname'] lastname = request.json['lastname'] user= Person.query.filter_by(id=request.json['userid']).first() name = user.first_name userid= user.id from_addr = '*****@*****.**' to_addr = request.json['email'] msg = MIMEMultipart() msg['From'] = from_addr msg['To'] = to_addr msg['Subject'] = str(name) + " has shared their wishlist with you" body = "Member " + str(name) + " from Wishlstproject.com has shared their wishlist with you!! https://www.google.com/search?q=cats+meme&client=firefox-b&noj=1&source=lnms&tbm=isch&sa=X&ved=0ahUKEwizk8GiyMXTAhWBKiYKHc0NAh0Q_AUICigB&biw=1366&bih=669" msg.attach(MIMEText(body, 'plain')) #from_name = 'wishlistproject' #to_name = request.json['name'] #subject = 'Someone has shared their wishlist with you' ### message = 'Member '+ username + 'from Wishlstproject.com has shared his/her wishlist with you!! /n http://info3180-project2-shadain94.c9users.io/api/users/' + userid + '/wishlist' #message = "test" #message_to_send = message.format(from_name, from_addr, to_name, to_addr, subject, message) # Credentials (if needed) username = '******' password = '******' # The actual mail send server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.login(username, password) text = msg.as_string() server.sendmail(from_addr, to_addr, text) server.quit() response = jsonify({"error":"null", "message":"Success"}) return response def timeinfo(entry): day = time.strftime("%a") date = time.strftime("%d") if (date <10): date = date.lstrip('0') month = time.strftime("%b") year = time.strftime("%Y") return day + ", " + date + " " + month + " " + year @app.route('/<file_name>.txt') def send_text_file(file_name): """Send your static text file.""" file_dot_text = file_name + '.txt' return app.send_static_file(file_dot_text) @app.after_request def add_header(response): """ Add headers to both force latest IE rendering engine or Chrome Frame, and also to cache the rendered page for 10 minutes. """ response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1' response.headers['Cache-Control'] = 'public, max-age=0' return response @app.errorhandler(404) def page_not_found(error): """Custom 404 page.""" return render_template('404.html'), 404 if __name__ == '__main__': app.run(debug=True,host="0.0.0.0",port="8080")
#!/usr/bin/env python # MIME message generation with 8-bit headers - Chapter 9 # mime_headers.py # This program requires Python 2.2.2 or above from email.MIMEText import MIMEText from email.Header import Header from email import Utils message = """Hello, This is a test message from Chapter 9. I hope you enjoy it! -- Anonymous""" msg = MIMEText(message) msg['To'] = '*****@*****.**' fromhdr = Header("Michael M\xfcller", 'iso-8859-1') fromhdr.append('<*****@*****.**>', 'ascii') msg['From'] = fromhdr msg['Subject'] = Header('Test Message, Chapter 9') msg['Date'] = Utils.formatdate(localtime = 1) msg['Message-ID'] = Utils.make_msgid() print msg.as_string()
def addAttachments(self, mainmsg, bodytext, attaches): # format a multipart message with attachments msg = MIMEText(bodytext) # add main text/plain part mainmsg.attach(msg) for filename in attaches: # absolute or relative paths if not os.path.isfile(filename): # skip dirs, etc. continue # guess content type from file extension, ignore encoding contype, encoding = mimetypes.guess_type(filename) if contype is None or encoding is not None: # no guess, compressed? contype = 'application/octet-stream' # use generic default print>>sys.stderr,'Adding ' + contype # build sub-Message of appropriate kind maintype, subtype = contype.split('/', 1) if maintype == 'text': data = open(filename, 'r') msg = MIMEText(data.read( ), _subtype=subtype) data.close( ) elif maintype == 'image': data = open(filename, 'rb') msg = MIMEImage(data.read( ), _subtype=subtype) data.close( ) elif maintype == 'audio': data = open(filename, 'rb') msg = MIMEAudio(data.read( ), _subtype=subtype) data.close( ) else: data = open(filename, 'rb') msg = MIMEBase(maintype, subtype) msg.set_payload(data.read( )) data.close( ) # make generic type email.Encoders.encode_base64(msg) # encode using base64 # set filename and attach to container basename = os.path.basename(filename) msg.add_header('Content-Disposition', 'attachment', filename=basename) mainmsg.attach(msg) # text outside mime structure, seen by non-MIME mail readers mainmsg.preamble = 'A multi-part MIME format message.\n' mainmsg.epilogue = '' # make sure message ends with a newline
def check_email(): """Check the mail account and lint new mail.""" server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.ehlo() server.login(user, password) g = gmail.login(user, password) # Check for unread messages. unread = g.inbox().mail(unread=True) # Submit a job to lint each email sent to [email protected]. Record the # resulting job_ids somewhere (in Redis, I suppose), keyed by a hash of the # email. for u in unread: u.fetch() signature = (u.fr.decode('utf-8') + u.subject.decode('utf-8') + u.body.decode('utf-8')) hash = hashlib.sha256(signature.encode('utf-8')).hexdigest() if user_to in u.to or user_to in u.headers.get('Cc', []): job_id = conn.get(hash) if not job_id: # If the email hasn't been sent for processing, send it. r = requests.post(api_url, data={"text": u.body}) conn.set(hash, r.json()["job_id"]) print("Email {} sent for processing.".format(hash)) else: # Otherwise, check whether the results are ready, and if so, # reply with them. r = requests.get(api_url, params={"job_id": job_id}) if r.json()["status"] == "success": reply = quoted(u.body) errors = r.json()['data']['errors'] reply += "\r\n\r\n".join([json.dumps(e) for e in errors]) msg = MIMEMultipart() msg["From"] = "{} <{}>".format(name, user) msg["To"] = u.fr msg["Subject"] = "Re: " + u.subject if u.headers.get('Message-ID'): msg.add_header("In-Reply-To", u.headers['Message-ID']) msg.add_header("References", u.headers['Message-ID']) body = reply + "\r\n\r\n--\r\n" + tagline + "\r\n" + url msg.attach(MIMEText(body, "plain")) text = msg.as_string() server.sendmail(user, u.fr, text) # Mark the email as read. u.read() u.archive() print("Email {} has been replied to.".format(hash))
def addTextPart(self, text, text_type): self.msg.attach(MIMEText(text, text_type))
def SendMail(SMTP="", Subject="", From="", To=[], CC=[], Message="", html_file="", Files=[]): """ ---------------------------------------------------------------------------------- Send a mail using SMTP address. Usage : SendMail (SMTP, From, To, Message, [Subject, CC, html_file, files]) Parameters "SMTP", "From", "To" and "Message" are necessary. "Subject", "C"C, "html_file" and "files" are optionnal. To send an e-mail in html format you can use "html_file" option. By default To and CC parameters are composed by mail addresses. To send mails to alias To and CC parameters must have 2 sub-lists. To or CC = [ [receiver_list] , [header_list ]. receiver_list is composed by al the elementary mail addresses. header_list is composed by alias. ---------------------------------------------------------------------------------- """ if SMTP == "": print "Error : SMTP is empty" sys.exit(1) if From == "": print "Error : From address is empty" sys.exit(1) if To == []: print "Error : To address is empty" sys.exit(1) if Message == "": print "Error : Message is empty" sys.exit(1) if type(To[0]) == list and type(To[1]) == list: To_header = "; ".join(To[1]) To_receiver = "; ".join(To[0]) else: To_header = To_receiver = "; ".join(To) if type(CC[0]) == list and type(CC[1]) == list: CC_header = "; ".join(CC[1]) CC_receiver = "; ".join(CC[0]) else: CC_header = CC_receiver = "; ".join(CC) msg = MIMEMultipart() msg['From'] = From msg['Date'] = formatdate(localtime=True) msg['To'] = To_header if CC != "": msg['CC'] = CC_header msg['Subject'] = Subject if html_file != "": temp = open(html_file, 'rb') msg.attach(MIMEText(Message + temp.read(), 'html')) temp.close() else: msg.attach(MIMEText(Message)) #Attach all the files into mail if len(Files) > 0: for my_file in Files: if (os.path.isfile(my_file)): part = MIMEBase('application', "octet-stream") part.set_payload(open(my_file, "rb").read()) Encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(my_file)) msg.attach(part) else: print 'Error : File ' + my_file + ' does not exist.' ##For Debug only #print "-->SMTP: %s \r\n\r\n-->From : %s \r\n\r\n-->To: %s \r\n\r\n-->To_h: %s \r\n\r\nSubject: %s \r\n\r\n-->Files: %s \r\n\r\n-->To_s: %s \r\n\r\n-->Message: %s" % (SMTP, From, To, To_header, Subject, Files, To_receiver, msg.as_string()) ##### Send notification mail ##### ## Connect to SMTP server try: mailServer = smtplib.SMTP(SMTP) except: print 'Error : SMTP connexion failed' sys.exit(1) ## Send mail try: mailServer.sendmail(From, To[0], msg.as_string()) except: print 'Error : Could not send mail ' sys.exit(1) ## Quit try: mailServer.quit() except: print 'Error : Could not exit properly' sys.exit(1)
def mail(to, subject, prioflag1, prioflag2, text): msg = MIMEMultipart() msg['From'] = str( Header(from_displayname, 'UTF-8').encode() + ' <' + from_address + '> ') msg['To'] = to msg['X-Priority'] = prioflag1 msg['X-MSMail-Priority'] = prioflag2 msg['Subject'] = Header(subject, 'UTF-8').encode() body_type = MIMEText(text, "%s" % (message_flag), 'UTF-8') msg.attach(body_type) # now attach the file if file_format != "": fileMsg = email.mime.base.MIMEBase('application', '') fileMsg.set_payload(file(file_format).read()) email.encoders.encode_base64(fileMsg) fileMsg.add_header('Content-Disposition', 'attachment;filename=%s' % (file_format)) msg.attach(fileMsg) mailServer = smtplib.SMTP(smtp, port) io = StringIO() msggen = Generator(io, False) msggen.flatten(msg) if sendmail == 0: if email_provider == "gmail" or email_provider == "yahoo" or email_provider == "hotmail": try: mailServer.starttls() except: pass mailServer.ehlo() else: mailServer.ehlo() try: if provideruser != "" or pwd != "": mailServer.login(provideruser, pwd) mailServer.sendmail(from_address, to, io.getvalue()) else: mailServer.sendmail(from_address, to, io.getvalue()) except: # try logging in with base64 encoding here import base64 try: mailServer.docmd("AUTH LOGIN", base64.b64encode(provideruser)) mailServer.docmd(base64.b64encode(pwd), "") # except exceptions and print incorrect passowrd except Exception as e: print_warning( "It appears your password was incorrect.\nPrinting response: " + (str(e))) return_continue() if sendmail == 1: mailServer.sendmail(from_address, to, io.getvalue())
class Message(object): def __init__(self, from_addr, to_addrs, subject, message, mime="text/plain", charset="utf-8"): self.subject = subject self.from_addr = from_addr if isinstance(to_addrs, types.StringType): self.to_addrs = [to_addrs] else: self.to_addrs = to_addrs self.msg = None self.__cache = None self.message = MIMEText(message) self.message.set_charset(charset) self.message.set_type(mime) def attach(self, filename, mime=None, charset=None, content=None): base = os.path.basename(filename) if content is None: fd = open(filename) content = fd.read() fd.close() elif not isinstance(content, types.StringType): raise TypeError("Don't know how to attach content: %s" % \ repr(content)) part = MIMEBase("application", "octet-stream") part.set_payload(content) Encoders.encode_base64(part) part.add_header("Content-Disposition", 'attachment; filename="%s"' % base) if mime is not None: part.set_type(mime) if charset is not None: part.set_charset(charset) if self.msg is None: self.msg = MIMEMultipart() self.msg.attach(self.message) self.msg.attach(part) def __str__(self): return self.__cache or "cyclone email message: not rendered yet" def render(self): if self.msg is None: self.msg = self.message self.msg["Subject"] = self.subject self.msg["From"] = self.from_addr self.msg["To"] = COMMASPACE.join(self.to_addrs) self.msg["Date"] = formatdate(localtime=True) if self.__cache is None: self.__cache = self.msg.as_string() return StringIO(self.__cache)
cap = cv2.VideoCapture(0) print "Saving Photo" picname = datetime.now().strftime("%y-%m-%d-%H-%M") picname = picname + '.jpg' cv2.imwrite(picname, frame) print "Sending email" attach = picname 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)) 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())