def send_notification(self, recipients, subject, body, attachments=None, bcc=[]): plain_part = MIMEText(body) if attachments: msg = MIMEMultipart() msg.preamble = 'This is a multi-part message in MIME format.' msg.epilogue = '' msg.attach(plain_part) for path in attachments: msg.attach(self.getAttachment(path)) else: msg = plain_part msg['From'] = self.from_ msg['Subject'] = subject msg['To'] = ','.join(recipients) if type(bcc) in [str, unicode]: bcc = [bcc] try: server = smtplib.SMTP(self.host, self.port) server.ehlo() server.starttls() server.ehlo() server.login(self.username, self.password) server.sendmail(self.from_, recipients + bcc, msg.as_string()) server.quit() except smtplib.SMTPException, e: raise EmailNotifierException(e.message)
def mimemelding(self): m = MIMEMultipart() m['Subject'] = Header(self.tittel, self.charset) n = self.ordre.firma.firmanavn.replace(';', ' ').replace(',',' ') m['From'] = '"%s" <%s>' % (Header(n, self.charset), self.fra) #m['To'] = '"%s" <%s>' % (Header(self.ordre.kunde.navn, self.charset), self.til) m['To'] = self.til #'"%s" <%s>' % (Header(self.ordre.kunde.navn, self.charset), self.til) m.preamble = 'You will not see this in a MIME-aware mail reader.\n' # To guarantee the message ends with a newline m.epilogue = '' # Legg til tekstlig informasjon t = MIMEText(self.tekst.encode(self.charset), 'plain', self.charset) m.attach(t) # Legg til fakturaen b = MIMEBase('application', 'x-pdf') _filename=Header('%s-%i.pdf' % (self.ordre.firma.firmanavn, self.ordre.ID), self.charset) b.add_header('Content-Disposition', 'attachment', filename=_filename.encode()) # legg til filnavn m.attach(b) fp = open(self.pdfFilnavn, 'rb') b.set_payload(fp.read()) # les inn fakturaen fp.close() encoders.encode_base64(b) #base64 encode subpart # Legg til vedlegg for filnavn, vedlegg in self.vedlegg: v = MIMEBase('application', 'octet-stream') _filename=Header(filnavn, self.charset) v.add_header('Content-Disposition', 'attachment', filename=_filename.encode()) # legg til filnavn m.attach(v) v.set_payload(vedlegg) encoders.encode_base64(v) #base64 encode subpart return m
def copy_mime_root(msg, strip_content=True): """Make a copy of the non_payload root mime part of msg and change content type to multipart/alternativ. By default drop old Content- headers. """ msg_new = MIMEMultipart() # drop default keys for k in msg_new.keys(): del msg_new[k] # make copy of old header for k, v in msg.items(): if strip_content and k.startswith('Content-'): continue msg_new[k] = v if msg.get_unixfrom(): msg_new.set_unixfrom(msg.get_unixfrom()) if msg.preamble: msg_new.preamble = msg.preamble else: msg_new.preamble = "This is a multi-part message in MIME format...\n" if msg.epilogue: msg_new.epilogue = msg.epilogue # set msg_new type msg_new.set_type('multipart/alternative') return msg_new
def send_email(user, pswd, from_, to_, subject, text): #import smtplib gmail_user = user gmail_pwd = pswd FROM = from_ TO = to_ #must be a list SUBJECT = subject TEXT = text # Prepare actual message message = """\From: %s\nTo: %s\nSubject: %s\n\n%s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) msg = MIMEMultipart() msg.preamble = 'This is a multi-part message in MIME format.\n' msg.epilogue = '' body = MIMEMultipart('alternative') body.attach(MIMEText(txt)) body.attach(MIMEText(text, 'html')) msg.attach(body) msg.add_header('From', from_) msg.add_header('To', to_) #msg.add_header('Cc', ccaddy) #doesn't work apparently #msg.add_header('Bcc', bccaddy) #doesn't work apparently msg.add_header('Subject', subject) msg.add_header('Reply-To', from_) try: #server = smtplib.SMTP(SERVER) server = smtplib.SMTP('smtp.gmail.com', 587) #SMTP("localhost", 50) #or port 465 doesn't seem to work! server.set_debuglevel(True) server.ehlo() server.starttls() server.login(gmail_user, gmail_pwd) server.sendmail(FROM, TO, msg.as_string()) server.quit() #server.close() print 'successfully sent the mail' except: print "failed to send mail" try: #server = smtplib.SMTP(SERVER) 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(FROM, TO, message) #server.quit() server.close() print 'successfully sent the mail' except: print "failed to send mail"
def sendFile(to_address, title, message, file_path): import smtplib import os, getpass, codecs import codecs import mimetypes from email.mime.multipart import MIMEMultipart from email import encoders from email.message import Message from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.text import MIMEText thing = ("*****@*****.**","oebgurerlr123", "*****@*****.**", "fzgc.tznvy.pbz:587") way = str(codecs.decode("ebg_13","rot_13")) essential_data = [str(codecs.decode(x,way)) for x in thing] gate = smtplib.SMTP(essential_data[3]) gate.ehlo() gate.starttls() gate.login(essential_data[0],essential_data[1]) msg = MIMEMultipart('mixed') msg["From"] = essential_data[0] msg["To"] = to_address msg["Subject"] = title msg.preamble = message msg.epilogue = message msg.attach(MIMEText(message,"html")) ctype, encoding = mimetypes.guess_type(file_path) if ctype is None or encoding is not None: ctype = "application/octet-stream" maintype, subtype = ctype.split("/", 1) if maintype == "text": fp = open(file_path) # Note: we should handle calculating the charset attachment = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == "image": fp = open(file_path, "rb") attachment = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == "audio": fp = open(file_path, "rb") attachment = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(file_path, "rb") attachment = MIMEBase(maintype, subtype) attachment.set_payload(fp.read()) fp.close() encoders.encode_base64(attachment) attachment.add_header("Content-Disposition", "attachment", filename=os.path.basename(file_path)) msg.attach(attachment) gate.sendmail(essential_data[0], to_address, msg.as_string()) gate.quit()
def execute(self, config, nl): self.config = config sender = self.readConfigValue('sender') recipient = self.readConfigValue('recipient') url = self.readConfigValue('url') msg = MIMEMultipart("alternative") msg['Subject'] = nl.generateSubject() msg['From'] = sender msg['To'] = recipient msg.preamble = nl.generatePlainText() msg.epilogue = '' plain = MIMEText(str( nl.generatePlainText() ), "plain") html = MIMEText(str( nl.generateHTML() ), "html") msg.attach(plain) msg.attach(html) s = smtplib.SMTP() s.connect() s.sendmail(sender, recipient, msg.as_string()) s.close() print "Posted to the <a href='" + url + "'>Mailing List</a><br />"
def send_email(user, pswd, from_, to_, subject, text): msg = MIMEMultipart() msg.preamble = 'This is a multi-part message in MIME format.\n' msg.epilogue = '' body = MIMEMultipart('alternative') body.attach(MIMEText("Some results")) body.attach(MIMEText(text, 'html')) msg.attach(body) msg.add_header('From', from_) msg.add_header('To', to_) #msg.add_header('Cc', ccaddy) #doesn't work apparently #msg.add_header('Bcc', bccaddy) #doesn't work apparently msg.add_header('Subject', subject) msg.add_header('Reply-To', from_) #msg.add_header('Content-Type', "text/html; charset=utf-8") try: #server = smtplib.SMTP(SERVER) server = smtplib.SMTP( 'smtp.gmail.com', 587) #SMTP("localhost", 50) #or port 465 doesn't seem to work! server.set_debuglevel(True) server.ehlo() server.starttls() server.login(user, pswd) server.sendmail(from_, to_, msg.as_string()) server.quit() #server.close() print 'successfully sent the mail' except: print "failed to send mail"
def as_mime(self): from email.mime.multipart import MIMEMultipart message = MIMEMultipart() message.preamble = 'This is a multi-part message in MIME format. It was automatically converted from a DIME message.\n' message.epilogue = '' for record in self.records: message.attach(record.as_mime()) return message
def get_data(): mails = [] # Create connection to MySQL db try: con = connections.connect_MySQLdb() except Exception as e: logger.error(str(e)) raise Exception logger.info('Successful connection to MySQLdb') cur = con.cursor() # Get value sender from database try: cur.execute("SELECT mb_value FROM `mb_properties` WHERE mb_field='Sender'") sender = cur.fetchone()[0] cur.execute("SELECT mb_value FROM `mb_properties` WHERE mb_field='Attempts'") attempt = cur.fetchone()[0] # Get all necessary information from database cur.execute(""" SELECT mb_mail_buffer.mail_id, p4s_srk_perforce_users.user_email, mb_mail_buffer.mail_subject, mb_mail_buffer.mail_body, mb_mail_buffer.sender_marker FROM mb_mail_buffer, p4s_srk_perforce_users WHERE ( mb_mail_buffer.destination_id = p4s_srk_perforce_users.user_id AND mb_mail_buffer.attempt < %s AND mb_mail_buffer.date_send is NULL) """ % attempt) rows = cur.fetchall() except Exception as e: logger.error(str(e)) raise Exception logger.info('Information from database is obtained') # Create email from obtained information for row in rows: msg = MIMEMultipart('related') msg['Subject'] = make_header([(row[2], 'UTF-8')]) msg['Date'] = formatdate(localtime=True) msg['Organization'] = make_header([('SAMSUNG', 'UTF-8')]) msg['X-Mailer'] = make_header([('MailSender', 'UTF-8')]) msg['Message-ID'] = make_msgid() msg['From'] = make_header([(sender, 'UTF-8')]) if ';' in row[1]: msg['To'] = make_header([(row[1].split('; '), 'UTF-8')]) else: msg['To'] = make_header([(row[1], 'UTF-8')]) msg.preamble = "This is a multi-part message in MIME format." msg.epilogue = "End of message" partbody = MIMEText(row[3], '', 'UTF-8') msg.attach(partbody) # Create a list with tags mail_id, email object and sender_marker mails.append((row[0], msg)) cur.close() con.close() if mails: logger.info('Created %s letters' % len(mails)) return mails
def send_email(subject, msg_body, recipient): #sender information addr = '*****@*****.**' username = '******' password = '******' #email information fromaddr = '<' + addr + '>' toaddr = '<' + recipient + '>' replyto = fromaddr msgsubject = subject sendtime = time.strftime("%b %d %Y at %H:%M:%S", time.localtime()) htmlmsgtext = msg_body + '</br></br></br>' + '<br>' + sendtime try: msgtext = htmlmsgtext.replace('<b>', '').replace('</b>', '').replace( '<br>', "\r").replace('</br>', "\r").replace('<br/>', "\r").replace('</a>', '') msgtext = re.sub('<.*?>', '', msgtext) msg = MIMEMultipart() msg.preamble = 'This is a multi-part message in MIME format.\n' msg.epilogue = '' body = MIMEMultipart('alternative') body.attach(MIMEText(msgtext)) body.attach(MIMEText(htmlmsgtext, 'html')) msg.attach(body) msg.add_header('From', fromaddr) msg.add_header('To', toaddr) msg.add_header('Subject', msgsubject) msg.add_header('Reply-To', replyto) server = smtplib.SMTP('smtp.gmail.com:587') server.set_debuglevel( False ) #commenting this out, changing to False will make the script give NO output at all upon successful completion server.starttls() server.login(username, password) server.sendmail(msg['From'], [msg['To']], msg.as_string()) server.quit() except: print('Email NOT sent to %s successfully. %s ERR: %s %s %s ', str(toaddr), 'tete', str(sys.exc_info()[0]), str(sys.exc_info()[1]), str(sys.exc_info()[2])) #test purpose #if __name__ == '__main__': # subject = 'Email Subject' # msg_body = 'This is a test e-mail' # recipient = '*****@*****.**' # send_email(subject, msg_body, recipient)
def SendEmail(toaddr,msgsubject,htmlmsgtext): print ("debug : send email") host = config['SMTPSERVER'] # "smtpmtl.itops.ad.ypg.com" port = config['SMTPPORT'] # 25 fromaddr = config['FROMADDR'] # "*****@*****.**" replyto = config['REPLYTO'] # "*****@*****.**" # Mail preparation class MLStripper(HTMLParser): def __init__(self): self.reset() self.fed = [] def handle_data(self, d): self.fed.append(d) def get_data(self): return ''.join(self.fed) def strip_tags(html): s = MLStripper() s.feed(html) return s.get_data() # Make text version from HTML - First convert tags that produce a line break to carriage returns msgtext = htmlmsgtext.replace('</br>',"r").replace('<br />',"r").replace('</p>',"r") # Then strip all the other tags out msgtext = strip_tags(msgtext) #msgtext.encode('utf-8') # necessary mimey stuff msg = MIMEMultipart() msg.preamble = 'This is a multi-part message in MIME format.n' msg.epilogue = '' body = MIMEMultipart('alternative') body.attach(MIMEText(msgtext.encode('utf-8'), 'plain', 'utf-8')) body.attach(MIMEText(htmlmsgtext.encode('utf-8'), 'html')) msg.attach(body) msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = msgsubject msg['Reply-To'] = replyto print ("Sending " + msgsubject + " to : " + toaddr) # The actual email sendy bits try : server = smtplib.SMTP(host, port) server.set_debuglevel(False) server.sendmail(fromaddr, toaddr, msg.as_string()) except smtplib.SMTPException as err: error = str(err.message) test = err. print ("smtplib error : " + error) else: print 'Email sent.' server.quit() # bye bye
def sendMail(subject, body, attachments=[], status=False, from_mail='*****@*****.**', to_mail=['*****@*****.**'], smtp_host=''): if attachments: msg = MIMEMultipart() else: msg = Message() msg['Subject'] = subject msg['From'] = from_mail msg['To'] = ', '.join(to_mail) msg['X-ERP5-Tests'] = 'ERP5' if status: msg['X-ERP5-Tests-Status'] = 'OK' # Guarantees the message ends in a newline msg.preamble = subject msg.epilogue = '' if attachments: mime_text = MIMEText(body) mime_text.add_header('Content-Disposition', 'attachment', filename='body') msg.attach(mime_text) html_re = re.compile('<html>', re.I) for item in attachments: mime_text = MIMEText(item) if html_re.match(item): mime_text.set_type('text/html') mime_text.add_header('Content-Disposition', 'attachment', filename='attachment.html') else: mime_text.add_header('Content-Disposition', 'attachment', filename='attachment.txt') msg.attach(mime_text) else: msg.set_payload(body) # Send the email via SMTP server. if smtp_host: s = smtplib.SMTP(smtp_host) else: s = smtplib.SMTP() s.connect() s.sendmail(from_mail, to_mail, msg.as_string()) s.close()
def __createMultipartMail(self): """ Private method to create a multipart mail message. @return string containing the mail message """ mpPreamble = ("This is a MIME-encoded message with attachments. " "If you see this message, your mail client is not " "capable of displaying the attachments.") msgtext = "{0}\r\n----\r\n{1}----\r\n{2}----\r\n{3}".format( self.message.toPlainText(), Utilities.generateVersionInfo("\r\n"), Utilities.generatePluginsVersionInfo("\r\n"), Utilities.generateDistroInfo("\r\n")) # first part of multipart mail explains format msg = MIMEMultipart() msg['From'] = Preferences.getUser("Email") msg['To'] = self.__toAddress subject = '[eric6] {0}'.format(self.subject.text()) msg['Subject'] = self.__encodedHeader(subject) msg.preamble = mpPreamble msg.epilogue = '' # second part is intended to be read att = self.__encodedText(msgtext) msg.attach(att) # next parts contain the attachments for index in range(self.attachments.topLevelItemCount()): itm = self.attachments.topLevelItem(index) maintype, subtype = itm.text(1).split('/', 1) fname = itm.text(0) name = os.path.basename(fname) if maintype == 'text': txt = open(fname, 'r', encoding="utf-8").read() try: txt.encode("us-ascii") att = MIMEText(txt, _subtype=subtype) except UnicodeEncodeError: att = MIMEText( txt.encode("utf-8"), _subtype=subtype, _charset="utf-8") elif maintype == 'image': att = MIMEImage(open(fname, 'rb').read(), _subtype=subtype) elif maintype == 'audio': att = MIMEAudio(open(fname, 'rb').read(), _subtype=subtype) else: att = MIMEApplication(open(fname, 'rb').read()) att.add_header('Content-Disposition', 'attachment', filename=name) msg.attach(att) return msg.as_string()
def __createMultipartMail(self): """ Private method to create a multipart mail message. @return prepared mail message @rtype email.mime.text.MIMEMultipart """ mpPreamble = ("This is a MIME-encoded message with attachments. " "If you see this message, your mail client is not " "capable of displaying the attachments.") msgtext = "{0}\r\n----\r\n{1}----\r\n{2}----\r\n{3}".format( self.message.toPlainText(), Utilities.generateVersionInfo("\r\n"), Utilities.generatePluginsVersionInfo("\r\n"), Utilities.generateDistroInfo("\r\n")) # first part of multipart mail explains format msg = MIMEMultipart() msg['From'] = Preferences.getUser("Email") msg['To'] = self.__toAddress subject = '[eric6] {0}'.format(self.subject.text()) msg['Subject'] = self.__encodedHeader(subject) msg.preamble = mpPreamble msg.epilogue = '' # second part is intended to be read att = self.__encodedText(msgtext) msg.attach(att) # next parts contain the attachments for index in range(self.attachments.topLevelItemCount()): itm = self.attachments.topLevelItem(index) maintype, subtype = itm.text(1).split('/', 1) fname = itm.text(0) name = os.path.basename(fname) if maintype == 'text': txt = open(fname, 'r', encoding="utf-8").read() try: txt.encode("us-ascii") att = MIMEText(txt, _subtype=subtype) except UnicodeEncodeError: att = MIMEText(txt.encode("utf-8"), _subtype=subtype, _charset="utf-8") elif maintype == 'image': att = MIMEImage(open(fname, 'rb').read(), _subtype=subtype) elif maintype == 'audio': att = MIMEAudio(open(fname, 'rb').read(), _subtype=subtype) else: att = MIMEApplication(open(fname, 'rb').read()) att.add_header('Content-Disposition', 'attachment', filename=name) msg.attach(att) return msg
def as_mime(self): from email.mime.multipart import MIMEMultipart message = MIMEMultipart() message.preamble = ( "This is a multi-part message in MIME format. It was automatically converted from a DIME message.\n" ) message.epilogue = "" for record in self.records: message.attach(record.as_mime()) return message
def send_to_admin(notsendmsg): try: con = connections.connect_MySQLdb() cur = con.cursor() cur.execute("SELECT mb_value FROM `mb_properties` WHERE mb_field='Sender'") sender = cur.fetchone()[0] # Get SMTP server address and port from database cur.execute("SELECT mb_value FROM `mb_properties` WHERE mb_field = 'SMTP server'") server = cur.fetchone()[0] cur.execute("SELECT mb_value FROM `mb_properties` WHERE mb_field = 'SMTP port'") port = int(cur.fetchone()[0]) # Get admin email address from database cur.execute("SELECT mb_value FROM `mb_properties` WHERE mb_field='Admin email'") admin = cur.fetchone()[0] cur.close() con.close() except Exception as e: logger.error(str(e)) raise Exception # Create connection to SMTP server try: # ransfer function of the parameter 2 server, port serversmtp = connections.connect_SMTP() except Exception as e: logger.error(str(e)) raise Exception logger.info('Connected\n') serversmtp.noop() for msg in notsendmsg: # Create email fo admin email = MIMEMultipart('related') email['Subject'] = make_header([('SRK DPIportal [Mail Sender] Impossible send email!', 'UTF-8')]) email['Date'] = formatdate(localtime=True) email['Organization'] = make_header([('SAMSUNG', 'UTF-8')]) email['X-Mailer'] = make_header([('MailSender', 'UTF-8')]) email['Message-ID'] = make_msgid() email['From'] = make_header([(sender, 'UTF-8')]) email['To'] = make_header([(admin, 'UTF-8')]) email.preamble = "This is a multi-part message in MIME format." email.epilogue = "End of message" partbody = MIMEText('Impossible send email to ' + msg[0] + '\n' + 'Error:\n' + msg[1], '', 'UTF-8') email.attach(partbody) try: serversmtp.sendmail(str(email['From']), str(email['To']).split('; '), email.as_string()) logger.info('Mail was send to %s' % admin) except Exception as e: logger.error(e) logger.info('Impossible send email to admin %s' % admin) serversmtp.quit()
def send_email(subject, msg_body, recipient): #sender information addr= '*****@*****.**' username = '******' password = '******' #email information fromaddr = '<'+addr+'>' toaddr = '<'+recipient+'>' replyto = fromaddr msgsubject = subject sendtime = time.strftime("%b %d %Y at %H:%M:%S",time.localtime()) htmlmsgtext = msg_body +'</br></br></br>' + '<br>' + sendtime try: msgtext = htmlmsgtext.replace('<b>','').replace('</b>','').replace('<br>',"\r").replace('</br>',"\r").replace('<br/>',"\r").replace('</a>','') msgtext = re.sub('<.*?>','',msgtext) msg = MIMEMultipart() msg.preamble = 'This is a multi-part message in MIME format.\n' msg.epilogue = '' body = MIMEMultipart('alternative') body.attach(MIMEText(msgtext)) body.attach(MIMEText(htmlmsgtext, 'html')) msg.attach(body) msg.add_header('From', fromaddr) msg.add_header('To', toaddr) msg.add_header('Subject', msgsubject) msg.add_header('Reply-To', replyto) server = smtplib.SMTP('smtp.gmail.com:587') server.set_debuglevel(False) #commenting this out, changing to False will make the script give NO output at all upon successful completion server.starttls() server.login(username,password) server.sendmail(msg['From'], [msg['To']], msg.as_string()) server.quit() except: print ('Email NOT sent to %s successfully. %s ERR: %s %s %s ', str(toaddr), 'tete', str(sys.exc_info()[0]), str(sys.exc_info()[1]), str(sys.exc_info()[2]) ) #test purpose #if __name__ == '__main__': # subject = 'Email Subject' # msg_body = 'This is a test e-mail' # recipient = '*****@*****.**' # send_email(subject, msg_body, recipient)
def sendMail(subject, body, attachments = [], status = False, from_mail = '*****@*****.**', to_mail = [ '*****@*****.**' ], smtp_host = ''): if attachments: msg = MIMEMultipart() else: msg = Message() msg['Subject'] = subject msg['From'] = from_mail msg['To'] = ', '.join(to_mail) msg['X-ERP5-Tests'] = 'ERP5' if status: msg['X-ERP5-Tests-Status'] = 'OK' # Guarantees the message ends in a newline msg.preamble = subject msg.epilogue = '' if attachments: mime_text = MIMEText(body) mime_text.add_header('Content-Disposition', 'attachment', filename='body') msg.attach(mime_text) html_re = re.compile('<html>', re.I) for item in attachments: mime_text = MIMEText(item) if html_re.match(item): mime_text.set_type('text/html') mime_text.add_header('Content-Disposition', 'attachment', filename='attachment.html') else: mime_text.add_header('Content-Disposition', 'attachment', filename='attachment.txt') msg.attach(mime_text) else: msg.set_payload(body) # Send the email via SMTP server. if smtp_host: s = smtplib.SMTP(smtp_host) else: s = smtplib.SMTP() s.connect() s.sendmail(from_mail, to_mail, msg.as_string()) s.close()
def sendEmail(htmlmessage, toaddr): try: # necessary mimey stuff msg = MIMEMultipart() msg.preamble = 'This is a multi-part message in MIME format.\n' msg.epilogue = '' body = MIMEMultipart('alternative') #body.attach(MIMEText(msgtext)) body.attach(MIMEText(htmlmessage, 'html')) msg.attach(body) if 'attachments' in globals() and len('attachments') > 0: # are there attachments? for filename in attachments: f = filename 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) msg.add_header('From', fromaddr) msg.add_header('To', toaddr) msg.add_header('Subject', msgsubject) msg.add_header('Reply-To', replyto) # The actual email sendy bits server = smtplib.SMTP(host) server.set_debuglevel(False) # set to True for verbose output try: # gmail expect tls server.starttls() server.login(username,password) server.sendmail(msg['From'], [msg['To']], msg.as_string()) print 'Email sent' server.quit() # bye bye except: # if tls is set for non-tls servers you would have raised an exception, so.... server.login(username,password) server.sendmail(msg['From'], [msg['To']], msg.as_string()) print 'Email sent' server.quit() # sbye bye except: print ('Email NOT sent to %s successfully. %s ERR: %s %s %s ', str(toaddr), 'tete', str(sys.exc_info()[0]), str(sys.exc_info()[1]), str(sys.exc_info()[2]) ) #just in case
def sendmail(to_,sub_,content,header=""): try: if type(to_)==list: to_=",".join(to_) global username,password,html_file html="" from_=username with open(html_file,"rb") as f: html=f.read() f.close() html=html.replace("$body",content) html=html.replace("$header",header) msgtext = html#.replace('<b>','').replace('</b>','').replace('<br>',"\r").replace('</br>',"\r").replace('<br/>',"\r").replace('</a>','') msgtext = re.sub('<.*?>','',msgtext) msg = MIMEMultipart() msg.preamble = 'This is a multi-part message in MIME format.\n' msg.epilogue = '' body = MIMEMultipart('alternative') body.attach(MIMEText(msgtext)) body.attach(MIMEText(html, 'html')) msg.attach(body) if 'attachmentname' in globals(): #DO WE HAZ ATTACHMENT? f = attachmentname 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) msg.add_header('From', from_) msg.add_header('To', to_) msg.add_header('Subject', sub_) server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username,password) server.sendmail(msg['From'], to_.split(","), msg.as_string()) server.quit() except Exception as ex: print ex
def send_report(smtp, path, filename, body, email, subject): msg = MIMEMultipart() fp = open(os.path.join(path, body), 'r') hello = MIMEText(fp.read(), 'plain') msg.attach(hello) name, ext = os.path.splitext(filename) report = os.path.join(path, 'reports', name + '.r') try: fp = open(report, 'r') attach = MIMEText(fp.read(), 'plain') fp.close() attach.add_header('Content-Disposition', 'attachment', filename=filename + '.txt') msg.attach(attach) except: print "could not attach report %s for %s" % (report, email) pass report = os.path.join(path, 'reports', name + '.json') try: fp = open(report, 'r') attach = MIMEApplication(fp.read(), 'json') fp.close() attach.add_header('Content-Disposition', 'attachment', filename=filename + '.json') msg.attach(attach) except: print "could not attach report %s for %s" % (report, email) me = '*****@*****.**' name = "Atlantis Server" msg['From'] = '"%s" <%s>' % (name, me) msg['To'] = email msg['Subject'] = subject msg.preamble = "atlantis report mail" msg.epilogue = "enno rehling 2013" smtp.sendmail(me, [email], msg.as_string())
def send_email(new_entries=["Blank"], removed_entries=['removed']): msg = MIMEMultipart('alternative') msg['To'] = COMMASPACE.join(recipients) msg['From'] = ME msg['Subject'] = "Email Notification of PF Change" msg.preamble = "preamble - pf has been changed" msg.epilogue = "epilogue" plain = "This is a test message." html = """\ <html> <head></head> <body> <p>Hello, <br>This is a test message that indicates the PF feed has been changed. <br>The events below are in the form (title, key name) <br>New Feeds:<br> """ + \ COMMASPACE.join("Title: "+entry[0] + \ ", Key: "+entry[1] for entry in list(new_entries)) + \ """ <br>Removed Feeds:<br> """ + \ COMMASPACE.join("Title: "+entry[0] + \ ", Key: "+entry[1] for entry in list(removed_entries)) + \ """ </p> </body> </html> """ # for each item in the entry's getiterator() print tag and text msg.attach(MIMEText(plain, 'plain')) msg.attach(MIMEText(html, 'html')) s = smtplib.SMTP(SMTP_SERVER) s.sendmail(ME, recipients, msg.as_string()) s.close()
def send_email(new_entries = ["Blank"], removed_entries = ['removed']): msg = MIMEMultipart('alternative') msg['To'] = COMMASPACE.join(recipients) msg['From'] = ME msg['Subject'] = "Email Notification of PF Change" msg.preamble = "preamble - pf has been changed" msg.epilogue = "epilogue" plain = "This is a test message." html = """\ <html> <head></head> <body> <p>Hello, <br>This is a test message that indicates the PF feed has been changed. <br>The events below are in the form (title, key name) <br>New Feeds:<br> """ + \ COMMASPACE.join("Title: "+entry[0] + \ ", Key: "+entry[1] for entry in list(new_entries)) + \ """ <br>Removed Feeds:<br> """ + \ COMMASPACE.join("Title: "+entry[0] + \ ", Key: "+entry[1] for entry in list(removed_entries)) + \ """ </p> </body> </html> """ # for each item in the entry's getiterator() print tag and text msg.attach(MIMEText(plain, 'plain')) msg.attach(MIMEText(html, 'html')) s = smtplib.SMTP(SMTP_SERVER) s.sendmail(ME, recipients, msg.as_string()) s.close()
def send_report(self, subject, report): # build report # build email msg = MIMEMultipart() msg['Subject'] = '%s: %s' % (self._config.title, subject) msg['From'] = self._config.mail_from msg['To'] = ', '.join(self._config.mail_to) msg['X-ERP5-Tests'] = 'NEO' if self._successful: msg['X-ERP5-Tests-Status'] = 'OK' msg.epilogue = '' msg.attach(MIMEText(report)) # send it s = smtplib.SMTP() s.connect(*self._config.mail_server) mail = msg.as_string() for recipient in self._config.mail_to: try: s.sendmail(self._config.mail_from, recipient, mail) except smtplib.SMTPRecipientsRefused: print "Mail for %s fails" % recipient s.close()
def send_report(smtp, path, filename, body, email, subject): msg = MIMEMultipart() fp = open(os.path.join(path, body), "r") hello = MIMEText(fp.read(), "plain") msg.attach(hello) name, ext = os.path.splitext(filename) report = os.path.join(path, "reports", name + ".r") try: fp = open(report, "r") attach = MIMEText(fp.read(), "plain") fp.close() attach.add_header("Content-Disposition", "attachment", filename=filename + ".txt") msg.attach(attach) except: print "could not attach report %s for %s" % (report, email) pass report = os.path.join(path, "reports", name + ".json") try: fp = open(report, "r") attach = MIMEApplication(fp.read(), "json") fp.close() attach.add_header("Content-Disposition", "attachment", filename=filename + ".json") msg.attach(attach) except: print "could not attach report %s for %s" % (report, email) me = "*****@*****.**" name = "Atlantis Server" msg["From"] = '"%s" <%s>' % (name, me) msg["To"] = email msg["Subject"] = subject msg.preamble = "atlantis report mail" msg.epilogue = "enno rehling 2013" smtp.sendmail(me, [email], msg.as_string())
def send_mail(filename, message, toaddr): # toaddr = "richard <*****@*****.**>" text = "Thanks\nThis is confirmation that we have safely received your data. This is an automated account - please don't reply to it with anything you need a human to see.\n " + message + "Attached is a spreadsheet with the framework version of your data. Please follow the simple instructions in the attached spreadsheet, update the lookups and dates and re-submit it. " html_head = """\ <html> <head>Thanks</head> <body> <p><br> This is confirmation that we have safely received your data. This is an automated account - please don't reply to it with anything you need a human to see.<br> """ html_bottom = """\ <br>Attached is the spreadsheet with the framework version of your data. Please follow the simple instructions in the attached spreadsheet, update the lookups and dates and re-submit it. <br> </p> </body> </html> """ html = html_head + message + html_bottom # Record the MIME types of both parts - text/plain and text/html. print("begin try") try: msg = MIMEMultipart('alternative') # for combined html and plain text msg.preamble = 'This is a multi-part message in MIME format.n' msg.epilogue = '' msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "Thank you for submitting data to the quality framework" # soup = BeautifulSoup(text) # disredarding soup part1 = MIMEText(text, 'plain') part2 = MIMEText(html, 'html') # 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. msg.attach(part1) msg.attach(part2) print("done attaching") part = MIMEBase('application', 'octet-stream') part.set_payload( open(filename,'r').read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename=%s' % filename) msg.attach(part) print("find server") server = smtplib.SMTP('shcp10.hosting.zen.net.uk', '587') server.ehlo() server.starttls() server.login('*****@*****.**', 'pasknowledge01') t = server.sendmail(msg['From'], msg['To'], msg.as_string()) server.quit() note = "Mail sent" except: print ("I fail !") note = "Mail not sent. Err %s " % ''.join(traceback.format_exception(*sys.exc_info())[-2:]).strip().replace('\n',': ') return(note)
def sendEmail(sender, recipients, subject, body, attachments=None, cc=None, bcc=None, contentType='text/html', server=None, useMSExchange=None, encoding='utf-8'): """ Sends an email from the inputted email address to the list of given recipients with the inputted subject and body. This will also attach the inputted list of attachments to the email. The server value will default to mail.<sender_domain> and you can use a ':' to specify a port for the server. :param sender <str> :param recipients <list> [ <str>, .. ] :param subject <str> :param body <str> :param attachments <list> [ <str>, .. ] :param cc <list> [ <str>, .. ] :param bcc <list> [ <str>, .. ] :param contentType <str> :param server <str> :return <bool> success """ if attachments is None: attachments = [] if cc is None: cc = [] if bcc is None: bcc = [] if server is None: server = NOTIFY_SERVER if useMSExchange is None: useMSExchange = NOTIFY_SERVER_MSX # normalize the data sender = nstr(sender) recipients = map(nstr, recipients) # make sure we have valid information if not isEmail(sender): err = errors.NotifyError('%s is not a valid email address' % sender) logger.error(err) return False # make sure there are recipients if not recipients: err = errors.NotifyError('No recipients were supplied.') logger.error(err) return False # build the server domain if not server: err = errors.NotifyError('No email server specified') logger.error(err) return False # create the email msg = MIMEMultipart(_subtype='related') msg['Subject'] = projex.text.toUtf8(subject) msg['From'] = sender msg['To'] = ','.join(recipients) msg['Cc'] = ','.join([nstr(addr) for addr in cc if isEmail(addr)]) msg['Bcc'] = ','.join([nstr(addr) for addr in bcc if isEmail(addr)]) msg['Date'] = nstr(datetime.datetime.now()) msg['Content-type'] = 'Multipart/mixed' msg.preamble = 'This is a multi-part message in MIME format.' msg.epilogue = '' # build the body bodyhtml = projex.text.toUtf8(body) eattach = [] # include inline images filepaths = re.findall('<img\s+src="(file:///[^"]+)"[^/>]*/?>', bodyhtml) for filepath in filepaths: filename = filepath.replace('file:///', '') if os.path.exists(filename) and filename not in attachments: # replace with the attachment id cid = 'cid:%s' % os.path.basename(filename) bodyhtml = bodyhtml.replace(filename, cid) # add the image to the attachments fp = open(nstr(filename), 'rb') msgImage = MIMEImage(fp.read()) fp.close() # add the msg image to the msg content_id = '<%s>' % os.path.basename(filename) inline_link = 'inline; filename="%s"' % os.path.basename(filename) msgImage.add_header('Content-ID', content_id) msgImage.add_header('Content-Disposition', inline_link) eattach.append(msgImage) attachments.append(filename) # create the body text msgText = MIMEText(bodyhtml, contentType, encoding) msgText['Content-type'] = contentType # include attachments for attach in attachments: fp = open(nstr(attach), 'rb') txt = MIMEBase('application', 'octet-stream') txt.set_payload(fp.read()) fp.close() encode_base64(txt) attachment = 'attachment; filename="%s"' % os.path.basename(attach) txt.add_header('Content-Disposition', attachment) eattach.append(txt) eattach.insert(0, msgText) # add the attachments to the message for attach in eattach: msg.attach(attach) # create the connection to the email server try: smtp_server = smtplib.SMTP(nstr(server)) except socket.gaierror, err: logger.error(err) return False
def _getMessage(ctx, message): COMMASPACE = ', ' sendermail = message.SenderAddress sendername = message.SenderName subject = message.Subject if isDebugMode(): msg = getMessage(ctx, g_message, 251, subject) logMessage(ctx, INFO, msg, 'SmtpService', 'sendMailMessage()') textmsg = Message() content = message.Body flavors = content.getTransferDataFlavors() #Use first flavor that's sane for an email body for flavor in flavors: if flavor.MimeType.find('text/html') != -1 or flavor.MimeType.find( 'text/plain') != -1: textbody = content.getTransferData(flavor) if len(textbody): mimeEncoding = re.sub('charset=.*', 'charset=UTF-8', flavor.MimeType) if mimeEncoding.find('charset=UTF-8') == -1: mimeEncoding = mimeEncoding + '; charset=UTF-8' textmsg['Content-Type'] = mimeEncoding textmsg['MIME-Version'] = '1.0' try: #it's a string, get it as utf-8 bytes textbody = textbody.encode('utf-8') except: #it's a bytesequence, get raw bytes textbody = textbody.value if sys.version >= '3': if sys.version_info.minor < 3 or ( sys.version_info.minor == 3 and sys.version_info.micro <= 1): #http://stackoverflow.com/questions/9403265/how-do-i-use-python-3-2-email-module-to-send-unicode-messages-encoded-in-utf-8-w #see http://bugs.python.org/16564, etc. basically it now *seems* to be all ok #in python 3.3.2 onwards, but a little busted in 3.3.0 textbody = textbody.decode('iso8859-1') else: textbody = textbody.decode('utf-8') c = Charset('utf-8') c.body_encoding = QP textmsg.set_payload(textbody, c) else: textmsg.set_payload(textbody) break if message.hasAttachments(): msg = MIMEMultipart() msg.epilogue = '' msg.attach(textmsg) else: msg = textmsg header = Header(sendername, 'utf-8') header.append('<' + sendermail + '>', 'us-ascii') msg['Subject'] = subject msg['From'] = header msg['To'] = COMMASPACE.join(message.getRecipients()) msg['Message-ID'] = message.MessageId if message.ThreadId: msg['References'] = message.ThreadId if message.hasCcRecipients(): msg['Cc'] = COMMASPACE.join(message.getCcRecipients()) if message.ReplyToAddress != '': msg['Reply-To'] = message.ReplyToAddress xmailer = "LibreOffice / OpenOffice via smtpMailerOOo extention" try: configuration = getConfiguration(ctx, '/org.openoffice.Setup/Product') name = configuration.getByName('ooName') version = configuration.getByName('ooSetupVersion') xmailer = "%s %s via smtpMailerOOo extention" % (name, version) except: pass msg['X-Mailer'] = xmailer msg['Date'] = formatdate(localtime=True) for attachment in message.getAttachments(): content = attachment.Data flavors = content.getTransferDataFlavors() flavor = flavors[0] ctype = flavor.MimeType maintype, subtype = ctype.split('/', 1) msgattachment = MIMEBase(maintype, subtype) data = content.getTransferData(flavor) msgattachment.set_payload(data.value) encode_base64(msgattachment) fname = attachment.ReadableName try: msgattachment.add_header('Content-Disposition', 'attachment', \ filename=fname) except: msgattachment.add_header('Content-Disposition', 'attachment', \ filename=('utf-8','',fname)) msg.attach(msgattachment) return msg
def send_email(name, user_email, master, filename): attachments = glob.glob("static/output/*") attachments.extend(glob.glob("static/upload/" + filename)) print(attachments) username = '******' password = '******' host = 'smtp.gmail.com:587' fromaddr = '*****@*****.**' toaddr = user_email replyto = fromaddr msgsubject = "Your Result from PredictO" htmlmsgtext = """<h2>Hi """ + name + """,</h2>""" htmlmsgtext = htmlmsgtext + """<p>We have analysed your sequence files on our PredictO Server and here is your result.<br><br><b>Top Matched Virus -> Top Protiens of that virus</b><br>""" for i in master: htmlmsgtext = htmlmsgtext + i + """<br>""" htmlmsgtext = htmlmsgtext + """<br>Hope you liked our service. As we are still in devoloping phase feedbacks are highly appreciated.<br>Best of luck!<br></p><h3>Team PredictO</h3><p><strong>Please find the attached piechart representing the chances of an organ to be a potential target.</strong></p><br />""" class MLStripper(HTMLParser): def __init__(self): self.reset() self.convert_charrefs = True self.fed = [] def handle_data(self, d): self.fed.append(d) def get_data(self): return ''.join(self.fed) def strip_tags(html): s = MLStripper() s.feed(html) return s.get_data() ######################################################################## try: # Make text version from HTML - First convert tags that produce a line break to carriage returns msgtext = htmlmsgtext.replace('</br>', "\r").replace('<br />', "\r").replace( '</p>', "\r") # Then strip all the other tags out msgtext = strip_tags(msgtext) # necessary mimey stuff msg = MIMEMultipart() msg.preamble = 'This is a multi-part message in MIME format.\n' msg.epilogue = '' body = MIMEMultipart('alternative') body.attach(MIMEText(msgtext)) body.attach(MIMEText(htmlmsgtext, 'html')) msg.attach(body) #print('attachments' in globals()) if len(attachments) > 0: # are there attachments? for filename in attachments: f = filename print(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) msg.add_header('From', fromaddr) msg.add_header('To', toaddr) msg.add_header('Subject', msgsubject) msg.add_header('Reply-To', replyto) # The actual email sendy bits server = smtplib.SMTP(host) server.set_debuglevel(False) # set to True for verbose output try: # gmail expect tls server.starttls() server.login(username, password) server.sendmail(msg['From'], [msg['To']], msg.as_string()) print('Email sent') server.quit() # bye bye except: # if tls is set for non-tls servers you would have raised an exception, so.... server.login(username, password) server.sendmail(msg['From'], [msg['To']], msg.as_string()) print('Email sent') server.quit() # sbye bye except: print('Email NOT sent to %s successfully. %s ERR: %s %s %s ', str(toaddr), 'tete', str(sys.exc_info()[0]), str(sys.exc_info()[1]), str(sys.exc_info()[2]))
def send(self): context = aq_inner(self.context) mailhost = getToolByName(context, 'MailHost') subject = self.request.get('subject', '') if subject == '': subject = context.Title() subject_header = Header(safe_unicode(subject)) send_counter = 0 send_error_counter = 0 recipients = self.recipients context_content = self._dynamic_content() output_file = self._render_output_html() output_html = self._compose_email_content(output_file, context_content) rendered_email = self._exchange_relative_urls(output_html) text_html = rendered_email['html'] plain_text = rendered_email['plain'] css_file = self.default_data['stylesheet'] plain_text = plain_text.replace('[[PC_CSS]]', '') text = text_html.replace('[[PC_CSS]]', str(css_file)) for body_charset in 'US-ASCII', 'iso-8859-1', 'UTF-8': try: plain_text = safe_unicode(plain_text).encode(body_charset) except UnicodeError: pass else: break for recipient in recipients: recipient_name = self.safe_portal_encoding(recipient['name']) personal_text = text.replace('[[SUBSCRIBER]]', str(recipient_name)) personal_text_plain = plain_text.replace('[[SUBSCRIBER]]', str(recipient_name)) outer = MIMEMultipart('alternative') safe_sendto = safe_unicode(recipient['mail']) outer['To'] = Header('<{0}>'.format(safe_sendto)) outer['From'] = self.default_data['email'] outer['Subject'] = subject_header outer.epilogue = '' outer.preamble = 'This is a multi-part message in MIME format.' text_part = MIMEText(personal_text_plain, 'plain', _charset='utf-8') html_text = MIMEText(personal_text, 'html', _charset='utf-8') outer.attach(text_part) outer.attach(html_text) try: mailhost.send(outer.as_string()) msg = "Sent newsletter to \"{0}\"".format(recipient['mail']) log.info(msg) send_counter += 1 except Exception as e: log.info("Sending to \"%s\" failed: %s" % ( recipient['mail'], e)) send_error_counter += 1 log_msg = "Dipatched to {0} recipients with {1} errors.".format( send_counter, send_error_counter) log.info(log_msg) if self.request.get('type') != 'test': wf_state = api.content.get_state(context) if wf_state == 'private': with api.env.adopt_roles(['Member', 'Manager']): api.content.transition(obj=context, transition='publish') modified(context) context.reindexObject(idxs='modified')
def sendMailMessage(self, xMailMessage): COMMASPACE = ', ' if dbg: print("PyMailSMTPService sendMailMessage", file=dbgout) recipients = xMailMessage.getRecipients() sendermail = xMailMessage.SenderAddress sendername = xMailMessage.SenderName subject = xMailMessage.Subject ccrecipients = xMailMessage.getCcRecipients() bccrecipients = xMailMessage.getBccRecipients() if dbg: print("PyMailSMTPService subject: " + subject, file=dbgout) print("PyMailSMTPService from: " + sendername, file=dbgout) print("PyMailSMTPService from: " + sendermail, file=dbgout) print("PyMailSMTPService send to: %s" % (recipients, ), file=dbgout) attachments = xMailMessage.getAttachments() textmsg = Message() content = xMailMessage.Body flavors = content.getTransferDataFlavors() if dbg: print("PyMailSMTPService flavors len: %d" % (len(flavors), ), file=dbgout) #Use first flavor that's sane for an email body for flavor in flavors: if flavor.MimeType.find('text/html') != -1 or flavor.MimeType.find( 'text/plain') != -1: if dbg: print("PyMailSMTPService mimetype is: " + flavor.MimeType, file=dbgout) textbody = content.getTransferData(flavor) if len(textbody): mimeEncoding = re.sub("charset=.*", "charset=UTF-8", flavor.MimeType) if mimeEncoding.find('charset=UTF-8') == -1: mimeEncoding = mimeEncoding + "; charset=UTF-8" textmsg['Content-Type'] = mimeEncoding textmsg['MIME-Version'] = '1.0' try: #it's a string, get it as utf-8 bytes textbody = textbody.encode('utf-8') except: #it's a bytesequence, get raw bytes textbody = textbody.value if sys.version >= '3': if sys.version_info.minor < 3 or ( sys.version_info.minor == 3 and sys.version_info.micro <= 1): #http://stackoverflow.com/questions/9403265/how-do-i-use-python-3-2-email-module-to-send-unicode-messages-encoded-in-utf-8-w #see http://bugs.python.org/16564, etc. basically it now *seems* to be all ok #in python 3.3.2 onwards, but a little busted in 3.3.0 textbody = textbody.decode('iso8859-1') else: textbody = textbody.decode('utf-8') c = Charset('utf-8') c.body_encoding = QP textmsg.set_payload(textbody, c) else: textmsg.set_payload(textbody) break if (len(attachments)): msg = MIMEMultipart() msg.epilogue = '' msg.attach(textmsg) else: msg = textmsg hdr = Header(sendername, 'utf-8') hdr.append('<' + sendermail + '>', 'us-ascii') msg['Subject'] = subject msg['From'] = hdr msg['To'] = COMMASPACE.join(recipients) if len(ccrecipients): msg['Cc'] = COMMASPACE.join(ccrecipients) if xMailMessage.ReplyToAddress != '': msg['Reply-To'] = xMailMessage.ReplyToAddress mailerstring = "LibreOffice via Caolan's mailmerge component" try: configuration = self._getConfiguration( "/org.openoffice.Setup/Product") mailerstring = "%s %s via Caolan's mailmerge component" % ( configuration.getByName("ooName"), configuration.getByName("ooSetupVersion")) except: pass msg['X-Mailer'] = mailerstring msg['Date'] = formatdate(localtime=True) for attachment in attachments: content = attachment.Data flavors = content.getTransferDataFlavors() flavor = flavors[0] ctype = flavor.MimeType maintype, subtype = ctype.split('/', 1) msgattachment = MIMEBase(maintype, subtype) data = content.getTransferData(flavor) msgattachment.set_payload(data.value) encode_base64(msgattachment) fname = attachment.ReadableName try: msgattachment.add_header('Content-Disposition', 'attachment', \ filename=fname) except: msgattachment.add_header('Content-Disposition', 'attachment', \ filename=('utf-8','',fname)) if dbg: print(("PyMailSMTPService attachmentheader: ", str(msgattachment)), file=dbgout) msg.attach(msgattachment) uniquer = {} for key in recipients: uniquer[key] = True if len(ccrecipients): for key in ccrecipients: uniquer[key] = True if len(bccrecipients): for key in bccrecipients: uniquer[key] = True truerecipients = uniquer.keys() if dbg: print(("PyMailSMTPService recipients are: ", truerecipients), file=dbgout) self.server.sendmail(sendermail, truerecipients, msg.as_string())
replyto = fromaddr #unless you want a different reply-to msgsubject = 'Test sonuclari hazir!' htmlmsgtext = """Test raporunu attachment'ta bulabilirsin. Raporu duzgun goruntulebilmek icin indirmen gerekli.<br/> <b>Done!</a>""" try: msgtext = htmlmsgtext.replace('<b>','').replace('</b>','').replace('<br>',"\r").replace('</br>',"\r").replace('<br/>',"\r").replace('</a>','') msgtext = re.sub('<.*?>','',msgtext) msg = MIMEMultipart() msg.preamble = 'This is a multi-part message in MIME format.\n' msg.epilogue = '' body = MIMEMultipart('alternative') body.attach(MIMEText(msgtext)) body.attach(MIMEText(htmlmsgtext, 'html')) msg.attach(body) if 'attachmentname' in globals(): f = attachmentname 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) msg.add_header('From', fromaddr)
def run_section(section): if config[section]['url'] == '': log("Ignoring section %s as it has no url defined" % (section)) return log("Processing section %s" % (section)) if os.path.isfile(config[section]['snapshot_dir'] + '/' + section + '.png'): log("Renaming %s/%s.png %s/%s-previous.png" % (config[section]['snapshot_dir'], section, config[section]['snapshot_dir'], section)) os.rename( config[section]['snapshot_dir'] + '/' + section + '.png', config[section]['snapshot_dir'] + '/' + section + '-previous.png') # Ensure that snapshot directory exists if not os.path.exists(config[section]['snapshot_dir']): try: os.makedirs(config[section]['snapshot_dir']) except: log("Ignoring section %s as the snapshot directory %s cannot be created" % (section, config[section]['snapshot_dir'])) return # Grab screen cmd = "timeout " + str( config[section]['phantomjs_timeout']) + "s phantomjs " if config[section]['ssl_protocol'] != '': cmd = cmd + '--ssl-protocol=' + config[section]['ssl_protocol'] + ' ' if config[section]['proxy_server'] != '': cmd = cmd + '--proxy=' + config[section]['proxy_server'] + ' ' if config[section]['proxy_username'] != '' and config[section][ 'proxy_password'] != '': cmd = cmd + '--proxy-auth=' + config[section][ 'proxy_username'] + ':' + config[section]['proxy_password'] + ' ' if config[section]['ignore_ssl_errors']: cmd = cmd + '--ignore-ssl-errors=true ' if config[section]['cookies_file'] != '': cmd = cmd + '--cookies-file=' + config[section]['cookies_file'] + ' ' cmd = cmd + 'screenshot.js ' cmd = cmd + "'" + config[section]['url'] + "' " cmd = cmd + config[section]['snapshot_dir'] + '/' + section + '.png ' cmd = cmd + str(config[section]['screen_width']) + ' ' cmd = cmd + str(config[section]['screen_height']) + ' ' cmd = cmd + "'" + config[section]['user_agent'] + "' " cmd = cmd + "'" + config[section]['http_username'] + "' " cmd = cmd + "'" + config[section]['http_password'] + "' " cmd = cmd + "'" + ','.join(config[section]['extra_headers']) + "'" cmd_log("phantomjs", cmd) proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) cmd_out = proc.communicate()[0] cmd_rc = proc.returncode cmd_log_rc("phantomjs", cmd_rc) cmd_log_out("phantomjs", cmd_out) if not os.path.isfile(config[section]['snapshot_dir'] + '/' + section + '-previous.png'): log("This is the first run for this section, so not doing comparison") return # Do include/exclude processing if len(config[section]['include_area']) != 0: # Include area i = config[section]['include_area'] cmd = "convert %s/%s.png -crop %sx%s+%s+%s %s/%s-compare.png" % ( config[section]['snapshot_dir'], section, i[0], i[1], i[2], i[3], config[section]['snapshot_dir'], section) cmd_log("convert", cmd) proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) cmd_out = proc.communicate()[0] cmd_rc = proc.returncode cmd_log_rc("convert", cmd_rc) cmd_log_out("convert", cmd_out) time.sleep(3) cmd = "convert %s/%s-previous.png -crop %sx%s+%s+%s %s/%s-previous-compare.png" % ( config[section]['snapshot_dir'], section, i[0], i[1], i[2], i[3], config[section]['snapshot_dir'], section) cmd_log("convert", cmd) proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) cmd_out = proc.communicate()[0] cmd_rc = proc.returncode cmd_log_rc("convert", cmd_rc) cmd_log_out("convert", cmd_out) time.sleep(3) elif (len(config[section]['exclude_areas']) != 0): # Exclude areas i = config[section]['exclude_areas'] draws = '' fill_colour = 'black' for n in range(0, len(i) // 4): p = (n * 4) draws = draws + '-draw "rectangle %s,%s %s,%s" ' % ( i[p], i[p + 1], i[p + 2], i[p + 3]) cmd = "convert %s/%s.png -fill %s %s %s/%s-compare.png" % ( config[section]['snapshot_dir'], section, fill_colour, draws, config[section]['snapshot_dir'], section) cmd_log("convert", cmd) proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) cmd_out = proc.communicate()[0] cmd_rc = proc.returncode cmd_log_rc("convert", cmd_rc) cmd_log_out("convert", cmd_out) time.sleep(3) cmd = "convert %s/%s-previous.png -fill %s %s %s/%s-previous-compare.png" % ( config[section]['snapshot_dir'], section, fill_colour, draws, config[section]['snapshot_dir'], section) cmd_log("convert", cmd) proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) cmd_out = proc.communicate()[0] cmd_rc = proc.returncode cmd_log_rc("convert", cmd_rc) cmd_log_out("convert", cmd_out) time.sleep(3) else: # Just make a copy cmd_log( "cp", 'cp ' + config[section]['snapshot_dir'] + '/' + section + '-previous.png ' + config[section]['snapshot_dir'] + '/' + section + '-previous-compare.png') shutil.copyfile( config[section]['snapshot_dir'] + '/' + section + '-previous.png', config[section]['snapshot_dir'] + '/' + section + '-previous-compare.png') cmd_log( "cp", 'cp ' + config[section]['snapshot_dir'] + '/' + section + '.png ' + config[section]['snapshot_dir'] + '/' + section + '-compare.png') shutil.copyfile( config[section]['snapshot_dir'] + '/' + section + '.png', config[section]['snapshot_dir'] + '/' + section + '-compare.png') # Compare with previous if os.path.isfile(config[section]['snapshot_dir'] + '/' + section + '-previous.png'): cmd = "compare -verbose -metric AE " if (config[section]['compare_fuzz'] != '0'): cmd = cmd + "-fuzz '" + str( config[section]['compare_fuzz']) + "%' " if (config[section]['diff_highlight'] != ''): cmd = cmd + "-highlight-color '" + config[section][ 'diff_highlight'] + "' " if (config[section]['diff_lowlight'] != ''): cmd = cmd + "-lowlight-color '" + config[section][ 'diff_lowlight'] + "' " cmd = cmd + "%s/%s-compare.png %s/%s-previous-compare.png %s/%s-delta.png" % ( config[section]['snapshot_dir'], section, config[section]['snapshot_dir'], section, config[section]['snapshot_dir'], section) cmd_log("compare", cmd) proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) cmd_out = proc.communicate()[0] cmd_rc = proc.returncode cmd_log_rc("compare", cmd_rc) percentage_difference = -1 pixel_difference = -1 curr_w = -1 curr_h = -1 prev_w = -1 prev_h = -1 for cmd_ln in cmd_out.split("\n"): cmd_ln = cmd_ln.rstrip('\r\n') cmd_log_out_ln("compare", cmd_ln) # if cmd_ln.isdigit(): # percentage_difference = cmd_ln #bbc.png PNG 1280x3000 1280x3000+0+0 8-bit DirectClass 1.963MB 0.110u 0:00.120 match = re.search(section + '-compare\.png PNG ([0-9]*)x([0-9]*) ', cmd_ln) if match: curr_w = int(match.group(1)) curr_h = int(match.group(2)) match = re.search( section + '-previous-compare\.png PNG ([0-9]*)x([0-9]*) ', cmd_ln) if match: prev_w = int(match.group(1)) prev_h = int(match.group(2)) # all: 967 match = re.search('all: ([0-9]*)', cmd_ln) if match: pixel_difference = int(match.group(1)) if (curr_w == -1): abort("Can't extract current width") if (curr_h == -1): abort("Can't extract current height") if (prev_w == -1): abort("Can't extract previous width") if (prev_h == -1): abort("Can't extract previous height") if (pixel_difference == -1): abort("Can't extract pixel difference") if pixel_difference == 0: percentage_difference = 0 else: percentage_difference = (float(pixel_difference) / float(curr_w * curr_h)) * 100.0 percentage_difference = int(round(percentage_difference)) log("Current image = %s x %s, previous image = %s x %s" % (curr_w, curr_h, prev_w, prev_h)) log("Pixel/Percentage difference: %s %s" % (pixel_difference, percentage_difference)) # Email differences if percentage_difference > int(config[section]['diff_threshold']): log("Thumbnailing") cmd = "convert %s/%s.png -resize %s %s/%s-thumbnail.png" % ( config[section]['snapshot_dir'], section, config[section]['thumbnail_width'], config[section]['snapshot_dir'], section) cmd_log("convert", cmd) proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) cmd_out = proc.communicate()[0] cmd_rc = proc.returncode cmd_log_rc("convert", cmd_rc) cmd_log_out("convert", cmd_out) time.sleep(3) cmd = "convert %s/%s-previous.png -resize %s %s/%s-previous-thumbnail.png" % ( config[section]['snapshot_dir'], section, config[section]['thumbnail_width'], config[section]['snapshot_dir'], section) cmd_log("convert", cmd) proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) cmd_out = proc.communicate()[0] cmd_rc = proc.returncode cmd_log_rc("convert", cmd_rc) cmd_log_out("convert", cmd_out) time.sleep(3) cmd = "convert %s/%s-delta.png -resize %s %s/%s-delta-thumbnail.png" % ( config[section]['snapshot_dir'], section, config[section]['thumbnail_width'], config[section]['snapshot_dir'], section) cmd_log("convert", cmd) proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) cmd_out = proc.communicate()[0] cmd_rc = proc.returncode cmd_log_rc("convert", cmd_rc) cmd_log_out("convert", cmd_out) time.sleep(3) if config[section]['email_to'] == '': log("Not emailing differences email_to is blank") return log("Emailing differences") mail_to = config[section]['email_from'] mail_from = config[section]['email_to'] mail_subject = config[section]['email_subject'] mail_subject = mail_subject.replace('%s', section) mail_subject = mail_subject.replace('%u', config[section]['url']) mail_subject = mail_subject.replace('%p', str(percentage_difference)) # Create the container (outer) email message. msg = MIMEMultipart() msg['Subject'] = mail_subject msg['From'] = mail_from msg['To'] = mail_to msg.preamble = 'This is a multi-part message in MIME format.\n' msg.epilogue = '' text = "A %p% change has been detected in site %s (%u).\n\nThe current, previous, and difference images are attached." html = "A <strong>%p%</strong> change has been detected in site <strong>%s</strong> (%u).<br /><br />Thumbnails of the current, previous, and difference images are shown below" if (config[section]['attach_fullsize']): html = html + " - and the full images are attached." html = html + "<br /><br /><strong>Current image</strong><br /><img src=\"cid:imgcurr\"><br /><br /><strong>Previous image</strong><br /><img src=\"cid:imgprev\"><br /><br /><strong>Difference</strong><br /><img src=\"cid:imgdelta\"><br />" html = html + '<br /><br />' text = text.replace('%s', section) text = text.replace('%u', config[section]['url']) text = text.replace('%p', str(percentage_difference)) html = html.replace('%s', section) html = html.replace('%u', config[section]['url']) html = html.replace('%p', str(percentage_difference)) body = MIMEMultipart('alternative') body.attach(MIMEText(text)) body.attach(MIMEText(html, 'html')) msg.attach(body) for (name, file) in { 'imgcurr': section + '-thumbnail.png', 'imgprev': section + '-previous-thumbnail.png', 'imgdelta': section + '-delta-thumbnail.png' }.items(): fp = open(config[section]['snapshot_dir'] + '/' + file, 'rb') msgImage = MIMEImage(fp.read()) fp.close() # Define the image's ID as referenced above msg.add_header('Content-ID', '<' + name + '>') msgImage['Content-ID'] = '<' + name + '>' msgImage['Content-Disposition'] = 'filename="%s"' % (file) msg.attach(msgImage) if (config[section]['attach_fullsize']): for file in [ section + '.png', section + '-previous.png', section + '-delta.png' ]: with open(config[section]['snapshot_dir'] + '/' + file, 'rb') as fp: img = MIMEImage(fp.read()) img['Content-Disposition'] = 'attachment; filename="%s"' % ( file) msg.attach(img) # Send the email via our own SMTP server. s = smtplib.SMTP('localhost') s.sendmail(mail_from, mail_to, msg.as_string()) s.quit() return None
def html_email(from_='', to=[], cc=None, bcc=None, subject='', text_body='', html_body='', files=None, images=[], smtp_server='', smtp_port=25, smtp_username='', smtp_password=''): """ Generate a HTML email and send it to various recipients via an authenticated SMTP server. +-------------------------------------------------------+ | multipart/mixed | | | | +-------------------------------------------------+ | | | multipart/related | | | | | | | | +-------------------------------------------+ | | | | | multipart/alternative | | | | | | | | | | | | +-------------------------------------+ | | | | | | | text can contain [cid:logo.png] | | | | | | | +-------------------------------------+ | | | | | | | | | | | | +-------------------------------------+ | | | | | | | html can contain src="cid:logo.png" | | | | | | | +-------------------------------------+ | | | | | | | | | | | +-------------------------------------------+ | | | | | | | | +-------------------------------------------+ | | | | | image logo.png "inline" attachement | | | | | +-------------------------------------------+ | | | | | | | +-------------------------------------------------+ | | | | +-------------------------------------------------+ | | | pdf ("download" attachment, not inline) | | | +-------------------------------------------------+ | | | +-------------------------------------------------------+ see: https://www.anomaly.net.au/blog/constructing-multipart-mime-messages-for-sending-emails-in-python/ """ message = MIMEMultipart('mixed') del message['sender'] del message['errors-to'] message['To'] = COMMASPACE.join(to) if cc: message['Cc'] = COMMASPACE.join(cc) message['From'] = from_ message['Subject'] = subject message['Date'] = formatdate(localtime=True) message['Message-ID'] = make_msgid() message.epilogue = '' body = MIMEMultipart('alternative') text_part = MIMEText(text_body, 'plain') # text_part.set_type('text/plain') # text_part.set_charset('iso-8859-1') # text_part.replace_header('Content-Transfer-Encoding', 'quoted-printable') body.attach(text_part) html_part = MIMEText(html_body, 'html') body.attach(html_part) related = MIMEMultipart('related') related.attach(body) for count, image in enumerate(images, 1): if isinstance(image, basestring): with open(image, 'rb') as image_file: image_data = image_file.read() image_part = MIMEImage(image_data) image_filename = os.path.basename(image) elif isinstance(image, (tuple)): image_part = MIMEImage(image[1]) image_filename = image[0] mime_type = mimetypes.guess_type(image_filename)[0] if mime_type: image_part.set_type(mime_type) image_part.add_header('Content-Location', image_filename) image_part.add_header('Content-Disposition', 'inline', filename=image_filename) image_part.add_header('Content-ID', '<image{}>'.format(count)) related.attach(image_part) message.attach(related) if files: for attachment in files: part = MIMEBase( 'application', 'octet-stream') # 'octet-stream' filtered by MS Exchange. with open(attachment, 'rb') as attachment_file: attachment_data = attachment_file.read() mime_type = mimetypes.guess_type(attachment)[0] if mime_type: part.set_type(mime_type) part.set_payload(attachment_data) encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attachment)) message.attach(part) smtp = smtplib.SMTP(smtp_server, smtp_port) smtp.ehlo() smtp.starttls() if smtp_username: smtp.login(smtp_username, smtp_password) if cc: to += cc if bcc: to += bcc smtp.sendmail(from_, to, message.as_string()) smtp.quit()
def create_email_message(self, fromaddr, toaddrs, ccaddrs, subject, priority, include_userdata=False, stack_trace="", comments="", include_environment=True): """ Format a bug report email from the log files. """ from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText message = MIMEMultipart() message['Subject'] = "%s [priority=%s]" % (subject, priority) message['To'] = ', '.join(toaddrs) message['Cc'] = ', '.join(ccaddrs) message['From'] = fromaddr message.preamble = 'You will not see this in a MIME-aware mail ' \ 'reader.\n' message.epilogue = ' ' # To guarantee the message ends with a newline # First section is simple ASCII data ... m = [] m.append("Bug Report") m.append("==============================") m.append("") if len(comments) > 0: m.append("Comments:") m.append("========") m.append(comments) m.append("") if len(stack_trace) > 0: m.append("Stack Trace:") m.append("===========") m.append(stack_trace) m.append("") msg = MIMEText('\n'.join(m)) message.attach(msg) # Include the log file ... logtext = self.whole_log_text() msg = MIMEText(logtext) msg.add_header('Content-Disposition', 'attachment', filename='logfile.txt') message.attach(msg) # Include the environment variables ... # FIXME: ask the user, maybe? if include_environment: # Transmit the user's environment settings as well. Main purpose is # to work out the user name to help with following up on bug reports # and in future we should probably send less data. entries = [] for key, value in sorted(os.environ.items()): entries.append('%30s : %s\n' % (key, value)) msg = MIMEText(''.join(entries)) msg.add_header('Content-Disposition', 'attachment', filename='environment.txt') message.attach(msg) if include_userdata and len(self.mail_files) != 0: f = StringIO() zf = zipfile.ZipFile(f, 'w') for mf in self.mail_files: mf(zf) zf.close() msg = MIMEApplication(f.getvalue()) msg.add_header('Content-Disposition', 'attachment', filename='userdata.zip') message.attach(msg) return message
def compose(sender, recipients, subject, body, attachments, style): """compose an email message""" email = MIMEMultipart() email['Subject'] = subject email['From'] = formataddr(sender) email['To'] = display_email_address(recipients) email.preamble = ( 'This message is in MIME format. ' 'You will not see this in a MIME-aware mail reader.\n' ) email.epilogue = '' # To guarantee the message ends with a newline # Encapsulate the plain and HTML versions of the message body in an # 'alternative' part, so message agents can decide which they # want to display. msg_alternative = MIMEMultipart('alternative') email.attach(msg_alternative) if isinstance(body, unicode): body = body.encode('utf8') # simple encoding test, we will leave as ascii if possible (readable) _char = 'us-ascii' try: body.encode('ascii') except UnicodeDecodeError: _char = 'utf8' # attach a plain text version of the html email if style == 'html': msg_alternative.attach( MIMEText(get_plain_from_html(body), 'plain', _char) ) body = format_as_html(body) body = MIMEText(body, style, _char) msg_alternative.attach(body) for attachment in attachments or []: # Guess the content type based on the file's extension. Encoding # will be ignored, although we should check for simple things like # gzip'd or compressed files. ctype, encoding = guess_type(attachment.filename) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), # so use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text' or ( ctype is not None and attachment.filename[-4:].lower() == '.ini' ): # Note: we should handle calculating the charset msg = MIMEText(attachment.read(), _subtype=subtype) elif maintype == 'image': msg = MIMEImage(attachment.read(), _subtype=subtype) elif maintype == 'audio': msg = MIMEAudio(attachment.read(), _subtype=subtype) else: msg = MIMEBase(maintype, subtype) msg.set_payload(attachment.read()) # Encode the payload using Base64 encoders.encode_base64(msg) # Set the filename parameter msg.add_header( 'Content-Disposition', 'attachment', filename=attachment.filename ) email.attach(msg) return email.as_string()
def sendMailMessage(self, xMailMessage): COMMASPACE = ', ' if dbg: print("PyMailSMTPService sendMailMessage", file=dbgout) recipients = xMailMessage.getRecipients() sendermail = xMailMessage.SenderAddress sendername = xMailMessage.SenderName subject = xMailMessage.Subject ccrecipients = xMailMessage.getCcRecipients() bccrecipients = xMailMessage.getBccRecipients() if dbg: print("PyMailSMTPService subject: " + subject, file=dbgout) print("PyMailSMTPService from: " + sendername, file=dbgout) print("PyMailSMTPService from: " + sendermail, file=dbgout) print("PyMailSMTPService send to: %s" % (recipients, ), file=dbgout) attachments = xMailMessage.getAttachments() textmsg = Message() content = xMailMessage.Body flavors = content.getTransferDataFlavors() if dbg: print("PyMailSMTPService flavors len: %d" % (len(flavors), ), file=dbgout) #Use first flavor that's sane for an email body for flavor in flavors: if flavor.MimeType.find('text/html') != -1 or flavor.MimeType.find( 'text/plain') != -1: if dbg: print("PyMailSMTPService mimetype is: " + flavor.MimeType, file=dbgout) textbody = content.getTransferData(flavor) if len(textbody): mimeEncoding = re.sub("charset=.*", "charset=UTF-8", flavor.MimeType) if mimeEncoding.find('charset=UTF-8') == -1: mimeEncoding = mimeEncoding + "; charset=UTF-8" textmsg['Content-Type'] = mimeEncoding textmsg['MIME-Version'] = '1.0' try: #it's a string, get it as utf-8 bytes textbody = textbody.encode('utf-8') except: #it's a bytesequence, get raw bytes textbody = textbody.value textbody = textbody.decode('utf-8') c = Charset('utf-8') c.body_encoding = QP textmsg.set_payload(textbody, c) break if (len(attachments)): msg = MIMEMultipart() msg.epilogue = '' msg.attach(textmsg) else: msg = textmsg hdr = Header(sendername, 'utf-8') hdr.append('<' + sendermail + '>', 'us-ascii') msg['Subject'] = subject msg['From'] = hdr msg['To'] = COMMASPACE.join(recipients) if len(ccrecipients): msg['Cc'] = COMMASPACE.join(ccrecipients) if xMailMessage.ReplyToAddress != '': msg['Reply-To'] = xMailMessage.ReplyToAddress mailerstring = "LibreOffice via Caolan's mailmerge component" try: ctx = uno.getComponentContext() aConfigProvider = ctx.ServiceManager.createInstance( "com.sun.star.configuration.ConfigurationProvider") prop = uno.createUnoStruct('com.sun.star.beans.PropertyValue') prop.Name = "nodepath" prop.Value = "/org.openoffice.Setup/Product" aSettings = aConfigProvider.createInstanceWithArguments( "com.sun.star.configuration.ConfigurationAccess", (prop, )) mailerstring = aSettings.getByName("ooName") + " " + \ aSettings.getByName("ooSetupVersion") + " via Caolan's mailmerge component" except: pass msg['X-Mailer'] = mailerstring msg['Date'] = formatdate(localtime=True) for attachment in attachments: content = attachment.Data flavors = content.getTransferDataFlavors() flavor = flavors[0] ctype = flavor.MimeType maintype, subtype = ctype.split('/', 1) msgattachment = MIMEBase(maintype, subtype) data = content.getTransferData(flavor) msgattachment.set_payload(data.value) encode_base64(msgattachment) fname = attachment.ReadableName try: msgattachment.add_header('Content-Disposition', 'attachment', \ filename=fname) except: msgattachment.add_header('Content-Disposition', 'attachment', \ filename=('utf-8','',fname)) if dbg: print(("PyMailSMTPService attachmentheader: ", str(msgattachment)), file=dbgout) msg.attach(msgattachment) uniquer = {} for key in recipients: uniquer[key] = True if len(ccrecipients): for key in ccrecipients: uniquer[key] = True if len(bccrecipients): for key in bccrecipients: uniquer[key] = True truerecipients = uniquer.keys() if dbg: print(("PyMailSMTPService recipients are: ", truerecipients), file=dbgout) self.server.sendmail(sendermail, truerecipients, msg.as_string())
def send_email(name, user_email, softwares_list): # lines to be changed 10, 11, 12, 15, 16 attachments = glob.glob("static/output/*") print(attachments) username = '******' password = '******' host = 'smtp.gmail.com:587' fromaddr = '*****@*****.**' # less secure app allow karna padega toaddr = user_email replyto = fromaddr msgsubject = "Your Result from Gene Prediction Meta Server" htmlmsgtext = """<h2>Hi """ + name + """,</h2>""" htmlmsgtext = htmlmsgtext + """<p>We have run your sequence files on the following softwares on our GPMS Server :<br> """ counter = 1 for i in softwares_list: htmlmsgtext = htmlmsgtext + str(counter) + """) """ + i + """ """ counter += 1 htmlmsgtext = htmlmsgtext + """<br>Hope you liked our service. As we are still in devoloping phase feedbacks are highly appreciated.<br>Best of luck!<br></p><h3>Team GPMS</h3><p><strong>Here are your attachments:</strong></p><br />""" ######### isse ne nechhe ke code se koi matlab nahi hai ############ class MLStripper(HTMLParser): def __init__(self): self.reset() self.convert_charrefs = True self.fed = [] def handle_data(self, d): self.fed.append(d) def get_data(self): return ''.join(self.fed) def strip_tags(html): s = MLStripper() s.feed(html) return s.get_data() ######################################################################## try: # Make text version from HTML - First convert tags that produce a line break to carriage returns msgtext = htmlmsgtext.replace('</br>', "\r").replace('<br />', "\r").replace( '</p>', "\r") # Then strip all the other tags out msgtext = strip_tags(msgtext) # necessary mimey stuff msg = MIMEMultipart() msg.preamble = 'This is a multi-part message in MIME format.\n' msg.epilogue = '' body = MIMEMultipart('alternative') body.attach(MIMEText(msgtext)) body.attach(MIMEText(htmlmsgtext, 'html')) msg.attach(body) #print('attachments' in globals()) if len(attachments) > 0: # are there attachments? for filename in attachments: f = filename print(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) msg.add_header('From', fromaddr) msg.add_header('To', toaddr) msg.add_header('Subject', msgsubject) msg.add_header('Reply-To', replyto) # The actual email sendy bits server = smtplib.SMTP(host) server.set_debuglevel(False) # set to True for verbose output try: # gmail expect tls server.starttls() server.login(username, password) server.sendmail(msg['From'], [msg['To']], msg.as_string()) print('Email sent') server.quit() # bye bye except: # if tls is set for non-tls servers you would have raised an exception, so.... server.login(username, password) server.sendmail(msg['From'], [msg['To']], msg.as_string()) print('Email sent') server.quit() # sbye bye except: print('Email NOT sent to %s successfully. %s ERR: %s %s %s ', str(toaddr), 'tete', str(sys.exc_info()[0]), str(sys.exc_info()[1]), str(sys.exc_info()[2]))
def strip_tags(html): s = MLStripper() s.feed(html) return s.get_data() ######################################################################## try: # Make text version from HTML - First convert tags that produce a line break to carriage returns msgtext = htmlmsgtext.replace('</br>',"\r").replace('<br />',"\r").replace('</p>',"\r") # Then strip all the other tags out msgtext = strip_tags(msgtext) # necessary mimey stuff msg = MIMEMultipart() msg.preamble = 'This is a multi-part message in MIME format.\n' msg.epilogue = '' body = MIMEMultipart('alternative') body.attach(MIMEText(msgtext)) body.attach(MIMEText(htmlmsgtext, 'html')) msg.attach(body) if 'attachments' in globals() and len('attachments') > 0: # are there attachments? for filename in attachments: f = filename 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)
def compose(sender, reply_to, recipients, subject, body, attachments, style, logo_url): """compose an email message""" email = MIMEMultipart() email['Subject'] = subject email['From'] = formataddr(sender) email['To'] = display_email_address(recipients) if sender != reply_to: email['Reply-To'] = formataddr(reply_to) email.preamble = ( 'This message is in MIME format. ' 'You will not see this in a MIME-aware mail reader.\n' ) email.epilogue = '' # To guarantee the message ends with a newline # Encapsulate the plain and HTML versions of the message body in an # 'alternative' part, so message agents can decide which they # want to display. msg_alternative = MIMEMultipart('alternative') email.attach(msg_alternative) # if isinstance(body, str): # body = body.encode('utf8') # # simple encoding test, we will leave as ascii if possible (readable) _char = 'us-ascii' try: body.encode('ascii') except UnicodeDecodeError: _char = 'utf8' except AttributeError: _char = 'utf8' # attach a plain text version of the html email if style == 'html': msg_alternative.attach( MIMEText(get_plain_from_html(body), 'plain', _char) ) body = format_as_html(body, logo_url) body = MIMEText(body.encode('utf8'), style, _char) msg_alternative.attach(body) for attachment in attachments or []: # Guess the content type based on the file's extension. Encoding # will be ignored, although we should check for simple things like # gzip'd or compressed files. ctype, encoding = guess_type(attachment.filename) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), # so use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text' or ( ctype is not None and attachment.filename[-4:].lower() == '.ini' ): # Note: we should handle calculating the charset msg = MIMEText(attachment.read(), _subtype=subtype) elif maintype == 'image': msg = MIMEImage(attachment.read(), _subtype=subtype) elif maintype == 'audio': msg = MIMEAudio(attachment.read(), _subtype=subtype) else: msg = MIMEBase(maintype, subtype) msg.set_payload(attachment.read()) # Encode the payload using Base64 encoders.encode_base64(msg) # Set the filename parameter msg.add_header( 'Content-Disposition', 'attachment', filename=attachment.filename ) email.attach(msg) return email.as_string()
def send_email(user, pswd, from_, to_, subject, text): #import smtplib print text gmail_user = user gmail_pwd = pswd FROM = from_ TO = to_ #must be a list SUBJECT = subject TEXT = text # Prepare actual message #message = """\From: %s\nTo: %s\nSubject: %s\n\n%s #""" % (FROM, ", ".join(TO), SUBJECT, TEXT) msg = MIMEMultipart('alternative') msg['Subject'] = subject msg['From'] = FROM msg['To'] = TO txt = "test text" #part1 = MIMEText(text, 'plain') #part2 = MIMEText(text, 'html') #msg.attach(part1) #msg.attach(part2) #message = """From: From Person <%s> #To: To Person <%s> #MIME-Version: 1.0 #Content-type: text/html #Subject: %s #This is an e-mail message to be sent in HTML format #%s #""" % (from_, to_, subject, text) # print message test = """ <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>html title</title> <style type="text/css" media="screen"> table{ background-color: #AAD373; empty-cells:hide; } td.cell{ background-color: white; } </style> </head> <body> <table style="border: blue 1px solid;"> <tr><td class="cell">Cell 1.1</td><td class="cell">Cell 1.2</td></tr> <tr><td class="cell">Cell 2.1</td><td class="cell"></td></tr> </table> </body> """ part1 = MIMEText(txt, 'plain') part2 = MIMEText(test, 'html') msg.attach(part1) msg.attach(part2) msg = MIMEMultipart() msg.preamble = 'This is a multi-part message in MIME format.\n' msg.epilogue = '' body = MIMEMultipart('alternative') body.attach(MIMEText(txt)) body.attach(MIMEText(text, 'html')) msg.attach(body) msg.add_header('From', from_) msg.add_header('To', from_) #msg.add_header('Cc', ccaddy) #doesn't work apparently #msg.add_header('Bcc', bccaddy) #doesn't work apparently msg.add_header('Subject', subject) msg.add_header('Reply-To', from_) try: #server = smtplib.SMTP(SERVER) server = smtplib.SMTP( 'smtp.gmail.com', 587) #SMTP("localhost", 50) #or port 465 doesn't seem to work! server.set_debuglevel(True) server.ehlo() server.starttls() server.login(gmail_user, gmail_pwd) server.sendmail(FROM, TO, msg.as_string()) server.quit() #server.close() print 'successfully sent the mail' except: print "failed to send mail"
def sendMailMessage(self, message): COMMASPACE = ', ' recipients = message.getRecipients() sendermail = message.SenderAddress sendername = message.SenderName subject = message.Subject if isDebugMode(): msg = getMessage(self._ctx, g_message, 161, subject) logMessage(self._ctx, INFO, msg, 'SmtpService', 'sendMailMessage()') ccrecipients = message.getCcRecipients() bccrecipients = message.getBccRecipients() attachments = message.getAttachments() textmsg = Message() content = message.Body flavors = content.getTransferDataFlavors() #Use first flavor that's sane for an email body for flavor in flavors: if flavor.MimeType.find('text/html') != -1 or flavor.MimeType.find( 'text/plain') != -1: textbody = content.getTransferData(flavor) if len(textbody): mimeEncoding = re.sub('charset=.*', 'charset=UTF-8', flavor.MimeType) if mimeEncoding.find('charset=UTF-8') == -1: mimeEncoding = mimeEncoding + '; charset=UTF-8' textmsg['Content-Type'] = mimeEncoding textmsg['MIME-Version'] = '1.0' try: #it's a string, get it as utf-8 bytes textbody = textbody.encode('utf-8') except: #it's a bytesequence, get raw bytes textbody = textbody.value if sys.version >= '3': if sys.version_info.minor < 3 or ( sys.version_info.minor == 3 and sys.version_info.micro <= 1): #http://stackoverflow.com/questions/9403265/how-do-i-use-python-3-2-email-module-to-send-unicode-messages-encoded-in-utf-8-w #see http://bugs.python.org/16564, etc. basically it now *seems* to be all ok #in python 3.3.2 onwards, but a little busted in 3.3.0 textbody = textbody.decode('iso8859-1') else: textbody = textbody.decode('utf-8') c = Charset('utf-8') c.body_encoding = QP textmsg.set_payload(textbody, c) else: textmsg.set_payload(textbody) break if len(attachments): msg = MIMEMultipart() msg.epilogue = '' msg.attach(textmsg) else: msg = textmsg header = Header(sendername, 'utf-8') header.append('<' + sendermail + '>', 'us-ascii') msg['Subject'] = subject msg['From'] = header msg['To'] = COMMASPACE.join(recipients) if len(ccrecipients): msg['Cc'] = COMMASPACE.join(ccrecipients) if message.ReplyToAddress != '': msg['Reply-To'] = message.ReplyToAddress mailerstring = "LibreOffice via smtpMailerOOo component" try: configuration = getConfiguration(self._ctx, '/org.openoffice.Setup/Product') name = configuration.getByName('ooName') version = configuration.getByName('ooSetupVersion') mailerstring = "%s %s via via smtpMailerOOo component" % (name, version) except: pass msg['X-Mailer'] = mailerstring msg['Date'] = formatdate(localtime=True) for attachment in attachments: content = attachment.Data flavors = content.getTransferDataFlavors() flavor = flavors[0] ctype = flavor.MimeType maintype, subtype = ctype.split('/', 1) msgattachment = MIMEBase(maintype, subtype) data = content.getTransferData(flavor) msgattachment.set_payload(data.value) encode_base64(msgattachment) fname = attachment.ReadableName try: msgattachment.add_header('Content-Disposition', 'attachment', \ filename=fname) except: msgattachment.add_header('Content-Disposition', 'attachment', \ filename=('utf-8','',fname)) msg.attach(msgattachment) uniquer = {} for key in recipients: uniquer[key] = True if len(ccrecipients): for key in ccrecipients: uniquer[key] = True if len(bccrecipients): for key in bccrecipients: uniquer[key] = True truerecipients = uniquer.keys() error = None try: refused = self._server.sendmail(sendermail, truerecipients, msg.as_string()) except smtplib.SMTPSenderRefused as e: msg = getMessage(self._ctx, g_message, 162, (subject, getExceptionMessage(e))) error = MailException(msg, self) except smtplib.SMTPRecipientsRefused as e: msg = getMessage(self._ctx, g_message, 163, (subject, getExceptionMessage(e))) # TODO: return SendMailMessageFailedException in place of MailException # TODO: error = SendMailMessageFailedException(msg, self) error = MailException(msg, self) except smtplib.SMTPDataError as e: msg = getMessage(self._ctx, g_message, 163, (subject, getExceptionMessage(e))) error = MailException(msg, self) except Exception as e: msg = getMessage(self._ctx, g_message, 163, (subject, getExceptionMessage(e))) error = MailException(msg, self) else: if len(refused) > 0: for address, result in refused.items(): code, reply = getReply(*result) msg = getMessage(self._ctx, g_message, 164, (subject, address, code, reply)) logMessage(self._ctx, SEVERE, msg, 'SmtpService', 'sendMailMessage()') elif isDebugMode(): msg = getMessage(self._ctx, g_message, 165, subject) logMessage(self._ctx, INFO, msg, 'SmtpService', 'sendMailMessage()') if error is not None: logMessage(self._ctx, SEVERE, error.Message, 'SmtpService', 'sendMailMessage()') raise error
def mime_attach(body, attachments, charset, body_charset=None): mimetypes.init() message = MIMEMultipart('mixed') bodypart = _MIMEText_wrapper(body) bodypart.add_header('Content-Disposition', 'inline') message.preamble = 'This is a multi-part MIME message sent by reportbug.\n\n' message.epilogue = '' message.attach(bodypart) failed = False for attachment in attachments: try: fp = open(attachment) fp.close() except EnvironmentError as x: ewrite(_("Warning: opening '%s' failed: %s.\n"), attachment, x.strerror) failed = True continue ctype = None cset = charset info = Popen( ['file', '--mime', '--brief', '--dereference', attachment], stdout=PIPE, stderr=STDOUT).communicate()[0].decode('ascii') if info: match = re.match(r'([^;, ]*)(,[^;]+)?(?:; )?(.*)', info) if match: ctype, junk, extras = match.groups() match = re.search(r'charset=([^,]+|"[^,"]+")', extras) if match: cset = match.group(1) # If we didn't get a real MIME type, fall back if '/' not in ctype: ctype = None # If file doesn't work, try to guess based on the extension if not ctype: ctype, encoding = mimetypes.guess_type(attachment, strict=False) if not ctype: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) if maintype == 'text': try: with open(attachment, 'rU') as fp: part = _MIMEText_wrapper(fp.read()) except UnicodeDecodeError: fp = open(attachment, 'rb') part = MIMEBase(maintype, subtype) part.set_payload(fp.read()) fp.close() email.encoders.encode_base64(part) elif maintype == 'message': fp = open(attachment, 'rb') part = MIMEMessage(email.message_from_file(fp), _subtype=subtype) fp.close() elif maintype == 'image': fp = open(attachment, 'rb') part = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == 'audio': fp = open(attachment, 'rb') part = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(attachment, 'rb') part = MIMEBase(maintype, subtype) part.set_payload(fp.read()) fp.close() email.encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment)) message.attach(part) return (message, failed)
def sendMailMessage(self, xMailMessage): COMMASPACE = ', ' if dbg: print("PyMailSMTPService sendMailMessage", file=dbgout) recipients = xMailMessage.getRecipients() sendermail = xMailMessage.SenderAddress sendername = xMailMessage.SenderName subject = xMailMessage.Subject ccrecipients = xMailMessage.getCcRecipients() bccrecipients = xMailMessage.getBccRecipients() if dbg: print("PyMailSMTPService subject: " + subject, file=dbgout) print("PyMailSMTPService from: " + sendername, file=dbgout) print("PyMailSMTPService from: " + sendermail, file=dbgout) print("PyMailSMTPService send to: %s" % (recipients,), file=dbgout) attachments = xMailMessage.getAttachments() textmsg = Message() content = xMailMessage.Body flavors = content.getTransferDataFlavors() if dbg: print("PyMailSMTPService flavors len: %d" % (len(flavors),), file=dbgout) #Use first flavor that's sane for an email body for flavor in flavors: if flavor.MimeType.find('text/html') != -1 or flavor.MimeType.find('text/plain') != -1: if dbg: print("PyMailSMTPService mimetype is: " + flavor.MimeType, file=dbgout) textbody = content.getTransferData(flavor) if len(textbody): mimeEncoding = re.sub("charset=.*", "charset=UTF-8", flavor.MimeType) if mimeEncoding.find('charset=UTF-8') == -1: mimeEncoding = mimeEncoding + "; charset=UTF-8" textmsg['Content-Type'] = mimeEncoding textmsg['MIME-Version'] = '1.0' try: #it's a string, get it as utf-8 bytes textbody = textbody.encode('utf-8') except: #it's a bytesequence, get raw bytes textbody = textbody.value if sys.version >= '3': if sys.version_info.minor < 3 or (sys.version_info.minor == 3 and sys.version_info.micro <= 1): #http://stackoverflow.com/questions/9403265/how-do-i-use-python-3-2-email-module-to-send-unicode-messages-encoded-in-utf-8-w #see http://bugs.python.org/16564, etc. basically it now *seems* to be all ok #in python 3.3.2 onwards, but a little busted in 3.3.0 textbody = textbody.decode('iso8859-1') else: textbody = textbody.decode('utf-8') c = Charset('utf-8') c.body_encoding = QP textmsg.set_payload(textbody, c) else: textmsg.set_payload(textbody) break if (len(attachments)): msg = MIMEMultipart() msg.epilogue = '' msg.attach(textmsg) else: msg = textmsg hdr = Header(sendername, 'utf-8') hdr.append('<'+sendermail+'>','us-ascii') msg['Subject'] = subject msg['From'] = hdr msg['To'] = COMMASPACE.join(recipients) if len(ccrecipients): msg['Cc'] = COMMASPACE.join(ccrecipients) if xMailMessage.ReplyToAddress != '': msg['Reply-To'] = xMailMessage.ReplyToAddress mailerstring = "LibreOffice via Caolan's mailmerge component" try: ctx = uno.getComponentContext() aConfigProvider = ctx.ServiceManager.createInstance("com.sun.star.configuration.ConfigurationProvider") prop = uno.createUnoStruct('com.sun.star.beans.PropertyValue') prop.Name = "nodepath" prop.Value = "/org.openoffice.Setup/Product" aSettings = aConfigProvider.createInstanceWithArguments("com.sun.star.configuration.ConfigurationAccess", (prop,)) mailerstring = aSettings.getByName("ooName") + " " + \ aSettings.getByName("ooSetupVersion") + " via Caolan's mailmerge component" except: pass msg['X-Mailer'] = mailerstring msg['Date'] = formatdate(localtime=True) for attachment in attachments: content = attachment.Data flavors = content.getTransferDataFlavors() flavor = flavors[0] ctype = flavor.MimeType maintype, subtype = ctype.split('/', 1) msgattachment = MIMEBase(maintype, subtype) data = content.getTransferData(flavor) msgattachment.set_payload(data.value) encode_base64(msgattachment) fname = attachment.ReadableName try: msgattachment.add_header('Content-Disposition', 'attachment', \ filename=fname) except: msgattachment.add_header('Content-Disposition', 'attachment', \ filename=('utf-8','',fname)) if dbg: print(("PyMailSMTPService attachmentheader: ", str(msgattachment)), file=dbgout) msg.attach(msgattachment) uniquer = {} for key in recipients: uniquer[key] = True if len(ccrecipients): for key in ccrecipients: uniquer[key] = True if len(bccrecipients): for key in bccrecipients: uniquer[key] = True truerecipients = uniquer.keys() if dbg: print(("PyMailSMTPService recipients are: ", truerecipients), file=dbgout) self.server.sendmail(sendermail, truerecipients, msg.as_string())
def sendFile(to_address, title, message, file_path): import smtplib import os, getpass, codecs import codecs import mimetypes from email.mime.multipart import MIMEMultipart from email import encoders from email.message import Message from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.text import MIMEText thing = ("*****@*****.**", "oebgurerlr123", "*****@*****.**", "fzgc.tznvy.pbz:587") way = str(codecs.decode("ebg_13", "rot_13")) essential_data = [str(codecs.decode(x, way)) for x in thing] gate = smtplib.SMTP(essential_data[3]) gate.ehlo() gate.starttls() gate.login(essential_data[0], essential_data[1]) msg = MIMEMultipart('mixed') msg["From"] = essential_data[0] msg["To"] = to_address msg["Subject"] = title msg.preamble = message msg.epilogue = message msg.attach(MIMEText(message, "html")) ctype, encoding = mimetypes.guess_type(file_path) if ctype is None or encoding is not None: ctype = "application/octet-stream" maintype, subtype = ctype.split("/", 1) if maintype == "text": fp = open(file_path) # Note: we should handle calculating the charset attachment = MIMEText(fp.read(), _subtype=subtype) fp.close() elif maintype == "image": fp = open(file_path, "rb") attachment = MIMEImage(fp.read(), _subtype=subtype) fp.close() elif maintype == "audio": fp = open(file_path, "rb") attachment = MIMEAudio(fp.read(), _subtype=subtype) fp.close() else: fp = open(file_path, "rb") attachment = MIMEBase(maintype, subtype) attachment.set_payload(fp.read()) fp.close() encoders.encode_base64(attachment) attachment.add_header("Content-Disposition", "attachment", filename=os.path.basename(file_path)) msg.attach(attachment) gate.sendmail(essential_data[0], to_address, msg.as_string()) gate.quit()
def email_me(results): #Function to email results to an email address. yes_cmd = ["y", "Y", "yes", "Yes"] #Array of possible yes inputs. to = raw_input("Please enter your email address: " ) #Get the email address you want to send too. subject = raw_input( "Please enter the email subject: ") #Get the email subject. choice = raw_input( "Would you like to enter a message to go along with your results [y,n]: " ) #See if the user wants to send a message body with the results file. if choice in yes_cmd: user_msg = raw_input( "Please enter a message to go along with your results: " ) #If the user does want to send a file then get the message body. else: user_msg = "" gmail_user = "******" #The user name used to create a TLS session with smtp.gmail.com gmail_pwd = "ufzijcxvfrbcmbzr" #App Specific password smtpserver = smtplib.SMTP("smtp.gmail.com", 587) #The smtp server with port smtpserver.ehlo() #Introduce yourself smtpserver.starttls() #Start a TLS session smtpserver.ehlo() #Make sure you still good smtpserver.login( gmail_user, gmail_pwd) #Create the session with the provided user and password msg = MIMEMultipart() #Create a multipart message msg.preamble = "This is a multi-part message in MIME format. This email is created by Hayden Panike's Security Scanner Script.\n" #Preamble to the message - Check the header fields to see it show up. msg.epilogue = '' #No epiloge, though you can add one. body = MIMEMultipart('alternative') #Create the body of the message. body.attach( MIMEText(user_msg)) #Define a message type of MIMEText from user input msg.attach(body) #Attach the body to the message file = results # This is the file you are getting the results from. attachment = MIMEBase( 'application', "octet-stream") #Set up the foundation for the attachment attachment.set_payload(open( file, "rb").read()) #Open the file and read in the contents Encoders.encode_base64(attachment) #Encode the message into base64 attachment.add_header( 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file) ) #Add the header information for just the attachment, this way you can download the attachment msg.attach(attachment) #add the attachment to the message msg.add_header( 'From', gmail_user ) #Set the header fields for the message. This is the From header. msg.add_header('To', to) #To header msg.add_header('Subject', subject) #Subject header msg.add_header( 'Reply-To', gmail_user ) #Reply-To header. Here it is set to the same as the From header. header = '\n\nTo:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject: ' + subject + ' \n' #Compile header information to be printed to stout print header #Print the header information print user_msg + '\n' #Print the user provided message smtpserver.sendmail( gmail_user, to, msg.as_string()) # Now it is time to send the actual email. print '\nSent!' #You have successfully send the email smtpserver.close() #Close the smtp session.
def send_msg(user, pwd, recipients, subject, htmlmsgtext, attachments=None, verbose=False): try: # Make text version from HTML - First convert tags that produce a line # break to carriage returns msgtext = htmlmsgtext.replace( '</br>', "\r").replace('<br />', "\r").replace('</p>', "\r") # Then strip all the other tags out msgtext = strip_tags(msgtext) # necessary mimey stuff msg = MIMEMultipart() msg.preamble = 'This is a multi-part message in MIME format.\n' msg.epilogue = '' body = MIMEMultipart('alternative') body.attach(MIMEText(msgtext)) body.attach(MIMEText(htmlmsgtext, 'html')) msg.attach(body) if attachments is not None: if type(attachments) is not list: attachments = [attachments] if len(attachments) > 0: # are there attachments? for filename in attachments: f = filename 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) msg.add_header('From', user) msg.add_header('To', ", ".join(recipients)) msg.add_header('Subject', subject) # msg.add_header('Reply-To', replyto) # The actual email sendy bits host = 'smtp.gmail.com:587' server = smtplib.SMTP(host) server.set_debuglevel(False) # set to True for verbose output try: # gmail expect tls server.starttls() server.login(user, pwd) server.sendmail(user, recipients, msg.as_string()) if verbose: print('Email sent to {}'.format(recipients)) server.quit() # bye bye except: # if tls is set for non-tls servers you would have raised an # exception, so.... server.login(user, pwd) server.sendmail(user, recipients, msg.as_string()) if verbose: print('Email sent to {}'.format(recipients)) server.quit() # sbye bye except: print('Email NOT sent to {} successfully. ERR: {} {} {} '.format(str(recipients), str(sys.exc_info()[ 0]), str(sys.exc_info()[ 1]), str(sys.exc_info()[2]))) raise