def send_mail(send_from, send_to, subject, text, files=[]): assert type(send_to) == list assert type(files) == list print('Sending {} to {}'.format(files, send_to)) emailMsg = MIMEMultipart() emailMsg['From'] = send_from if CcEmail: emailMsg['Cc'] = COMMASPACE.join([send_from]) emailMsg['To'] = COMMASPACE.join(send_to) emailMsg['Date'] = formatdate(localtime=True) emailMsg['Subject'] = subject emailMsg.attach(MIMEText(text)) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload(open(f, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) emailMsg.attach(part) smtp = smtplib.SMTP(MailServer) if TestMode: print('Test mode - no email sent [%s]'.format(subject)) else: print('SMTP: To [{}] From [{}]'.format(send_to, emailMsg['From'])) smtp.sendmail(emailMsg['From'], send_to, emailMsg.as_string()) smtp.close()
def send(self, to, subject, body, cc=None, attachs=(), mimetype='text/plain', _callback=None): if attachs: msg = MIMEMultipart() else: msg = MIMENonMultipart(*mimetype.split('/', 1)) msg['From'] = self.mailfrom msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject rcpts = to[:] if cc: rcpts.extend(cc) msg['Cc'] = COMMASPACE.join(cc) if attachs: msg.attach(MIMEText(body)) for attach_name, mimetype, f in attachs: part = MIMEBase(*mimetype.split('/')) part.set_payload(f.read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' \ % attach_name) msg.attach(part) else: msg.set_payload(body) if _callback: _callback(to=to, subject=subject, body=body, cc=cc, attach=attachs, msg=msg) dfd = self._sendmail(rcpts, msg.as_string()) dfd.addCallbacks(self._sent_ok, self._sent_failed, callbackArgs=[to, cc, subject, len(attachs)], errbackArgs=[to, cc, subject, len(attachs)]) reactor.addSystemEventTrigger('before', 'shutdown', lambda: dfd) return dfd
def send_mail(p_send_from, p_send_to, p_send_cc, p_subject, p_text, p_files = [], p_server = "localhost"): try: assert type(p_send_to) == list assert type(p_send_cc) == list assert type(p_files) == list msg = MIMEMultipart() msg['From'] = p_send_from msg['To'] = COMMASPACE.join(p_send_to) msg['Cc'] = COMMASPACE.join(p_send_cc) msg['Date'] = formatdate(localtime = True) msg['Subject'] = p_subject msg.attach(MIMEText(p_text)) for l_files in p_files: part = MIMEBase('application', "octet-stream") part.set_payload(open(l_files, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(l_files)) msg.attach(part) smtp = smtplib.SMTP(p_server) smtp.sendmail(p_send_from, p_send_to + p_send_cc, msg.as_string()) smtp.close() print "Email successfully sent..!" except Exception, e: print "\n* EXCEPTION DURING EMAIL SENDING: ", e
def send_email( self, message, mail_server_id=None, smtp_server=None, smtp_port=None, smtp_user=None, smtp_password=None, smtp_encryption=None, smtp_debug=False): override_email = self.env.ref( 'override_mail_recipients.override_email_to').value if override_email: for field in ['to', 'cc', 'bcc']: if not message[field]: continue original = COMMASPACE.join(message.get_all(field, [])) del message[field] message[field] = COMMASPACE.join( '"%s" <%s>' % ( original.replace('\\', '').replace('"', '\\"') .replace('<', '[').replace('>', ']') .replace('@', '(at)'), email ) for email in extract_rfc2822_addresses(override_email)) return super(IrMailServer, self).send_email( message, mail_server_id=mail_server_id, smtp_server=smtp_server, smtp_port=smtp_port, smtp_user=smtp_user, smtp_password=smtp_password, smtp_encryption=smtp_encryption, smtp_debug=smtp_debug)
def sendMailWithAttachements(context, sender, receiver, cc=[], bcc=[], subject="", text="", files=[]): """ """ mail = MIMEMultipart() mail['From'] = sender mail['To'] = receiver mail['Cc'] = COMMASPACE.join(cc) mail['Bcc'] = COMMASPACE.join(bcc) mail['Subject'] = subject # text = text.encode("utf-8") # text_part = MIMEText(text, "plain", "utf-8") # mail.attach(text_part) # create & attach html part with images text = text.encode("utf-8") mail.attach(MIMEText(text, "html", "utf-8")) for filename, file_ in files: try: data = file_.data.data except AttributeError: data = file_.data attachment_part = MIMEBase('application', "octet-stream") attachment_part.set_payload(data) Encoders.encode_base64(attachment_part) attachment_part.add_header('Content-Disposition', 'attachment; filename=%s' % filename) mail.attach(attachment_part) context.MailHost.send(mail.as_string())
def send_mail(**a): assert type(a['send_to'])==list assert type(a['files'])==list msg = MIMEMultipart() msg['From'] = a['send_from'] msg['To'] = COMMASPACE.join(a['send_to']) msg['cc'] = COMMASPACE.join(a['send_cc']) msg['Date'] = formatdate(localtime=True) msg['Subject'] = a['subject'] msg.attach( MIMEText(a['text']) ) for f in a['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) try: smtp = smtplib.SMTP(a['server']) smtp.sendmail(a['send_from'], a['send_to']+a['send_cc'], msg.as_string()) smtp.close() except SMTPException: pass
def send_email( self, message, mail_server_id=None, smtp_server=None, smtp_port=None, smtp_user=None, smtp_password=None, smtp_encryption=None, smtp_debug=False): override_email = self.env['ir.model.data'].xmlid_to_object( 'override_mail_from.override_email_from', raise_if_not_found=True).value if override_email: for field in ['from', 'reply-to']: if not message[field]: continue original = COMMASPACE.join(message.get_all(field, [])) del message[field] message[field] = COMMASPACE.join( '"%s" <%s>' % ( original.replace('\\', '').replace('"', '\\"') .replace('<', '[').replace('>', ']') .replace('@', '(at)'), email ) for email in extract_rfc2822_addresses(override_email)) return super(IrMailServer, self).send_email( message, mail_server_id=mail_server_id, smtp_server=smtp_server, smtp_port=smtp_port, smtp_user=smtp_user, smtp_password=smtp_password, smtp_encryption=smtp_encryption, smtp_debug=smtp_debug)
def send_mail(sender, receivers, subject='', content='', ccs=[], bccs=[], attachment=[]): try: print "Sending Email" # All receivers all_recvs = [] all_recvs.extend(receivers) all_recvs.extend(ccs) all_recvs.extend(bccs) msg = MIMEMultipart() msg.attach(MIMEText(content, 'html', 'utf-8')) msg['Subject'] = subject msg['From'] = sender msg['To'] = COMMASPACE.join(receivers) print msg['To'] msg['Cc'] = COMMASPACE.join(ccs) for att in attachment: part = MIMEApplication(open(att, "rb").read()) part.add_header("Content-Disposition", "attachment", filename=os.path.basename(att)) msg.attach(part) server = smtplib.SMTP('mail.intel.com') server.sendmail(sender, all_recvs, msg.as_string()) print "Email sent out" server.quit() except Exception as err: print "[ERROR:]{0}".format(str(err)) print sys.exc_info()[1] return False return True
def send(self, to, subject, body, cc=None, attachs=(), mimetype='text/plain',body_encode='utf8'): if attachs: msg = MIMEMultipart() else: msg = MIMENonMultipart(*mimetype.split('/', 1)) msg['From'] = self.mailfrom msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject rcpts = to[:] if cc: rcpts.extend(cc) msg['Cc'] = COMMASPACE.join(cc) if attachs: msg.attach(MIMEText(body, 'plain', body_encode)) for attach_name, mimetype, f in attachs: part = MIMEBase(*mimetype.split('/')) part.set_payload(f.read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' \ % attach_name) msg.attach(part) else: msg.set_payload(body) try: self._sendmail(rcpts, msg.as_string()) except smtplib.SMTPException, e: self._sent_failed(e, to, cc, subject, len(attachs)) return False
def send_mail(send_from, send_to,send_cc, subject, text, files=[],server="localhost"): assert type(send_to)==list assert type(files)==list msg = MIMEMultipart('alternative') msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) if send_cc is None: send_tocc = send_to else: assert type(send_cc)==list msg['Cc'] = COMMASPACE.join(send_cc) send_tocc = send_to + send_cc msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.sendmail(send_from, send_tocc, msg.as_string()) smtp.close()
def notifyWithBCC( receiver = ['email'],\ cc = [''],\ bcc = [''],\ subject = 'generic subject',\ body = 'generic body',\ files=[], transmitter = 'email', server = '192.168.75.40'): header = "From: %s\r\nTo: %s\r\nSubject: %s\r\nX-Mailer: My-Mail\r\n\r\n" % (transmitter, receiver, subject) #msg = header + body msg = MIMEMultipart() msg['From'] = transmitter msg['To'] = COMMASPACE.join(receiver) msg['Cc'] = COMMASPACE.join(cc) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(body) ) 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) server = smtplib.SMTP(server) server.set_debuglevel(0) server.sendmail(transmitter, receiver + cc + bcc, msg.as_string()) server.quit()
def send_mail(subject, message, server="localhost"): sender = "*****@*****.**" to = ['*****@*****.**'] cc = [] msg = MIMEMultipart() msg['From'] = sender msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg['Cc'] = COMMASPACE.join(cc) msg.attach(MIMEText(message)) addresses = [] for x in to: addresses.append(x) for x in cc: addresses.append(x) try: smtp = smtplib.SMTP(server) smtp.sendmail(sender, addresses, msg.as_string()) smtp.close() log.info("Mail Sent Successfully") except smtplib.SMTPException as e: log.error("%s", traceback.format_exc())
def send_mail( send_from, send_to, subject, text, cc, \ bcc, attachments, server, login, passwd ) : assert type( send_to )==list assert type( attachments )==list assert type( cc )==list assert type( bcc )==list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join( send_to ) #msg['To'] = send_to[0] msg['CC'] = COMMASPACE.join( cc ) #msg['CC'] = cc[0] msg['BCC'] = COMMASPACE.join( bcc ) #msg['BCC'] = bcc[0] msg['Date'] = formatdate( localtime=True ) msg['Subject'] = subject msg.attach( MIMEText( text ) ) for f in attachments : part = MIMEBase( 'application', "octet-stream" ) part.set_payload( open( f, "rb" ).read() ) Encoders.encode_base64( part ) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename( f )) msg.attach( part ) server = smtplib.SMTP( server ) if login : server.login( login, passwd ) server.sendmail( send_from, send_to, msg.as_string() ) server.close()
def send_mail(**a): assert type(a['send_to'])==list assert type(a['files'])==list msg = MIMEMultipart() msg['From'] = a['send_from'] msg['To'] = COMMASPACE.join(a['send_to']) msg['cc'] = COMMASPACE.join(a['send_cc']) msg['Date'] = formatdate(localtime=True) msg['Subject'] = a['subject'] msg.attach( MIMEText(a['text']) ) for f in a['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) try: smtp = smtplib.SMTP(a['server']) smtp.sendmail(a['send_from'], a['send_to']+a['send_cc'], msg.as_string()) smtp.close() except Exception.SMTPException: pass
def sendmail(subject, message, sender='*****@*****.**', to=[], cc=[], bcc=[], attachments=[], priority=3, type_="plain", smtp_server="smtp.eecs.umich.edu"): assert priority in range(1,6) msg = MIMEMultipart() msg['From'] = sender msg['To'] = COMMASPACE.join(to) msg['Cc'] = COMMASPACE.join(cc) msg['X-Priority'] = str(priority) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(message, type_)) for f in attachments: part = MIMEBase('application', "octet-stream") part.set_payload(open(f,"rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"'\ % os.path.basename(f)) msg.attach(part) to.extend(cc) to.extend(bcc) smtp = smtplib.SMTP(smtp_server) smtp.sendmail(sender, to, msg.as_string()) smtp.close()
def sendMailOnChanges(self, messageText, emailSubject, org_message_ID, new_message_ID, username=False, diff_HN_adress=None, **kwargs): msg = MIMEMultipart() reply_to = [] send_to = [] if org_message_ID != None: msg['In-Reply-To'] = org_message_ID msg['References'] = org_message_ID #send_from = "*****@*****.**" send_from = getUserEmail(username, Session) msg['From'] = send_from if diff_HN_adress == None: send_to += [self.MAILING_LIST[0]] else: send_to += [diff_HN_adress] #if username != False: #send email copy to the sender himself # email = getUserEmail(username, Session) # send_to.append(email) reply_to.append(send_from) #make a reply header to sender+receivers of the email. reply_to.append("*****@*****.**") msg['reply-to'] = COMMASPACE.join(reply_to) msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = emailSubject msg['Message-ID'] = new_message_ID try: msg.attach(MIMEText(messageText)) smtpObj = smtplib.SMTP() smtpObj.connect() smtpObj.sendmail(send_from, send_to, msg.as_string()) smtpObj.close() except Exception as e: logging.error("Error: unable to send email: %s", str(e))
def send_email(to, subject, text, user_from, files=[], cc=[], bcc=[], server=EMAIL_SERVER, port = EMAIL_PORT, user = EMAIL_USER, password = EMAIL_PASS, domain = EMAIL_DOMAIN): message = MIMEMultipart() message['From'] = user_from message['To'] = COMMASPACE.join(to) message['Date'] = formatdate(localtime=True) message['Subject'] = subject message['Cc'] = COMMASPACE.join(cc) message.attach(MIMEText(text)) for f in files: part = MIMEBase('application', 'octet-stream') part.set_payload(f) part.add_header('Content-Disposition', 'attachment; filename="%s"' % \ 'report.csv') message.attach(part) addresses = [] for x in to: addresses.append(x) for x in cc: addresses.append(x) for x in bcc: addresses.append(x) s = smtplib.SMTP_SSL(server, port, domain) s.login(user, password) s.sendmail(user_from, addresses, message.as_string())
def sendEmail(send_from, send_to, subject, text, cc_to=[], files=[], server="192.168.42.13"): assert type(send_to)==list assert type(files)==list msg=MIMEMultipart() msg.set_charset("utf-8") msg['From']=send_from msg['To']=COMMASPACE.join(send_to) if cc_to: assert type(cc_to)==list msg['cc']=COMMASPACE.join(cc_to) send_to.extend(cc_to) msg['Date']=formatdate(localtime=True) msg['Subject']=subject msg.attach(MIMEText(text)) for f in files: part=MIMEBase('application', "octet-stream") part.set_payload(open(f, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"'%Header(os.path.basename(f), 'utf-8')) msg.attach(part) smtp=smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send_mail(send_to, subject, text, files=[], cc=[]): assert isinstance(send_to, list) assert isinstance(files, list) assert isinstance(cc, list) msg = MIMEMultipart() msg['From'] = sender_username msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject #new things... msg['CC'] = COMMASPACE.join(cc) send_to = send_to + cc msg.attach( MIMEText(text) ) for f in files: print "Attaching %s..." % os.path.basename(f), 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) print "Sending...", smtp = smtplib.SMTP('smtpout.secureserver.net', 80) smtp.login(sender_username, sender_pass) smtp.sendmail(sender_username, send_to, msg.as_string()) smtp.close()
def send_mail( send_to, message_subject, message_text, Out, message_html = "", send_from = "", files = [], send_cc = [], send_bcc = [], mail_server = "localhost", smtp_user = "", smtp_password = "" ): try: # Assertions assert type( send_to ) == list assert type( files ) == list assert type( send_cc ) == list assert type( send_bcc ) == list # Build the message message = MIMEMultipart( 'related' ) message[ 'From' ] = send_from message[ 'To' ] = COMMASPACE.join( send_to ) message[ 'Date' ] = formatdate( localtime = True ) message[ 'Subject' ] = message_subject message[ 'Cc' ] = COMMASPACE.join( send_cc ) message.attach( MIMEText( message_text ) ) # Attachments 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 ) ) message.attach( part ) # Now who it's going to addresses = [] for adr in send_to: addresses.append( adr ) for adr in send_cc: addresses.append( adr ) for adr in send_bcc: addresses.append( adr ) # Now send it if ( len( addresses ) > 0 ): Out.OutputInfo('Sending from send_mail function') #smtp = smtplib.SMTP( mail_server ) #smtp.sendmail( send_from, addresses, message.as_string( ) ) #smtp.close( ) mailServer = smtplib.SMTP_SSL( mail_server , 465) mailServer.ehlo() mailServer.login(smtp_user, smtp_password) mailServer.sendmail( send_from, send_to, message.as_string() ) mailServer.close( ) else: Out.OutputError( 'No addressees to send the e-mail to', True ) except KeyboardInterrupt: Out.OutputError( 'Keyboard interrupt detected', False ) raise except: Out.OutputError( 'Attempting to send SMTP message', True ) Out.OutputException( sys.exc_info( ), True ) return
def send(self, to, subject, body, cc=None, attachs=()): if attachs: msg = MIMEMultipart() else: msg = MIMENonMultipart('text', 'plain') msg['From'] = self.mailfrom msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject rcpts = to[:] if cc: rcpts.extend(cc) msg['Cc'] = COMMASPACE.join(cc) if attachs: msg.attach(MIMEText(body)) for attach_name, mimetype, f in attachs: part = MIMEBase(*mimetype.split('/')) part.set_payload(f.read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' \ % attach_name) msg.attach(part) else: msg.set_payload(body) if self.signals: self.signals.send_catch_log(signal=mail_sent, to=to, subject=subject, body=body, cc=cc, attach=attachs, msg=msg) if self.debug: log.msg( format= 'Debug mail sent OK: To=%(mailto)s Cc=%(mailcc)s Subject="%(mailsubject)s" Attachs=%(mailattachs)d', level=log.DEBUG, mailto=to, mailcc=cc, mailsubject=subject, mailattachs=len(attachs)) return dfd = self._sendmail(rcpts, msg.as_string()) dfd.addCallbacks(self._sent_ok, self._sent_failed, callbackArgs=[to, cc, subject, len(attachs)], errbackArgs=[to, cc, subject, len(attachs)]) reactor.addSystemEventTrigger('before', 'shutdown', lambda: dfd) return dfd
def reply_function(): msg = MIMEMultipart() send_from = cherrypy.session.get('_cp_username')+"@ecommunicate.ch" #msg['From'] = send_to = re.findall(r'[^\;\,\s]+',to) send_cc = re.findall(r'[^\;\,\s]+',cc) for email_address in (send_to + send_cc): if email_address.split("@")[1] != "ecommunicate.ch": return "Can only send emails to ecommunicate.ch e-mail addresses." msg['To'] = COMMASPACE.join(send_to) msg['CC'] = COMMASPACE.join(send_cc) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg['Message-ID'] = email.Utils.make_msgid() mime_applications = [] l = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9'] if len(attachments) > 36: raise Exception for i,attachment in enumerate(attachments): if attachment.file != None and attachment.filename != "": tmp_filename=os.popen("mktemp").read().rstrip('\n') open(tmp_filename,'wb').write(attachment.file.read()); if str(attachment.content_type) == "application/pdf": mime_application = MIMEApplication(open(tmp_filename,'rb').read(),"pdf") mime_application['Content-Disposition'] = 'attachment; filename="'+str(attachment.filename)+'"' mime_application['Content-Description'] = str(attachment.filename) mime_application['X-Attachment-Id'] = str("f_")+l[random.randint(0,35)]+l[random.randint(0,35)]+l[random.randint(0,35)]+l[random.randint(0,35)]+l[i]+l[random.randint(0,35)]+l[random.randint(0,35)]+l[random.randint(0,35)]+l[random.randint(0,35)] mime_applications.append(mime_application) try: msg.attach(MIMEText(body)) for mime_application in mime_applications: msg.attach(mime_application) smtpObj = smtplib.SMTP(port=25) smtpObj.connect() smtpObj.sendmail(send_from, send_to+send_cc, msg.as_string()) smtpObj.close() except Exception as e: print "Error: unable to send email", e.__class__
def send(self, subject, to, content, html_content=None, from_='', cc=[], bcc=[], type='plain', mpart_type='alternative'): """Sends an email In: - ``subject`` -- email subject - ``to`` -- list of recipients' emails - ``content`` -- email content - ``from_`` -- email sender adress - ``cc`` -- list of CC emails - ``bcc`` -- list of BCC emails - ``type`` -- email type ('plain' or 'html') - ``mpart_type`` -- email part type """ from_ = from_ if from_ else self.default_sender # create the message envelop msg = MIMEMultipart(mpart_type) msg['Subject'] = subject msg['Date'] = formatdate(localtime=True) msg['From'] = from_ msg['To'] = COMMASPACE.join(to) if cc: msg['Cc'] = COMMASPACE.join(cc) # attach the mail content charset = 'us-ascii' if isinstance(content, unicode): content = content.encode('UTF-8') charset = 'UTF-8' msg.attach(MIMEText(content, type, charset)) if html_content: msg.attach(MIMEText(html_content, 'html', charset)) # log log.info( '%s mail:\n subject=%s\n from=%s\n to=%s\n cc=%s\n bcc=%s', 'sending' if self.activated else 'ignoring', subject, from_, to, cc, bcc) log.debug('Mail content:\n' + content) # post the email to the SMTP server if self.activated: self._smtp_send(from_, to + cc + bcc, msg.as_string())
def email_html_send_attach(email_from, email_to, subject, body, email_cc=None, email_bcc=None, on_error=False, reply_to=False, attach=None, tinycrm=False): if not email_cc: email_cc=[] if not email_bcc: email_bcc=[] if not attach: attach=[] msg = MIMEMultipart('related') msg['Subject'] = Header(subject.decode('utf8'), 'utf-8') msg['From'] = email_from del msg['Reply-To'] if reply_to: msg['Reply-To'] = reply_to msg['To'] = COMMASPACE.join(email_to) if email_cc: msg['Cc'] = COMMASPACE.join(email_cc) if email_bcc: msg['Bcc'] = COMMASPACE.join(email_bcc) if tinycrm: msg['Message-Id'] = '<'+str(time.time())+'-tinycrm-'+str(tinycrm)+'@'+socket.gethostname()+'>' msg['Date'] = formatdate(localtime=True) msg_alt = MIMEMultipart('alternative') msg_alt.attach(MIMEText("Vous devez activez l'affichage en mode HTML pour lire ce message.")) body_part = MIMEText(body , _subtype='html') body_part.set_charset('UTF-8') msg_alt.attach(body_part) msg.attach(msg_alt) for (fname,fcontent) in attach: part = MIMEBase('application', "octet-stream") part.set_payload( fcontent ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % (fname,)) msg.attach(part) try: s = smtplib.SMTP() s.connect(config['smtp_server']) if config['smtp_user'] or config['smtp_password']: s.login(config['smtp_user'], config['smtp_password']) s.sendmail(email_from, email_to + email_cc + email_bcc, msg.as_string()) s.quit() except Exception, e: import logging logging.getLogger().info(str(e))
def build_invitation(self, email_from='', email_to='', subject='', email_cc=[], email_bcc=[], reply_to=False, attachments=None, message_id=None, references=None, object_id=False, headers={}, ): 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." msg = MIMEMultipart() if not headers: headers = {} 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() for key, value in headers.items(): msg[ustr(key).encode('utf-8')] = encode_header(value) text_to_body_added = False if attachments: #it is assumed for now that only ics file is attached!!! for fname, fcontent in attachments: if not text_to_body_added and fname == 'invite.ics': # Provide message description in body of message only as text for now; need fixes if 'DESCRIPTION:' in fcontent and 'LOCATION' in fcontent.split('DESCRIPTION')[1]: meeting_description_text = fcontent.split('DESCRIPTION:')[1].split('LOCATION')[0] text_converted_to_html = self.plaintext2html(meeting_description_text, tabstop=4) text_utf8 = re.sub(r'\\n', "</p><p>", text_converted_to_html) alternative_part = MIMEMultipart(_subtype="alternative") alternative_part.attach(MIMEText(text_utf8, _charset='utf-8', _subtype='html')) msg.attach(alternative_part) #adding invitation stuff part = MIMEBase('text', 'calendar', charset='utf-8', method='REQUEST') part.set_payload(fcontent) msg.attach(part) return msg
def send(self, sender, recipient, subject, text=None, html=None, files=[], cc=[], dry_run=False): try: msg = MIMEMultipart("alternative") if isinstance(recipient, str): recipient = recipient.split(',') if isinstance(cc, str): cc = cc.split(',') msg['From'] = sender msg['To'] = COMMASPACE.join(recipient) if cc: msg['Cc'] = COMMASPACE.join(cc) msg['Date'] = formatdate(localtime=True) msg['Subject'] = Header(subject, "utf-8") # 內文 if text: msg.attach(MIMEText(text, "plain", "utf-8")) if html: msg.attach(MIMEText(html, "html", "utf-8")) # 附加檔案 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) # 寄出 if not dry_run: self.smtp.sendmail(sender, list(chain(recipient, cc)), msg.as_string()) return True except Exception as error: print("Unable to send e-mail: '%s'." % str(error)) return False
def sendMail(send_from, send_to, subject, text=None, html=None, files=None, server='172.25.1.8', send_cc=None): assert type(send_to) is list files = files or [] assert type(files) is list send_cc = send_cc or [] assert type(send_cc) is list # Need at least text or html specified assert text is not None or html is not None msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) if send_cc: msg['Cc'] = COMMASPACE.join(send_cc) msg['Date'] = formatdate(localtime=True) msg['Subject'] = Header(subject) # attach parts into message container # according to RFC 2046, the last part of a multipart message, in this case # the HTML message, is best and preferred if text is not None: msg.attach(MIMEText(text, 'plain')) if html is not None: msg.attach(MIMEText(html, 'html')) # attach files 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)) if send_cc: send_to += send_cc smtp = smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send(self, sender, recipients, subject, text, attachments=None): To =[] for recipient in recipients.split(','): self.logger.debug('Appending to recipients list : {0}'.format(recipient)) To.append(recipient) msg = MIMEMultipart() msg['From'] = sender self.logger.debug('Set sender to : {0}'.format(sender)) msg['To'] = COMMASPACE.join(To) self.logger.debug('Set recipients to : {0}'.format(COMMASPACE.join(To))) msg['Date'] = formatdate(localtime=True) self.logger.debug('Set date to : {0}'.format(formatdate(localtime=True))) msg['Subject'] = subject.decode('utf-8') self.logger.debug('Set subject to : {0}'.format(subject.decode('utf-8'))) msg.preamble = 'Multipart massage.\n' part = MIMEText(text, 'plain', 'UTF-8') msg.attach(part) # This is the binary part(The Attachment): if attachments: for attachment in attachments.split(','): self.logger.debug('Appending to attachment list : {0}'.format(attachment)) part = MIMEApplication(open(attachment,"rb").read()) part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment)) msg.attach(part) # Could set tls for encryption #smtp.starttls() # Could use credentials for authentication #smtp.login('user','pass') try: self.logger.debug('Opening smtp connection with argument : {0}'.format(self.smtp)) smtp = smtplib.SMTP(self.smtp) self.logger.debug('Sending email report with attachments.') smtp.sendmail(sender, To, msg.as_string() ) self.logger.debug('Done sending email report.') result = True except Exception: self.logger.warning('Sending of mail failed!') self.logger.warning('Traceback :', exc_info=True) result = False self.logger.debug('Closing smtp connection.') try: smtp.close() self.logger.debug('Done closing smtp connection.') result = True except Exception: self.logger.warning('Smtp connection not closed properly. Propably the email sending failed.') result = False return result
def send_mail( text, send_from, send_to, subject, cc_to=[], files=[], server={ 'server': "localhost", 'port': None, 'username': '', 'password': '', 'ssl': False, }): assert type(send_to) == list assert type(files) == list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) if cc_to: assert type(cc_to) == list msg['cc'] = COMMASPACE.join(cc_to) send_to.extend(cc_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload(open(f, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) if server.get('ssl', False): smtp = smtplib.SMTP_SSL(server['server'], server.get('port', 465) or 465) else: smtp = smtplib.SMTP(server['server'], server.get('port', 25) or 25) if server.get('username', None): smtp.login(server['username'], server.get('password', None)) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send_mail(send_from, send_to, subject, text, files=[], server="localhost"): assert type(send_to) == list assert type(files) == list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload(open(f, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) #Set Email smtp parameters smtp = smtplib.SMTP('smtp.gmail.com:587') smtp.starttls() smtp.login('*****@*****.**', 'pythonheat1') smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send_mail(send_from, send_to, subject, text, files=[], html=None, server="localhost"): assert type(send_to)==list assert type(files)==list if html: msg = MIMEMultipart('alternative') textbody = dehtml(text) part1 = MIMEText(textbody, 'plain') part2 = MIMEText(text, 'html') msg.attach(part1) msg.attach(part2) else: msg = MIMEMultipart() msg.attach( MIMEText(text) ) msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject for f in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send_mail(send_from, send_to, subject, text, files=[], server="localhost",password=None,user=None): if type(send_to) in types.StringTypes: send_to = [send_to] if files is None: files = [] assert type(files)==list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for f in files: part = MIMEBase('application', "octet-stream") content = open(f, 'rb').read() part.set_payload(content) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server) if password: if not user: user = msg['From'] smtp.starttls() smtp.login(user,password) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send(recipients, subject, body, files=[]): if config.PASSWORD == None: raise Exception( "You must set GMAILPASSW with the '%s' password. You can change the user by setting GMAILUSER" % SENDER) smtp = smtplib.SMTP(config.SMTPSERVER, config.SMTPPORT) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(config.SENDER, config.PASSWORD) mail = MIMEMultipart() mail['Subject'] = subject mail['Date'] = formatdate(localtime=True) mail['From'] = config.SENDER mail['To'] = COMMASPACE.join(recipients) mail.preamble = 'This is a multi-part message in MIME format.' mail.attach(MIMEText(body)) for f in files: part = MIMEText(open(f, "r").read()) Encoders.encode_quopri(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) mail.attach(part) smtp.sendmail(config.SENDER, recipients, mail.as_string()) smtp.quit() print("Sent to ") print(recipients)
def send_email(self, send_from, send_to, subject, text, server, files=[]): import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders assert type(send_to) == list assert type(files) == list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload(open(f, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send_mail(send_to, subject, text, files=[]): """ send_mail('*****@*****.**', '附件邮件测试', '附件邮件正文测试', '/root/robot.txt') """ send_to = [send_to] if isinstance(send_to, (str, unicode)) else send_to files = [files] if isinstance(files, (str, unicode)) else files msg = MIMEMultipart() msg['From'] = '*****@*****.**' msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload(open(f, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP() smtp.connect('smtp.exmail.qq.com', '25') smtp.login('*****@*****.**', 'scut2092') smtp.sendmail('*****@*****.**', send_to, msg.as_string()) smtp.close()
def send_mail(send_to, subject, text, files=[], server='localhost', username=None, password=None): send_from = '*****@*****.**' msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) for f in files: part = MIMEBase('application', 'octet-stream') part.set_payload(open(f, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % basename(f)) msg.attach(part) smtp = SMTP(server) if username is not None: smtp.login(str(username), str(password)) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send_message_html(self, to_email_id, subject, body_html, files=[]): ''' This must be removed ''' msg = MIMEMultipart() msg['From'] = self.email msg['To'] = COMMASPACE.join([to_email_id]) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject text = body_html.encode("utf-8") text = MIMEText(text, 'html', "utf-8") msg.attach(text) msg.add_header('Message-ID', generate_message_id(self.email)) for file in files: part = MIMEBase('application', "octet-stream") part.set_payload(open(file, "rb").read()) Encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(part) self.session.sendmail(self.email, to_email_id, msg.as_string())
def sendMailWithAttachments(to, subject, text, files=[]): assert type(to) == list assert type(files) == list msg = MIMEMultipart() msg['From'] = USERNAME msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) for file in files: part = MIMEBase('application', "octet-stream") part.set_payload(open(file, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(part) server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo_or_helo_if_needed() server.starttls() server.ehlo_or_helo_if_needed() server.login(USERNAME, PASSWORD) server.sendmail(USERNAME, to, msg.as_string()) server.quit()
def enviaEmail(remetente, destinatarios, assunto, dados, anexos=[]): assert type(destinatarios) == type([]) msg = MIMEMultipart() msg["From"] = remetente msg["To"] = COMMASPACE.join(destinatarios) msg["Subject"] = assunto msg.attach(MIMEText(dados)) for anexo in anexos: part = MIMEBase("application", "octet-stream") part.set_payload(anexo.read()) Encoders.encode_base64(part) part.add_header("Content-Disposition", 'attachment; filename="%s"' % os.path.basename(anexo.name)) msg.attach(part) if SMTP["PORT"] == 465: server = smtplib.SMTP_SSL(SMTP["SERVER"], SMTP["PORT"]) else: server = smtplib.SMTP(SMTP["SERVER"], SMTP["PORT"]) if SMTP.get("TLS", None): server.starttls() if SMTP["USER"] and SMTP["PASS"]: server.login(SMTP["USER"], SMTP["PASS"]) server.sendmail(remetente, destinatarios, msg.as_string()) server.close()
def send_mail(send_from, send_to, subject, text, files=[]): assert isinstance(send_to, list) assert isinstance(files, list) msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP('smtp.gmail.com', 587) smtp.ehlo() smtp.starttls() smtp.login("*****@*****.**", pw) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.quit()
def send_mail(send_from, send_to, subject, text, files=[]): assert isinstance(send_to, list) assert isinstance(files, list) msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload(open(f, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP('smtp.gmail.com', 587) smtp.ehlo() smtp.starttls() smtp.login("*****@*****.**", pw) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.quit()
def send_mail(sender, recipient, subject, body, file=None, filename=None): ''' Funktion zum versenden von Emails recipient muss als Liste übergeben werden body sollte einen formatierter String sein ''' msg = MIMEMultipart() msg["From"] = sender msg["To"] = COMMASPACE.join(recipient) # List to String msg["Subject"] = email.Header.Header(subject, 'UTF-8') msg.attach(MIMEText(body.encode('utf-8'), 'plain', 'utf-8')) # Attachment von Dateien if file is not None: fn = file.split("/") fn = fn[-1] part = MIMEBase('application', 'octet-stream') part.set_payload(open(file, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename=%s' % filename or fn) msg.attach(part) mailer = zope.component.getUtility(zope.sendmail.interfaces.IMailDelivery, name=u'uvcsite.maildelivery') mailer.send(sender, recipient, msg.as_string())
def send_mail(send_from, send_to, subject, text, files=[], server="localhost"): assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) #Set Email smtp parameters smtp = smtplib.SMTP('smtp.gmail.com:587') smtp.starttls() smtp.login('*****@*****.**', 'pythonheat1') smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def restartAndSendEmailAlert(restart, subject, msg, alertops = False): if restart: restart_msg = commands.getoutput("/etc/init.d/smartproxyd restart") # append restart msg: msg += "\n\nRestarting smartproxyd: %s\n\n" % restart_msg sender = 'root@%s' % socket.gethostname() receivers = EMAIL_NOTIFICATION_LIST # add ops to the receivers if necessary: if alertops: receivers.append(OPS_NOTIFICATION) server= smtplib.SMTP('localhost') # if we restarted, wait for a few seconds before appending the log, so that smartproxyd has time to start: if restart: time.sleep(5) # append the last 30 lines of the smartproxyd.log to the msg: log = commands.getoutput("tail -n 30 /var/log/lounge/smartproxyd.log") msg += "\n\nsmartproxyd.log (last 30 lines):\n" + log server.sendmail(sender, receivers, ('From: %s\n' + 'To: %s\n' + 'Subject: %s: %s\n\n' + '%s') % (sender, COMMASPACE.join(receivers), socket.gethostname(), subject, msg)) server.quit()
def send_mail(to, fro, subject, text, files=[],server="localhost"): assert type(to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = fro msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for file in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(file,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(part) # now deal with connecting to the server server = current_app.config.get("MAIL_SERVER", "localhost") server_port = current_app.config.get("MAIL_PORT", 25) smtp_user = current_app.config.get("MAIL_USERNAME") smtp_pass = current_app.config.get("MAIL_PASSWORD") smtp = smtplib.SMTP() # just doing SMTP(server, server_port) does not work with Mailtrap # but doing .connect explicitly afterwards works both with Mailtrap and with Mandrill smtp.connect(server, server_port) if smtp_user is not None: smtp.login(smtp_user, smtp_pass) smtp.sendmail(fro, to, msg.as_string() ) smtp.close()
def send_mail(send_from, send_to, subject, text, files=[], server='smtp.typa.ru'): from smtplib import SMTP from os import path 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 from email.header import Header assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = Header(send_from.decode("utf-8")).encode() msg['To'] = Header(COMMASPACE.join(send_to).decode("utf-8")).encode() msg['Date'] = formatdate(localtime=True) msg['Subject'] = Header(subject.decode("utf-8")).encode() msg.attach( MIMEText(text,'plain','UTF-8') ) 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"' % path.basename(f)) msg.attach(part) smtp = SMTP(server, 25) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send_mail(send_from, send_to, subject, text, files=[], server="localhost", port=25): assert type(send_to)==list assert type(files)==list # We must choose the body charset manually for body_charset in 'US-ASCII', 'ISO-8859-1', 'UTF-8': try: text.encode(body_charset) except UnicodeError: pass else: break msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text.encode(body_charset), 'plain', body_charset) ) 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(host=server, port=port, local_hostname='cked.es') smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send_mail(send_from, send_to, subject, text, files=[], server="localhost"): import smtplib import os from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import COMMASPACE, formatdate from email import Encoders assert type(send_to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload( open(f,"rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send_samples_missing_clinical_data_report(study_id, clinical_filename): """ Send email reporting ARCHER-linked cases that are missing from the clinical data. """ # construct message body msg = MIMEMultipart() message = "** NOTE - Although these samples are linked to ARCHER fusion events, they were not " message += "added to the fusions data file since they are missing from the clinical data file. " message += "These samples may need to be requeued if they are not already in the DMP queue for " message += "the next CVR data fetch. If a sample fails to requeue and/or does not appear in the " message += "CVR JSON from the following CVR fetch then please alert the DMP team to address any issues.\n\n" message += "Found " + str(len(SAMPLES_MISSING_CLINICAL_DATA)) + " ARCHER-linked sample(s) missing clinical data in: " + clinical_filename + "\n" for sample_id in SAMPLES_MISSING_CLINICAL_DATA: message += "\n\t" + sample_id email_body = MIMEText(message, "plain") msg.attach(email_body) assert type(MESSAGE_RECIPIENTS)==list msg['Subject'] = "ARCHER-linked cases missing clinical data: " + study_id msg['From'] = MESSAGE_SENDER msg['To'] = COMMASPACE.join(MESSAGE_RECIPIENTS) msg['Date'] = formatdate(localtime=True) print >> OUTPUT_FILE, "Sending email..." # send email s = smtplib.SMTP(SMTP_SERVER) s.sendmail(MESSAGE_SENDER, MESSAGE_RECIPIENTS, msg.as_string()) s.quit()
def encode_rfc2822_address_header(header_text): """If ``header_text`` contains non-ASCII characters, attempts to locate patterns of the form ``"Name" <address@domain>`` and replace the ``"Name"`` portion by the RFC2047-encoded version, preserving the address part untouched. """ header_text_utf8 = tools.ustr(header_text).encode('utf-8') header_text_ascii = try_coerce_ascii(header_text_utf8) if header_text_ascii: return header_text_ascii # non-ASCII characters are present, attempt to # replace all "Name" patterns with the RFC2047- # encoded version def replace(match_obj): name, email = match_obj.group(1), match_obj.group(2) name_encoded = str(Header(name, 'utf-8')) return "%s <%s>" % (name_encoded, email) header_text_utf8 = name_with_email_pattern.sub(replace, header_text_utf8) # try again after encoding header_text_ascii = try_coerce_ascii(header_text_utf8) if header_text_ascii: return header_text_ascii # fallback to extracting pure addresses only, which could # still cause a failure downstream if the actual addresses # contain non-ASCII characters return COMMASPACE.join(extract_rfc2822_addresses(header_text_utf8))
def _sendMail(toUser, fromUser, subject, text, files=[], rd='plain'): #smtpServer = os.environ['SMTP'] if os.environ.has_key('SMTP') else 'localhost' smtpServer = os.environ['SMTP'] if os.environ.has_key('SMTP') else None #smtpServer = 'rydersendmailrelay.ryder.com' if smtpServer is None: log.error("Need to set env SMTP") return 3 msg = MIMEMultipart() msg['From'] = fromUser #msg['To'] = toUser msg['To'] = COMMASPACE.join(toUser) # To user needs to be a list ! msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject print " MSG TO ", msg['To'] #msg.attach( MIMEText(text,'html') ) msg.attach(MIMEText(text, rd)) 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(smtpServer) smtp.sendmail(fromUser, toUser, msg.as_string()) smtp.quit( ) # Invokes smtp.close. This call should return : (221, '2.0.0 sscldinf.ryder.com closing connection') return SUCCESS
def sendEmail(to, subject, text, files=[]): assert type(to)==list assert type(files)==list msg = MIMEMultipart() msg['From'] = USERNAME msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for file in files: part = MIMEBase('application', "octet-stream") part.set_payload(open(file, "rb").read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"'% os.path.basename(file)) msg.attach(part) server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo_or_helo_if_needed() server.starttls() server.ehlo_or_helo_if_needed() server.login(USERNAME,PASSWORD) server.sendmail(USERNAME, MAILTO, msg.as_string()) server.quit()
def send_email(subject, body, attachement=None): with open('credentials.txt') as f: credentials = [x.strip().split(':') for x in f.readlines()] gmail_user = credentials[0][1] gmail_pwd = credentials[0][2] recipient = credentials[1][1] msg = MIMEMultipart() msg['From'] = gmail_user msg['To'] = COMMASPACE.join(recipient) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(body)) if not attachement is None: part = MIMEBase('application', "octet-stream") part.set_payload(open(attachement, "rb").read()) Encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attachement)) msg.attach(part) try: server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo_or_helo_if_needed() server.starttls() server.ehlo_or_helo_if_needed() server.login(gmail_user, gmail_pwd) server.sendmail(gmail_user, recipient, msg.as_string()) server.close() print 'successfully sent the mail' except Exception as e: print e print "failed to send mail"
def send_mail(files, send_from='*****@*****.**', send_to=['*****@*****.**'], subject='El PDF de hoy!', server='localhost'): assert type(send_to) == list assert type(files) == list msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject html = MIMEText( 'Se subió el siguiente PDF, corrobore que sea la edición de hoy!', 'html') msg.attach(html) 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"' % path.basename(f)) msg.attach(part) smtp = smtplib.SMTP(server, port=settings.EMAIL_PORT) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send_email_with_files(to, fro, subject, text, files=[], server="localhost"): assert type(to) == list assert type(files) == list msg = MIMEMultipart() msg['From'] = fro msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) for file in files: part = MIMEBase('application', "octet-stream") part.set_payload(open(file, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(part) smtp = smtplib.SMTP(server) smtp.sendmail(fro, to, msg.as_string()) smtp.close()
def send_report(to, subj, files): # Create a text/plain message email_body = [] email_body.append("RSEM / deseq2 pipeline results") email_body.append("Please direct any questions to [email protected]") # msg object msg = MIMEMultipart() # header stuff # no one else cares but me! root = "*****@*****.**" msg['Subject'] = subj msg['From'] = root msg['To'] = COMMASPACE.join(to) msg.attach(MIMEText("\n".join(email_body))) # attatch the files 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) # Send the message via our own SMTP server, but don't include the # envelope header. s = smtplib.SMTP('localhost') s.sendmail(root, to, msg.as_string()) s.quit()