def send_mail(send_from, send_to, subject, text, files=None, server="smtp"): assert isinstance(send_to, list) msg = MIMEMultipart( From=send_from, To=COMMASPACE.join(send_to), Date=formatdate(localtime=True), Subject=subject ) msg['Subject'] = subject msg['To'] = COMMASPACE.join(send_to) msg['From'] = send_from msg.attach(MIMEText(text)) for f in files or []: with open(f, "rb") as fil: msg.attach(MIMEApplication( fil.read(), Content_Disposition='attachment; filename="tinypass.csv"', Name='tinypass.csv', )) smtp = smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def __init__(self, from_, to, subject, message, message_type='plain', attachments=None, cc=None, bcc=None, message_encoding='us-ascii', multi_to=False, multi_cc=False, multi_bcc=False, multi_attach=False): self.email = MIMEMultipart() self.message = message self.email['From'] = from_ if not multi_to: self.email['To'] = to else: self.email['To'] = COMMASPACE.join(to) self.email['Subject'] = subject self.email['subject'] = subject # Case Sensitive Email-Readers if cc is not None: if not multi_cc: self.email['Cc'] = cc else: self.email['Cc'] = COMMASPACE.join(cc) if bcc is not None: if not multi_bcc: self.email['bcc'] = bcc else: self.email['bcc'] = COMMASPACE.join(bcc) text = MIMEText(message, message_type, message_encoding) self.email.attach(text) if attachments is not None: if multi_attach: for filename in attachments: self.attach(filename) else: self.attach(attachments)
def send_mail(): assert type(server) == dict assert type(to) == list assert type(files) == list assert type(cc) == list msg = MIMEMultipart() msg['From'] = fro msg['Subject'] = subject msg['To'] = COMMASPACE.join(to) msg['Cc'] = COMMASPACE.join(cc) msg['Date'] = formatdate(localtime=True) msg.attach(MIMEText(text)) for perfile in files: part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data try: part.set_payload(open(perfile,'rb').read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(perfile)) msg.attach(part) except IOError: print "The files path is not aviable!" smtp = smtplib.SMTP(server['name']) smtp.login(server['user'], server['passwd']) smtp.sendmail(fro, to, msg.as_string()) for cmail in cc: if cmail in to: continue smtp.sendmail(fro, cmail, msg.as_string()) smtp.close()
def sendmail(self, send_from, send_to, copy_to, subject, text, files=None, server="localhost"): msg = MIMEMultipart() msg.add_header("From", send_from) msg.add_header("Date", formatdate(localtime=True)) msg.add_header("To", COMMASPACE.join(send_to)) msg.add_header("CC", COMMASPACE.join(copy_to)) msg.add_header("Subject", subject) msg.attach(MIMEText(text)) for f in files or []: if os.path.isfile(f): with open(f, "rb") as fil: part = MIMEBase('application', "octet-stream") part.set_payload(fil.read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f) ) msg.attach(part) fil.close() smtp = smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def create_message(self, subject, from_, to, content, cc=None, bcc=None, type='plain', mpart_type='mixed', attachments=()): """Sends an e-mail using the mail section configuration of the application. Parameters: * `subject` -- the subject of the mail, * `from_` -- the sender, * `to` -- the receiver or list of receivers, * `content` -- the content of the mail, * `cc` -- the eventual CC or list of CC, * `bcc` -- the eventual BCC or list of BCC, * `type` -- the eventual type of the email, either `'plain'` or `'html'`. * `mpart_type` -- the eventual custom ``MIMEMultipart`` type ('mixed' or 'related') (defaults to mixed) * `attachments` -- the eventual list of attachments to add """ # converts recipients to list and provide an empty list for None to = [to] if is_string(to) else to cc = [cc] if is_string(cc) else (cc or []) bcc = [bcc] if is_string(bcc) else (bcc or []) # always adds the hidden recipients if self.hidden_recipients: bcc += self.hidden_recipients # creates the message envelop msg = MIMEMultipart(mpart_type) msg['Subject'] = subject msg['Date'] = formatdate(localtime=True) if self.reply_to: msg['From'] = self.reply_to msg['Reply-to'] = from_ else: msg['From'] = from_ msg['To'] = COMMASPACE.join(to) if cc: msg['Cc'] = COMMASPACE.join(cc) # attaches the mail content if isinstance(content, unicode): content = content.encode('UTF-8') msg.attach(MIMEText(content, type, _charset='UTF-8')) # eventually completes the message with attachments for attachment in attachments: self.add_file_attachment(msg, *attachment) # log the email logger = log.get_logger('.' + __name__) logger.debug('Sending mail: from=%r, to=%r, cc=%r, bcc=%r, subject=%r', from_, to, cc, bcc, subject) logger.debug('Mail content:\n' + content) return msg
def send_mail(subject, text, send_to=SEND_TO, cc=CC, bcc=BCC, files=None): msg = MIMEMultipart() msg['From'] = formataddr(("ResultBot", USERNAME)) msg['To'] = COMMASPACE.join(send_to) if type(send_to) is list else send_to msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject if cc: msg['Cc'] = COMMASPACE.join(cc) if type(cc) is list else cc send_to += [msg['Cc']] if bcc: bcc = COMMASPACE.join(bcc) if type(bcc) is list else bcc send_to += [bcc] msg.attach(MIMEText(text)) # Attach files to email for f in files or []: with open(f, "rb") as fil: part = MIMEApplication( fil.read(), Name=basename(f) ) attachment = 'attachment; filename="%s"' % basename(f) part['Content-Disposition'] = attachment msg.attach(part) smtp = smtplib.SMTP(EMAIL_SMTP) # smtp initialization 1 smtp.ehlo() # smtp initialization 2 smtp.starttls() # smtp initialization 3 send(smtp, send_to, msg)
def sendEmail(send_from, send_to, subject, text, cc_to = [], files = [], server = "192.168.42.14"): assert type(send_to) == list assert type(files) == list msg = MIMEMultipart() msg.set_charset("utf-8") msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) if cc_to: assert type(cc_to) == list msg['cc'] = COMMASPACE.join(cc_to) send_to.extend(cc_to) msg['Date'] = formatdate(localtime = True) msg['Subject'] = subject.replace("\n", ' ') msg.attach(MIMEText(text)) for f in files: part = MIMEBase('application', "octet-stream") if isinstance(f, basestring): part.set_payload(open(f, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % Header(os.path.basename(f), 'utf-8')) elif hasattr(f, "file_path") and hasattr(f, "file_name"): part.set_payload(open(f.file_path, "rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % Header(f.file_name, 'utf-8')) msg.attach(part) smtp = smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def sendMail(subject, content, filespath = None) : try : # get server name from email sender r_server = re.compile(r'.*@(.*)(\.com|\.cn)') server_name = re.findall(r_server, sender) smtpserver = 'smtp.' + server_name[0][0] + '.com' smtpport = '25' username = sender # support attachment msg = MIMEMultipart() if filespath is not None : for singlefile in filespath : att = MIMEText(open(singlefile, 'rb').read(), 'base64') att['content-type'] = 'application/octet-stream' att['content-disposition'] = 'attachment;filename="%s"' % os.path.basename(singlefile) msg.attach(att) # mail body body = MIMEText(content) msg.attach(body) msg['from'] = sender msg['to'] = COMMASPACE.join(tolist) msg['cc'] = COMMASPACE.join(cclist) msg['subject'] = subject smtp = smtplib.SMTP() smtp.connect(smtpserver, smtpport) smtp.login(username, password) smtp.sendmail(sender, tolist, msg.as_string()) smtp.close() return True except Exception, errmsg : print errmsg return False
def send(to_email, content, cc_email=[], files=[], subject=''): """ @param to_email: list, emails to be sent to @param cc_email: list, emails to be copy to @param content: str, what to send @param files: list, the attachements to be sent @return response: str, { 'status':int 0:success,-1:failed. 'msgid': } """ logging.info("to_email=%s, cc_email=%s, content=%s", to_email, cc_email, content) #text = "From:%s\r\nTo:%s\r\nSubject:%s\r\n\r\n%s" #text = text % (ConfHelper.EMAIL_CONF.efrom, # email, # ConfHelper.EMAIL_CONF.subject, # content) #text = safe_utf8(text) if type(to_email) != list: to_email = [to_email,] msg = MIMEMultipart() msg['From'] = ConfHelper.EMAIL_CONF.efrom if subject: msg['Subject'] = subject else: msg['Subject'] = ConfHelper.EMAIL_CONF.subject msg['To'] = COMMASPACE.join(to_email) if cc_email: msg['Cc'] = COMMASPACE.join(cc_email) msg['Date'] = formatdate(localtime=True) msg.attach(MIMEText(safe_utf8(content), 'plain', 'utf-8')) for file in files: part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data part.set_payload(open(file, 'rb').read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(part) senderrs = None try: smtp = smtplib.SMTP() smtp.connect(ConfHelper.EMAIL_CONF.server) #smtp.ehlo() #smtp.starttls() smtp.login(ConfHelper.EMAIL_CONF.user, ConfHelper.EMAIL_CONF.password) senderrs = smtp.sendmail(ConfHelper.EMAIL_CONF.user, to_email+cc_email, msg.as_string()) smtp.quit() except Exception as e: senderrs = e.args[0] logging.error("Unknow error: %s", e.args) return senderrs
def renderMessage(self): msg = MIMEMultipart('alternative') msg[self.SUBJECT] = self.header[self.SUBJECT] msg[self.FROM] = self.getFullAddressList()[0] msg[self.TO] = COMMASPACE.join(self.header[self.TO]) msg[self.CC] = COMMASPACE.join(self.header[self.CC]) msg[self.REPLYTO] = common['replymailaddr'] partHtml = MIMEText(self.body, 'html') msg.attach(partHtml) self.message = msg
def build(self): """build message string""" # There can be only ONE ENCODING TO RULE THEM ALL!! MUWAHAHAHA subject, body = map( lambda x: UnicodeDammit(x).unicode_markup, [self._subject, self._body] ) if self._embedded_images: msg = MIMEMultipart('related') #msg = MIMEMultipart('mixed') else: msg = MIMEMultipart() msg['From'] = self._sender msg['To'] = COMMASPACE.join(self._recipients) msg['Date'] = formatdate(localtime=True) msg['Subject'] = Header(subject, 'utf-8') msg['Cc'] = COMMASPACE.join(self._carbon_copy) # NOTE: Bcc headers are not added to the message # The BCC'd recipients are added to the smtplib recipient # list when the mail is actually sent. # TODO: Send individual messages for each recipient on the BCC list # (and use the BCC header). This way the BCC'd recip's KNOW that they we're BCC'd. # Set character encoding so that viewing the source # of an HTML email is still readable to humans. charset.add_charset('utf-8', charset.SHORTEST) # add body of email msg.attach(MIMEText( body, _subtype=self._format, _charset='utf-8', )) # add attachments for f in self._attachments: msg.attach(_build_attachment(f)) for content_id, image_filename in self._embedded_images: fp = open(image_filename, 'rb') msgImage = MIMEImage(fp.read()) fp.close() # Define the image's ID as referenced above msgImage.add_header('Content-ID', '<{0}>'.format(content_id)) msg.attach(msgImage) return msg.as_string()
def send(self, to, subject, body, cc=None, attachs=(), mimetype='text/plain', charset=None, _callback=None): if attachs: msg = MIMEMultipart() else: msg = MIMENonMultipart(*mimetype.split('/', 1)) to = list(arg_to_iter(to)) cc = list(arg_to_iter(cc)) msg['From'] = self.mailfrom msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject rcpts = to[:] if cc: rcpts.extend(cc) msg['Cc'] = COMMASPACE.join(cc) if charset: msg.set_charset(charset) if attachs: msg.attach(MIMEText(body, 'plain', charset or 'us-ascii')) for attach_name, mimetype, f in attachs: part = MIMEBase(*mimetype.split('/')) part.set_payload(f.read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' \ % attach_name) msg.attach(part) else: msg.set_payload(body) if _callback: _callback(to=to, subject=subject, body=body, cc=cc, attach=attachs, msg=msg) if self.debug: logger.debug('Debug mail sent OK: To=%(mailto)s Cc=%(mailcc)s ' 'Subject="%(mailsubject)s" Attachs=%(mailattachs)d', {'mailto': to, 'mailcc': cc, 'mailsubject': subject, 'mailattachs': len(attachs)}) return dfd = self._sendmail(rcpts, msg.as_string()) dfd.addCallbacks(self._sent_ok, self._sent_failed, callbackArgs=[to, cc, subject, len(attachs)], errbackArgs=[to, cc, subject, len(attachs)]) reactor.addSystemEventTrigger('before', 'shutdown', lambda: dfd) return dfd
def send_mail(send_from, send_to, subject, text, files=None, reply_to=None, cc_to=None, bcc_to=None, server="localhost",SSL=False,date=None,references=None,inreplyto=None): if files is None: files = [] if reply_to is not None: assert isinstance(reply_to, list) if cc_to is None: cc_to = [] else: assert isinstance(cc_to, list) if bcc_to is None: bcc_to = [] else: assert isinstance(bcc_to, list) assert isinstance(send_to, list) assert isinstance(files, list) msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Cc'] = COMMASPACE.join(cc_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject if reply_to is not None: msg['Reply-To'] = COMMASPACE.join(reply_to) if date is not None: msg['Date'] = date.strftime("%a, %d %b %Y %H:%M:%S %z") if references is not None: msg['References'] = references if inreplyto is not None: msg['In-Reply-To'] = inreplyto msg.attach( MIMEText(text) ) for f in files: part = MIMEBase('application', "octet-stream") try: part.set_payload( open(f,"rb").read() ) except: pass else: encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) if SSL: smtp = smtplib.SMTP_SSL(server) else: smtp = smtplib.SMTP(server) smtp.sendmail(send_from, send_to+cc_to+bcc_to, msg.as_string()) smtp.close()
def send_mail(_from_, to_, subject, text, files=None, server=config.MAIL_SERVER, port=config.MAIL_SERVER_PORT): assert isinstance(to_, (list, tuple)) if files is None: files = [] msg = MIMEMultipart() msg['From'] = _from_ msg['To'] = COMMASPACE.join(to_) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach( MIMEText(text) ) for file_name, file_content in files: part = MIMEBase('application', "octet-stream") part.set_payload( file_content ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % file_name) msg.attach(part) smtp = smtplib.SMTP(server, port=port) smtp.sendmail(_from_, to_, msg.as_string() ) smtp.close()
def send(self, subject, html, smtp_server, images=[], zipfile=None): msg = MIMEMultipart() msg['From'] = '{0} <{1}>'.format(self.name, self.sender) msg['To'] = COMMASPACE.join(self.to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject if self.reply_to is not None: msg['Reply-To'] = self.reply_to msg.attach(MIMEText(html.encode('utf-8'), 'html', 'utf-8')) for i, image in enumerate(images): img = MIMEImage(image.read()) img.add_header('Content-ID', '<image{0}>'.format(i+1)) msg.attach(img) if zipfile: zip = MIMEBase('application', 'zip') zip.set_payload(zipfile.read()) encoders.encode_base64(zip) zip.add_header('Content-Disposition', 'attachment; filename=%s' % basename(zipfile)) msg.attach(zip) smtp = smtplib.SMTP(smtp_server) smtp.sendmail(self.sender, set(self.to+self.bcc), msg.as_string()) smtp.close()
def send_mail(subject, text, send_from="", dest_to=None, server="localhost", port=25, user="", passwd=""): """Send a email with a local or an external SMTP server. Arguments: (str) subject -- the mail's subject (str) text -- the message's text (str) send_from -- a sender's email address (default "") (list) dest_to -- a list of receivers' email addresses (default None) (str) server -- the smtp server (default "localhost") (int) port -- the smtp server port (default 25) (str) user -- the smtp server user (default "") (str) passwd --the smtp server password (default "") If "send_from" or "dest_to" are empty or None, then script user's mailbox is assumed instead. Useful for logging scripts """ local_email = "@".join([getpass.getuser(), socket.gethostname()]) send_from = send_from if send_from else local_email dest_to = dest_to if dest_to else [local_email] dest_to_addrs = COMMASPACE.join(dest_to) # receivers mails message = MIMEMultipart() message["Subject"] = subject message["From"] = send_from message["To"] = dest_to_addrs message["Date"] = formatdate(localtime=True) message.preamble = "You'll not see this in a MIME-aware mail reader.\n" message.attach(MIMEText(text)) # initialize the mail server smtp_server = smtplib.SMTP() # Connect to mail server try: smtp_server.connect(server, port) except socket.gaierror: print("mail error", "Wrong server, are you sure is correct?") except socket.error: print("mail error", "Server unavailable or connection refused") # Login in mail server if server != "localhost": try: smtp_server.login(user, passwd) except smtplib.SMTPAuthenticationError: print("mail error", "Authentication error") except smtplib.SMTPException: print("mail error", "No suitable authentication method") # Send mail try: smtp_server.sendmail(send_from, dest_to_addrs, message.as_string()) except smtplib.SMTPRecipientsRefused: print("mail error", "All recipients were refused." "Nobody got the mail.") except smtplib.SMTPSenderRefused: print("mail error", "The server didn’t accept the from_addr") except smtplib.SMTPDataError: print("mail error", "An unexpected error code, Data refused") # Disconnect from server smtp_server.quit()
def send_mail( send_to, subject, text, send_from=None, username=None, password=None, server='smtp.gmail.com', port=587, isTls=True): assert username is not None and password is not None if send_from is None: send_from = username if not isinstance(send_to, list): send_to = [send_to] message = MIMEMultipart() message['From'] = send_from message['To'] = COMMASPACE.join(send_to) message['Date'] = formatdate(localtime=True) message['Subject'] = subject message.attach(MIMEText(text)) smtp = smtplib.SMTP(server, port) if isTls: smtp.starttls() smtp.login(username, password) smtp.sendmail(send_from, send_to, msg=message.as_string()) smtp.quit()
def send_mail(send_from, send_to, subject, text, files=None, server="127.0.0.1"): assert isinstance(send_to, list) msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) for f in files or []: with open(f, "rb") as fil: part = MIMEApplication( fil.read(), Name=basename(f) ) # After the file is closed part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f) msg.attach(part) smtp = smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send_mail(files=None): send_to = read_config('default_send_report_to') send_from = read_config('default_send_report_from') subject = read_config('default_send_report_subject') text = read_config('default_send_report_text') print 'send test result to: ' + send_to msg = MIMEMultipart( From=send_from, To=COMMASPACE.join(send_to), Date=formatdate(localtime=True), Subject=subject ) msg.attach(MIMEText(text)) for f in files or []: with open(f, "rb") as fil: msg.attach(MIMEApplication( fil.read(), Content_Disposition='attachment; filename="%s"' % basename(f), Name=basename(f) )) smtp = smtplib.SMTP('localhost', 25) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def _convert_to_strings(list_of_strs): """ """ if isinstance(list_of_strs, (list, tuple)): result = COMMASPACE.join(list_of_strs) else: result = list_of_strs return _encode_str(result)
def send_mail(send_from, send_to, subject, text, files=None): assert isinstance(send_to, list) # build server in which the message will be sent to and how to attach the vide(text) msg = MIMEMultipart( From=send_from, To=COMMASPACE.join(send_to), Date=formatdate(localtime=True), Subject=subject ) msg.attach(MIMEText(text)) # attch the file to application for f in files or []: with open(f, "rb") as fil: msg.attach(MIMEApplication( fil.read(), Content_Disposition='attachment; filename="output.avi"', Name=basename(f) )) # choose the type of email and import the host's server data # add your email, password # this allows the program to know who to send the email too and what email to log into smtp = smtplib.SMTP("smtp.gmail.com", 587) smtp.starttls() smtp.login('*****@*****.**','moto4life') smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
def send_mail(sentfrom,to,subject,text,files=[],server='smtp.gmail.com:587', user = '******',password='******'): "generate automated email to a client using Gmail, by default colin's Gmail. " assert type(to) == list assert type(files) == list msg = MIMEMultipart() msg['From'] = sentfrom msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) for f in files: part = MIMEBase('application', "octet-stream") part.set_payload(open(f,'rb').read() ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) try: smtp_s = smtplib.SMTP(server) smtp_s.ehlo() smtp_s.starttls() smtp_s.login(user, password) smtp_s.sendmail(sentfrom, to, msg.as_string() ) smtp_s.close() print "successfully sent the mail !" except: print 'failed to send a mail '
def send_mail(server, fro, to, subject, text, files=[]): assert type(server) == dict assert type(fro) == str assert type(to) == list assert type(subject) == str assert type(text) == str assert type(files) == list msg = MIMEMultipart() msg['From'] = fro msg['Subject'] = subject msg['To'] = COMMASPACE.join(to) # COMMASPACE==',' msg['Date'] = formatdate(localtime=True) msg.attach(MIMEText(text, _subtype='html', _charset='utf-8')) me = "QA_CI_Report"+"<"+fro+">" print me for f in files: att = MIMEText(open(f, 'rb').read(), 'base64', 'gb2312') att["Content-Type"] = 'application/octet-stream' att.add_header("Content-Disposition", "attachment", filename=os.path.basename(f)) msg.attach(att) smtp = smtplib.SMTP(server['name'], server['port']) smtp.login(server['user'], server['passwd']) smtp.sendmail(me, to, msg.as_string()) smtp.close()
def encode_rfc2822_address_header(header_text): """If ``header_text`` contains non-ASCII characters, attempts to locate patterns of the form ``"Name" <address@domain>`` and replace the ``"Name"`` portion by the RFC2047-encoded version, preserving the address part untouched. """ header_text_utf8 = tools.ustr(header_text).encode('utf-8') header_text_ascii = try_coerce_ascii(header_text_utf8) if header_text_ascii: return header_text_ascii # non-ASCII characters are present, attempt to # replace all "Name" patterns with the RFC2047- # encoded version def replace(match_obj): name, email = match_obj.group(1), match_obj.group(2) name_encoded = str(Header(name, 'utf-8')) return "%s <%s>" % (name_encoded, email) header_text_utf8 = name_with_email_pattern.sub(replace, header_text_utf8) # try again after encoding header_text_ascii = try_coerce_ascii(header_text_utf8) if header_text_ascii: return header_text_ascii # fallback to extracting pure addresses only, which could # still cause a failure downstream if the actual addresses # contain non-ASCII characters return COMMASPACE.join(extract_rfc2822_addresses(header_text_utf8))
def send_mail(self, add_to, add_from, subject, password, message, attachment): to = re.findall(re.compile(r'([^;, ]+@[^,; ]+)[,]?'), add_to) smtp = 'smtp.' + re.match('.*@(.*)', add_from).group(1) user = re.match('(.*)@.*', add_from).group(1) msg = MIMEMultipart() for st in re.findall('([^,]+),?', attachment): attach = {} attach[st] = MIMEText(open(st, 'rb').read(), 'base64', 'gb2312') attach[st]["Content-Type"] = 'application/octet-stream' attach[st]["Content-Disposition"] = 'attachment; filename=' + re.match(r'.*[\\/]+(.*)', st).group( 1) msg.attach(attach[st]) msg['to'] = COMMASPACE.join(to) msg['from'] = add_from msg['subject'] = subject part1 = MIMEText(message, 'plain') msg.attach(part1) try: server = smtplib.SMTP() server.connect(smtp) server.login(user, password) server.sendmail(msg['from'], msg['to'], msg.as_string()) server.quit() self.status.set(u'发送成功') except Exception as e: print(str(e))
def send_mail(to, subject, text, files=[]): server = {} server['name'] = 'smtp.qq.com' server['user'] = '******' server['passwd'] = 'nameLR9969' assert type(server) == dict assert type(to) == list assert type(files) == list msg = MIMEMultipart() msg['From'] = server['user'] msg['Subject'] = subject msg['To'] = COMMASPACE.join(to) #COMMASPACE==', ' msg['Date'] = formatdate(localtime=True) msg.attach(MIMEText(text)) for file in files: part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data part.set_payload(open(file, 'rb'.read())) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(part) import smtplib smtp = smtplib.SMTP(server['name']) smtp.login(server['user'], server['passwd']) smtp.sendmail(server['user'], to, msg.as_string()) smtp.close()
def pack(sender_addr, recipient_addrs, subject, text=None, attachments=[], sender_name=None, html=None): if sender_name is None: sender_name = sender_addr sender_name = Header(sender_name, ENCODING).encode() msg_root = MIMEMultipart('mixed') msg_root['date'] = formatdate() msg_root['From'] = formataddr((sender_name, sender_addr)) msg_root['To'] = COMMASPACE.join(recipient_addrs) msg_root['Subject'] = Header(subject, ENCODING) msg_root.preamble = 'This is a multi-part message in MIME format.' msg_related = MIMEMultipart('related') msg_root.attach(msg_related) msg_alternative = MIMEMultipart('alternative') msg_related.attach(msg_alternative) if text: msg_text = MIMEText(text, 'plain', ENCODING) msg_alternative.attach(msg_text) if html: msg_html = MIMEText(html, 'html', ENCODING) msg_alternative.attach(msg_html) for child in format_attachments(attachments): msg_related.attach(child) return msg_root
def send_mail(send_from, send_to, subject, text, files=None): assert isinstance(send_to, list) server = 'mail.optisolutions.cz' USERNAME = "******" PASSWORD = "******" try: msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg.attach(MIMEText(text, "plain", "utf-8")) for f in files or []: if os.path.isfile(f): with open(f, "rb") as fil: msg.attach(MIMEApplication( fil.read(), Content_Disposition='attachment; filename="%s"' % basename(f), Name=basename(f) )) else: print "File %s doesn't exist."%f smtp = SMTP(server) smtp.login(USERNAME, PASSWORD) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close() except: print traceback.format_exc() # send_mail('*****@*****.**', ['*****@*****.**'], 'HOLA LOLA', 'UZ BUDU???',['asd'] )
def construct_mime_message(fromaddr, toaddrs, subject, files): msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = COMMASPACE.join(toaddrs) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject email_body = "" print "Enter message, end with ^D (Unix) or ^Z (Windows):" while 1: try: line = raw_input() except EOFError: break; if not line: break; email_body = email_body + line msg.attach(MIMEText(email_body)) for f in files or []: with open(f, "rb") as n_file: part = MIMEApplication( n_file.read(), Name = os.path.basename(f) ) part['Content-Disposition'] = 'attachment; filename="%s"' % os.path.basename(f) msg.attach(part) return msg.as_string()
def sendFile(_file,body): server = smtplib.SMTP('secure.emailsrvr.com') server.login('*****@*****.**', "Temporal") msg = MIMEMultipart( From='*****@*****.**', To=COMMASPACE.join(['*****@*****.**','*****@*****.**']), Date=formatdate(localtime=True), Subject='new products' ) text=body msg.attach(MIMEText(text)) # for f in files or []: with open(_file, "rb") as fil: msg.attach(MIMEApplication( fil.read(), Content_Disposition='attachment; filename="%s"' % basename(_file), Name=basename(_file) )) # smtp = smtplib.SMTP(server) server.sendmail('*****@*****.**', '*****@*****.**', msg.as_string()) server.close()
def send_email(client_emaillist, subject, file_path, emailattachments, log_path): """Send email via O365""" import base64 from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate import os from os.path import basename from shutil import copy import smtplib import re message = "\n\nPreparing email results\n" print message send_to = client_emaillist.split(";") send_from = '*****@*****.**' server = "smtp.office365.com" if 'SERVER_EMAIL_USERNAME' in os.environ: send_from = os.environ.get('SERVER_EMAIL_USERNAME') if 'SERVER_EMAIL' in os.environ: server = os.environ.get('SERVER_EMAIL') #https://stackoverflow.com/questions/3362600/how-to-send-email-attachments msg = MIMEMultipart() msg['From'] = send_from msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject from os import listdir from os.path import isfile, join, exists msgbody = subject + "\n\n" if not emailattachments: msgbody += "Attachments disabled: Result files can be accessed on the import client.\n\n" # Send To Admin Only unless there is a csv file which means there was at least a load attempt and not a system failure sendTo_AdminOnly = True sendTo_AdminAddress = "*****@*****.**" for sendToEmail in send_to: if re.search("501commons", sendToEmail, re.IGNORECASE): sendTo_AdminAddress = sendToEmail break if file_path: onlyfiles = [join(file_path, f) for f in listdir(file_path) if isfile(join(file_path, f))] msgbody += "Log Directory: {}\n\n".format(log_path) for file_name in onlyfiles: if contains_data(file_name) and ".sent" not in file_name: msgbody += "\t{}, with {} rows\n".format(basename(file_name), file_linecount(file_name)) if emailattachments or (contains_error(subject) and "log" in file_name.lower()) or contains_error(file_name.lower()): if "csv" in file_name: sendTo_AdminOnly = False with open(file_name, "rb") as file_name_open: part = MIMEApplication( file_name_open.read(), Name=basename(file_name) ) # After the file is closed part['Content-Disposition'] = 'attachment; filename="%s"' % basename(file_name) msg.attach(part) # Rename file so do not attached again sent_file = join(file_path, file_name) filename, file_extension = os.path.splitext(sent_file) sent_file = "{}.sent{}".format(filename, file_extension) if exists(sent_file): os.remove(sent_file) os.rename(file_name, sent_file) #Save copy to log directory copy(sent_file, log_path) # Check if sending email only to the Admin if sendTo_AdminOnly: msg['To'] = sendTo_AdminAddress else: msg['To'] = COMMASPACE.join(send_to) import time msgbody += "\n\n501 Commons ETL Version: %s\n\n" % format(time.ctime(os.path.getmtime(join(file_path, '..\\..\\..\\importer.py')))) print msgbody msg.attach(MIMEText(msgbody)) server = smtplib.SMTP(server, 587) server.starttls() server_password = '******' if 'SERVER_EMAIL_PASSWORD' in os.environ: server_password = os.environ.get('SERVER_EMAIL_PASSWORD') if 'SERVER_EMAIL_PASSWORDOVERRIDE' in os.environ: server_password = os.environ.get('SERVER_EMAIL_PASSWORDOVERRIDE') server.login(send_from, base64.b64decode(server_password)) text = msg.as_string() server.sendmail(send_from, send_to, text) server.quit() message = "\nSent email results\n" print message
def sendMail(cls, sender, recipients, subject, body, filesList=[], recipients_cc=[], recipients_bcc=[]): """ Parameters: 1. sender (str): Email address or name to be specified as the sender. 2. recipients (str): Comma separated email addresses for "to". 3. subject (str): Subject of the email. 4. body (str): Body of the email. 5. filesList (str): List of file paths to attach in the email. 6. recipients_cc (str): Comma separated email addresses for "cc". 7. recipients_bcc (str): Comma separated email addresses for "bcc". Return: 1. returnValue (bool): success/failure 2. returnError (str): error if sending email failed. """ returnValue = True returnError = '' # Append the sender's machine name to the end of the email. body = ''.join([ body, '\n', 'This is an automated message from "{0}"'.format(platform.node()) ]) # Create the multi-part email message msg = MIMEMultipart() msg['Subject'] = subject msg['From'] = sender msg['To'] = COMMASPACE.join(recipients) msg['Cc'] = COMMASPACE.join(recipients_cc) msg['Bcc'] = COMMASPACE.join(recipients_bcc) msg.attach(MIMEText(body)) for eachFile in filesList: try: part = MIMEBase('application', "octet-stream") part.set_payload(open(eachFile, "rb").read()) Encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(eachFile)) msg.attach(part) except Exception: logger.debug(traceback.format_exc()) logger.warning( 'Could not attach file to email: {0}'.format(eachFile)) # Create connection to the SMTP server and send the email try: server = smtplib.SMTP('qcmail1.qualcomm.com') except Exception: logger.debug(traceback.format_exc()) returnValue = False returnError = sys.exc_info()[1] else: server.starttls() try: server.sendmail(sender, recipients + recipients_cc + recipients_bcc, msg.as_string()) except Exception: logger.debug(traceback.format_exc()) returnValue = False returnError = sys.exc_info()[1] server.quit() return returnValue, returnError
def send(self, subject, send_from='', dest_to='', mail_server='localhost', server_user='', server_pass=''): """Send a email with the log. Arguments: (str) send_from -- a sender's email address (default '') (str or list) dest_to -- a list of receivers' email addresses ('') (str) subject -- the mail's subject (str) mail_server -- the smtp server (default 'localhost') (str) server_user -- the smtp server user (default '') (str) server_pass --the smtp server password (default '') If 'send_from' or 'dest_to' are empty or None, then script user's mailbox is assumed instead. Useful for loggin scripts """ local_email = '@'.join([getpass.getuser(), socket.gethostname()]) if not send_from: send_from = local_email if not dest_to: dest_to = [local_email] dest_to_addrs = COMMASPACE.join(dest_to) # receivers mails message = MIMEMultipart() message['Subject'] = '{0} - {1}'.format(subject, time.strftime('%A %x, %X')) message['From'] = send_from message['To'] = dest_to_addrs message['Date'] = formatdate(localtime=True) message.preamble = "You'll not see this in a MIME-aware mail reader.\n" message.attach(MIMEText(self.__log)) # initialize the mail server server = smtplib.SMTP() # Connect to mail server try: server.connect(mail_server) except socket.gaierror: self.list('mail error', 'Wrong server, are you sure is correct?') except socket.error: self.list('mail error', 'Server unavailable or connection refused') # Login in mail server if mail_server != 'localhost': try: server.login(server_user, server_pass) except smtplib.SMTPAuthenticationError: self.list('mail error', 'Authentication error') except smtplib.SMTPException: self.list('mail error', 'No suitable authentication method') # Send mail try: server.sendmail(send_from, dest_to_addrs, message.as_string()) except smtplib.SMTPRecipientsRefused: self.list('mail error', 'All recipients were refused.' 'Nobody got the mail.') except smtplib.SMTPSenderRefused: self.list('mail error', 'The server didn’t accept the from_addr') except smtplib.SMTPDataError: self.list('mail error', 'An unexpected error code, Data refused') # Disconnect from server server.quit()
def main(): ''' main provides the argparse part of the the entire collector script which is quite nice to have as it explains everything, how to operate the script, etc. It uses flags in order to indicate what should be done. This is especially useful when the script is called outside of a python IDE, which allows for everything to function from the command line. ''' # What is displayed when help is called parser = argparse.ArgumentParser( epilog='Written by Jason Ho; [email protected]', formatter_class=argparse.RawDescriptionHelpFormatter, description=textwrap.dedent('''\ Email Sender -------------------------------------------------------------- This script can be used as both a command line argument script or used as an individual module that is needed for different scripts. Since it is used so much, it was a good idea to just port this into a script of its own. The email object either is instantialized and called with its methods to send emails while editing the contents of the email using other methods in the class. The email object can also be called as a command line argument using the correct flags to automatically input what the user wants to do. Note: Everything can be done as command line arguments, manually in the console using the --manual flag (-m) or just by doing a module call. ''')) parser.add_argument( '-p', '--filepath', type=str, help='Attachment filepath for email. Full filepath needed.') parser.add_argument( '-f', '--fromemail', type=str, help='Attachment filename for email. Full filepath needed.') parser.add_argument('-t', '--toemail', action='append', help='Add as many emails to notify. Each email added' + 'from command line must be preceded by -e') parser.add_argument('-s', '--subject', type=str, help='Subject of the email to be sent out') parser.add_argument('-b', '--body', type=str, help='Body of the message that will be sent in email.') parser.add_argument( '-m', '--manual', action='store_true', help='Takes input rather than using command line arguments') # parses out the arguments from the command line call args = parser.parse_args() e = Email_Distributor() if args.manual != True: # Checking if file path exists if args.filepath != None: e.file_path = args.filepath # Checking if from email exists if args.fromemail != None: e.from_add = args.fromemail else: print('Missing a from email. This is required to work correctly.') print('\n Here is how to use the program correctly.') parser.print_help() # Checking if to email exists if args.toemail != None: e.to_add = COMMASPACE.join(args.toemail) print(type(e.to_add)) else: print('Missing a to email. This is required to work correctly.') print('\n Here is how to use the program correctly.') parser.print_help() # Checking if subject exists if args.subject != None: e.sub = args.subject else: print('Missing a subject. This is required to work correctly.') print('Here is how to use the program correctly.\n') parser.print_help() # Checking if body exists if args.body != None: e.body = args.body else: e.is_body_empty() print('Since no body was added, one was automatically generated.') if (e.to_add != None and e.from_add != None and e.sub != None): print(str(e)) e.send_mail() # If lazy flag was passed else: print('\nYou have entered the manual input mode for the email sender.') print( 'The script will prompt for the following information: from address' + ', to address, subject, body, and optional filepath.') # Asking for inputs for from email, to email, subject, body and optional # filepath e.from_add = input('Please input a from address: ') # To Address to_email = [] loop_variable = True while loop_variable: em = input('Please input a to address: ') to_email.append(em) # Check if want to add another email add = input('Add another email address to send to? (yes/no): ') if add == 'no': loop_variable = False e.to_add = COMMASPACE.join(to_email) # Subject e.sub = input('Please input the subject for email: ') # Body e.body = input('Please input the body for the email: ') # Filepath i = input('Add a file path to send? (yes/no): ') if i == 'yes': e.file_path = input('Input full file path here: ') print(str(e)) c = input('Is this information correct? (yes/no): ') print('\n') if c != 'yes': sys.exit(0) else: e.send_mail()
def update_recv(self, recv): del self.msg["To"] if isinstance(recv, basestring): self.msg["To"] = recv elif isinstance(recv, list): self.msg["To"] = COMMASPACE.join(recv)
datecsv = yesterday.strftime('%m_%d_%Y') print(datecsv) SUBJECT = '{}'.format(datecsv+"_IgniteEvents") FILENAME = 'attachthisfile.csv' FILEPATH = './attachthisfile.csv' MY_EMAIL = '*****@*****.**' MY_PASSWORD = '******' # TO_EMAIL = ['*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**'] TO_EMAIL = ['*****@*****.**'] SMTP_SERVER = 'smtp.gmail.com' SMTP_PORT = 587 msg = MIMEMultipart() msg['From'] = MY_EMAIL msg['To'] = COMMASPACE.join(TO_EMAIL) msg['Subject'] = SUBJECT BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print(BASE_DIR) pathtofile = BASE_DIR + str("/target/Data_"+yesterday.strftime('%m_%d_%Y')+'.csv') FILENAME = str("Data_"+yesterday.strftime('%m_%d_%Y')+'.csv') part = MIMEBase('application', "octet-stream") part.set_payload(open(pathtofile, "rb").read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment', filename=FILENAME) # or # part.add_header('Content-Disposition', 'attachment; filename="attachthisfile.csv"') msg.attach(part)
def build_email(self, email_from, email_to, subject, body, email_cc=None, email_bcc=None, reply_to=False, attachments=None, message_id=None, references=None, object_id=False, subtype='plain', headers=None, body_alternative=None, subtype_alternative='plain'): """Constructs an RFC2822 email.message.Message object based on the keyword arguments passed, and returns it. :param string email_from: sender email address :param list email_to: list of recipient addresses (to be joined with commas) :param string subject: email subject (no pre-encoding/quoting necessary) :param string body: email body, of the type ``subtype`` (by default, plaintext). If html subtype is used, the message will be automatically converted to plaintext and wrapped in multipart/alternative, unless an explicit ``body_alternative`` version is passed. :param string body_alternative: optional alternative body, of the type specified in ``subtype_alternative`` :param string reply_to: optional value of Reply-To header :param string object_id: optional tracking identifier, to be included in the message-id for recognizing replies. Suggested format for object-id is "res_id-model", e.g. "12345-crm.lead". :param string subtype: optional mime subtype for the text body (usually 'plain' or 'html'), must match the format of the ``body`` parameter. Default is 'plain', making the content part of the mail "text/plain". :param string subtype_alternative: optional mime subtype of ``body_alternative`` (usually 'plain' or 'html'). Default is 'plain'. :param list attachments: list of (filename, filecontents) pairs, where filecontents is a string containing the bytes of the attachment :param list email_cc: optional list of string values for CC header (to be joined with commas) :param list email_bcc: optional list of string values for BCC header (to be joined with commas) :param dict headers: optional map of headers to set on the outgoing mail (may override the other headers, including Subject, Reply-To, Message-Id, etc.) :rtype: email.message.Message (usually MIMEMultipart) :return: the new RFC2822 email message """ email_from = email_from or tools.config.get('email_from') assert email_from, "You must either provide a sender address explicitly or configure "\ "a global sender address in the server configuration or with the "\ "--email-from startup parameter." # Note: we must force all strings to to 8-bit utf-8 when crafting message, # or use encode_header() for headers, which does it automatically. headers = headers or {} # need valid dict later email_cc = email_cc or [] email_bcc = email_bcc or [] body = body or u'' email_body = ustr(body) email_text_part = MIMEText(email_body, _subtype=subtype, _charset='utf-8') msg = MIMEMultipart() if not message_id: if object_id: message_id = tools.generate_tracking_message_id(object_id) else: message_id = make_msgid() msg['Message-Id'] = encode_header(message_id) if references: msg['references'] = encode_header(references) msg['Subject'] = encode_header(subject) msg['From'] = encode_rfc2822_address_header(email_from) del msg['Reply-To'] if reply_to: msg['Reply-To'] = encode_rfc2822_address_header(reply_to) else: msg['Reply-To'] = msg['From'] msg['To'] = encode_rfc2822_address_header(COMMASPACE.join(email_to)) if email_cc: msg['Cc'] = encode_rfc2822_address_header( COMMASPACE.join(email_cc)) if email_bcc: msg['Bcc'] = encode_rfc2822_address_header( COMMASPACE.join(email_bcc)) msg['Date'] = formatdate() # Custom headers may override normal headers or provide additional ones for key, value in headers.items(): msg[pycompat.to_native(ustr(key))] = encode_header(value) if subtype == 'html' and not body_alternative: # Always provide alternative text body ourselves if possible. text = html2text.html2text(email_body) alternative_part = MIMEMultipart(_subtype="alternative") alternative_part.attach( MIMEText(text, _charset='utf-8', _subtype='plain')) alternative_part.attach(email_text_part) msg.attach(alternative_part) elif body_alternative: # Include both alternatives, as specified, within a multipart/alternative part alternative_part = MIMEMultipart(_subtype="alternative") body_alternative_ = ustr(body_alternative) alternative_body_part = MIMEText(body_alternative_, _subtype=subtype_alternative, _charset='utf-8') alternative_part.attach(alternative_body_part) alternative_part.attach(email_text_part) msg.attach(alternative_part) else: msg.attach(email_text_part) if attachments: for (fname, fcontent, mime) in attachments: filename_rfc2047 = encode_header_param(fname) if mime and '/' in mime: maintype, subtype = mime.split('/', 1) part = MIMEBase(maintype, subtype) else: part = MIMEBase('application', "octet-stream") # The default RFC2231 encoding of Message.add_header() works in Thunderbird but not GMail # so we fix it by using RFC2047 encoding for the filename instead. part.set_param('name', filename_rfc2047) part.add_header('Content-Disposition', 'attachment', filename=filename_rfc2047) part.set_payload(fcontent) encoders.encode_base64(part) msg.attach(part) return msg
def _convert_to_strings(list_of_strs): if isinstance(list_of_strs, (list, tuple)): result = COMMASPACE.join(list_of_strs) else: result = list_of_strs return _encode_str(result)
def format_addresses(addr): return COMMASPACE.join(addr) if isinstance(addr, list) else addr
def send(self, to, subject, body, cc=None, attachs=(), mimetype='text/plain', charset=None, _callback=None): if attachs: msg = MIMEMultipart() else: msg = MIMENonMultipart(*mimetype.split('/', 1)) to = list(arg_to_iter(to)) cc = list(arg_to_iter(cc)) msg['From'] = self.mailfrom msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject rcpts = to[:] if cc: rcpts.extend(cc) msg['Cc'] = COMMASPACE.join(cc) if charset: msg.set_charset(charset) if attachs: msg.attach(MIMEText(body, 'plain', charset or 'us-ascii')) for attach_name, mimetype, f in attachs: part = MIMEBase(*mimetype.split('/')) part.set_payload(f.read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment', filename=attach_name) msg.attach(part) else: msg.set_payload(body) if _callback: _callback(to=to, subject=subject, body=body, cc=cc, attach=attachs, msg=msg) if self.debug: logger.debug( 'Debug mail sent OK: To=%(mailto)s Cc=%(mailcc)s ' 'Subject="%(mailsubject)s" Attachs=%(mailattachs)d', { 'mailto': to, 'mailcc': cc, 'mailsubject': subject, 'mailattachs': len(attachs) }) return dfd = self._sendmail(rcpts, msg.as_string().encode(charset or 'utf-8')) dfd.addCallbacks(self._sent_ok, self._sent_failed, callbackArgs=[to, cc, subject, len(attachs)], errbackArgs=[to, cc, subject, len(attachs)]) reactor.addSystemEventTrigger('before', 'shutdown', lambda: dfd) return dfd
user='******', password='******', host='scraper-test.cmuq9py90auz.us-east-1.rds.amazonaws.com', port='5432') cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor) today = date.today() fromaddr = "*****@*****.**" toaddrs = [ "*****@*****.**", "*****@*****.**", "*****@*****.**", "*****@*****.**" ] # must be a list subject = "Regression Service Summary Report: {0}".format(today.isoformat()) msg = MIMEMultipart(From=fromaddr, To=COMMASPACE.join(toaddrs), Date=formatdate(localtime=True)) msg['Subject'] = subject msg.preamble = subject header_content = "Possibly Changed Sites:\n" sites_changed = "" email_content = "\nWeb console:\nhttp://regression.contentanalyticsinc.com:8080/regression/\nlogin: tester\npassword: password\n\n" websites = [ "walmart", "jcpenney", "kohls", "macys", "target", "levi", "dockers", "samsclub", "drugstore", "amazon" ] ''' for website in websites: if website == "amazon": sql_sample_products = "select id, url, website, json, not_a_product from console_urlsample where website like '{0}'".format("amazon%")
def load(self, mail_file_name): ''' 从文件中读入并生成邮件头和体 { "from": "", "aliasName": "", "to": [], "cc": [], "bcc": [], "subject": "", "content": "", "embedRes": [ { "resName": "", "file": "", "type": "" } ], "attachments": [ { "type": "", "file": "" } ] } ''' mail_obj = json.loads(open(mail_file_name, "r").read()) self.msg = MIMEMultipart(_subtype="related") sender = "" sender_alias = "" if "from" in mail_obj: sender = mail_obj if "aliasName" in mail_obj: sender_alias = mail_obj["aliasName"] if sender != "": self.msg["From"] = self.__format_addr(u'%s <%s>' % (sender_alias, sender)) if "to" in mail_obj and len(mail_obj["to"]) > 0: self.msg["To"] = COMMASPACE.join(mail_obj["to"]) if "cc" in mail_obj and len(mail_obj["cc"]) > 0: self.msg["Cc"] = COMMASPACE.join(mail_obj["cc"]) if "bcc" in mail_obj and len(mail_obj["bcc"]) > 0: self.msg["Bcc"] = COMMASPACE.join(mail_obj["bcc"]) self.msg["Subject"] = Header(mail_obj["subject"], 'utf-8').encode() self.msg.attach(MIMEText(mail_obj["content"], 'html', 'utf-8')) if len(mail_obj["embedRes"]) > 0: for res in mail_obj["embedRes"]: with open(res["file"], 'rb') as f: if res["type"] == "img": img = MIMEImage(f.read()) img.add_header('Content-ID', res["resName"]) self.msg.attach(img) else: pass if len(mail_obj["attachments"]) > 0: for res in mail_obj["attachments"]: res_file = os.path.basename(res["file"]).encode('gbk') with open(res["file"], 'rb') as f: doc = MIMEText(f.read(), "base64", "gb2312") doc["Content-Type"] = "application/octet-stream" doc["Content-Disposition"] = 'attachment; filename="' + res_file + '"' self.msg.attach(doc)
def send( self, to, subject, body, cc=None, attachs=(), mimetype="text/plain", charset=None, _callback=None, ): from twisted.internet import reactor if attachs: msg = MIMEMultipart() else: msg = MIMENonMultipart(*mimetype.split("/", 1)) to = list(arg_to_iter(to)) cc = list(arg_to_iter(cc)) msg["From"] = self.mailfrom msg["To"] = COMMASPACE.join(to) msg["Date"] = formatdate(localtime=True) msg["Subject"] = subject rcpts = to[:] if cc: rcpts.extend(cc) msg["Cc"] = COMMASPACE.join(cc) if charset: msg.set_charset(charset) if attachs: msg.attach(MIMEText(body, "plain", charset or "us-ascii")) for attach_name, mimetype, f in attachs: part = MIMEBase(*mimetype.split("/")) part.set_payload(f.read()) Encoders.encode_base64(part) part.add_header("Content-Disposition", "attachment", filename=attach_name) msg.attach(part) else: msg.set_payload(body) if _callback: _callback(to=to, subject=subject, body=body, cc=cc, attach=attachs, msg=msg) if self.debug: logger.debug( "Debug mail sent OK: To=%(mailto)s Cc=%(mailcc)s " 'Subject="%(mailsubject)s" Attachs=%(mailattachs)d', { "mailto": to, "mailcc": cc, "mailsubject": subject, "mailattachs": len(attachs), }, ) return dfd = self._sendmail(rcpts, msg.as_string().encode(charset or "utf-8")) dfd.addCallbacks( callback=self._sent_ok, errback=self._sent_failed, callbackArgs=[to, cc, subject, len(attachs)], errbackArgs=[to, cc, subject, len(attachs)], ) reactor.addSystemEventTrigger("before", "shutdown", lambda: dfd) return dfd
def send_mail(manually, objConcurso, objPessoa, subject, text, send_to=None, send_to_cc=None, send_to_bcc=None, files=None): send_from = EmailAuthentication().USERNAME password = EmailAuthentication().PWD if send_to is not None: if type(send_to) is list: assert isinstance(send_to, list) else: send_to = [send_to] assert isinstance(send_to, list) if send_to_cc is not None: if type(send_to_cc) is list: assert isinstance(send_to_cc, list) else: send_to_cc = [send_to_cc] assert isinstance(send_to_cc, list) if send_to_bcc is not None: if type(send_to_bcc) is list: assert isinstance(send_to_bcc, list) else: send_to_bcc = [send_to_bcc] assert isinstance(send_to_bcc, list) msg = MIMEMultipart() msg['From'] = send_from if send_to is not None: msg['To'] = COMMASPACE.join(send_to) if send_to_cc is not None: msg['Cc'] = COMMASPACE.join(send_to_cc) if send_to is None: send_to = [] send_to += send_to_cc if send_to_bcc is not None: if send_to is None: send_to = [] send_to += send_to_bcc msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text, 'html')) for f in files or []: with open(f, "rb") as fil: part = MIMEApplication(fil.read(), Name=basename(f)) part[ 'Content-Disposition'] = 'attachment; filename="%s"' % basename( f) msg.attach(part) smtp = smtplib.SMTP('smtp.gmail.com', 587) smtp.starttls() smtp.login(send_from, password) result = False try: print("Enviando e-mail..") smtp.sendmail(send_from, send_to, msg.as_string()) result = True print("E-mail Enviado com sucesso!") except Exception as e: print("Ocorreu um arro ao enviar o e-mail.") print("Erro: {0}".format(e.args)) # raise e finally: smtp.close() emailSent = EmailSent( 0, 0, objPessoa.id, objPessoa.email, EmailAuthentication().MINE_EMAIL, '', 0, "Serviço Agendado Lotofacil - {0}".format(objPessoa.name), text, _pesLotCTRL.RecuperaJogoPessoa(objConcurso.concurse, objPessoa.id, True)['totalBilhetes'], objConcurso.concurse, result, manually) print("Gravando log do envio de e-mail!") _emaCTRL.GravaLog(emailSent) return result
csvlist.append(file) # print(csvlist) name = '*****@*****.**' passw = '499!ismylovE' sender = name #receiver = ['*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**'] receiver = ['*****@*****.**'] smtpsrv = "smtp.office365.com" SUBJECT = 'MMCIX Daily Status ({0})'.format( datetime.now().strftime('%Y-%m-%d-%H:%M:%S')) FILEPATH = os.path.dirname(os.path.abspath(__file__)) msg = MIMEMultipart() msg['From'] = sender msg['To'] = COMMASPACE.join(receiver) msg['Subject'] = SUBJECT body = """ Daily Status job schedule are processed successfully. """ body = MIMEText(body) msg.attach(body) part = MIMEBase('application', "octet-stream") part.set_payload(open(FILEPATH, "rb").read()) encoders.encode_base64(part) for f in csvlist: part.add_header('Content-Disposition', 'attachment', filename=f) # or msg.attach(part) smtpserver = smtplib.SMTP(smtpsrv, 587) smtpserver.ehlo() smtpserver.starttls()
def send(self): if not self.ses: raise Exception, 'No connection found' if (self.text and not self.html and not self.attachments) or \ (self.html and not self.text and not self.attachments): return self.ses.send_email(self._source, self.subject, self.text or self.html, self._to_addresses, self._cc_addresses, self._bcc_addresses, format='text' if self.text else 'html') else: if not self.attachments: message = MIMEMultipart('alternative') message['Subject'] = self.subject message['From'] = self._source if isinstance(self._to_addresses, (list, tuple)): message['To'] = COMMASPACE.join(self._to_addresses) else: message['To'] = self._to_addresses message.attach(MIMEText(self.text, 'plain')) message.attach(MIMEText(self.html, 'html')) else: raise NotImplementedError, 'SES does not currently allow ' + \ 'messages with attachments.' # message = MIMEMultipart() # # message_alt = MIMEMultipart('alternative') # # if self.text: # message_alt.attach(MIMEText(self.text, 'plain')) # if self.html: # message_alt.attach(MIMEText(self.html, 'html')) # # message.attach(message_alt) # # message['Subject'] = self.subject # message['From'] = self._source # if isinstance(self._to_addresses, (list, tuple)): # message['To'] = COMMASPACE.join(self._to_addresses) # else: # message['To'] = self._to_addresses # message.preamble = 'You will not see this in a MIME-aware mail reader.\n' # print 'message: ', message.as_string() # for attachment in self.attachments: # # Guess the content type based on the file's extension. Encoding # # will be ignored, although we should check for simple things like # # gzip'd or compressed files. # ctype, encoding = mimetypes.guess_type(attachment) # if ctype is None or encoding is not None: # # No guess could be made, or the file is encoded (compressed), so # # use a generic bag-of-bits type. # ctype = 'application/octet-stream' # maintype, subtype = ctype.split('/', 1) # if maintype == 'text': # fp = open(attachment) # # Note: we should handle calculating the charset # part = MIMEText(fp.read(), _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() # # Encode the payload using Base64 # encoders.encode_base64(part) # # Set the filename parameter # part.add_header('Content-Disposition', 'attachment', filename=attachment) # message.attach(part) return self.ses.send_raw_email(self._source, message.as_string(), destinations=self._to_addresses)
result.to_json("./results_data/time2") # compress results and send it by email os.system('say "computation finished"') os.system('zip -r results.zip results_data') send_from = '*****@*****.**' send_to = ['*****@*****.**'] subject = "computation finished for computing times" text = "results available \n" files = "./results.zip" msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Subject'] = subject msg.attach(MIMEText(text)) with open(files, "rb") as fil: part = MIMEApplication( fil.read(), Name="results.zip" ) part[ 'Content-Disposition'] = 'attachment; filename="results.zip"' msg.attach(part) try: smtp = smtplib.SMTP('smtp.upmc.fr')
def main(): """mail loop to execute data and attach to mail and send the mail """ #use automationassets to get credentials cred = automationassets.get_automation_credential("xxxx") username = cred["username"] password = cred["password"] driver = '{SQL Server}' #declare database connection conn = pyodbc.connect( 'DRIVER={0};SERVER=xxxxx;DATABASE=xxxxx;UID={1};PWD={2}'.format( driver, username, password)) cursor = conn.cursor() #execute [App].[RptStagClientFileStatus] procedure and write to csv file cursor.execute( "SET NOCOUNT ON; EXEC [App].[RptStagClientFileStatus] active") results_activeclient = cursor.fetchall() activecsv = datetime.now().strftime('activeclientfile-%Y-%m-%d-%H-%M.csv') with open(activecsv, 'wb') as fp: a = csv.writer(fp, delimiter=',') a.writerow(['CreateDate', 'Institution', 'Status', 'RecCount']) a.writerows(results_activeclient) #execute [App].[RptStagClientFileStatus] procedure and write to csv file cursor.execute( "SET NOCOUNT ON; EXEC [App].[RptStagClientFileStatus] writeoff") results_writeoff = cursor.fetchall() writeoffcsv = datetime.now().strftime('writeoff-%Y-%m-%d-%H-%M.csv') with open(writeoffcsv, 'wb') as fp: a = csv.writer(fp, delimiter=',') a.writerow(['CreateDate', 'Institution', 'Status', 'RecCount']) a.writerows(results_writeoff) #execute [App].[RptMFILog] procedure and write to csv file cursor.execute("SET NOCOUNT ON; EXEC [App].[RptMFILog]") results_mfilog = cursor.fetchall() mficsv = datetime.now().strftime('mfilog-%Y-%m-%d-%H-%M.csv') with open(mficsv, 'wb') as fp: a = csv.writer(fp, delimiter=',') a.writerow(['CreateDate', 'MFILog']) a.writerows(results_mfilog) #execute [Client].[GetAccountStatistics] procedure and write to csv file cursor.execute("SET NOCOUNT ON; EXEC [Client].[GetAccountStatistics]") results_percent = cursor.fetchall() #create row_as_list for encoding process (changed pyodbc.Row to list data type) row_as_list = [x for x in results_percent] rawlist = list() #create rawlist to build manually list of pyodbc row for easily write to csv for x in row_as_list: lst2 = list() for y in x: res = encode(y) lst2.append(res) rawlist.append(lst2) percentcsv = datetime.now().strftime('80percent-%Y-%m-%d-%H-%M.csv') with codecs.open(percentcsv, 'wb', encoding='utf-8') as fp: a = csv.writer(fp, delimiter=',') header = [ 'MFIName', 'ClientCountAtSignUp', 'UploadCountLastMonth', 'UploadCount', '80%', 'Status' ] a.writerow(header) a.writerows(rawlist) #Execute [App].[RptDailyStatusSummary] and show in body of mail cursor.execute("SET NOCOUNT ON; EXEC [App].[RptDailyStatusSummary]") summary = cursor.fetchall() #get summary data to show in mail's body sum1 = strip_data(summary[0]) sum2 = strip_data(summary[1]) sum3 = strip_data(summary[2]) sum4 = strip_data(summary[3]) sum5 = strip_data(summary[4]) sum6 = strip_data(summary[5]) sum7 = strip_data(summary[6]) csvlist = list() for file in glob.glob("*.csv"): csvlist.append(file) #credentials of sender's address cred1 = automationassets.get_automation_credential("RunBookEmailCred") name = cred1["username"] passw = cred1["password"] sender = name receiver = xxxxxxxx smtpsrv = "smtp.office365.com" SUBJECT = 'MMCIX Daily Status ({0})'.format( datetime.now().strftime('%Y-%m-%d-%H:%M:%S')) #get the location of the script FILEPATH = os.path.dirname(os.path.abspath(__file__)) #build mail's body msg = MIMEMultipart() msg['From'] = sender msg['To'] = COMMASPACE.join(receiver) msg['Subject'] = SUBJECT b1 = 'Daily Status job schedule are processed successfully.' b2 = 'Daily Status Summary' btle = 'Title, Record' body = """ {0} {1} {2} {3} {4} {5} {6} {7} {8} {9} Regards, MMCIX Team """.format(b1, b2, btle, sum1, sum2, sum3, sum4, sum5, sum6, sum7) body = MIMEText(body) msg.attach(body) #attach multiple csv in csvlist for f in csvlist: #file_path = os.path.join(FILEPATH, f) part = MIMEBase('application', "octet-stream") part.set_payload(open(f, "rb").read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment', filename=f) # or msg.attach(part) smtpserver = smtplib.SMTP(smtpsrv, 587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo smtpserver.login(sender, passw) smtpserver.sendmail(sender, receiver, msg.as_string()) print 'Successfully sent mail' smtpserver.close()
def send(self, to, subject, body, cc=None, attachs=(), mimetype='text/plain', charset=None, _callback=None): from twisted.internet import reactor if attachs: msg = MIMEMultipart() else: msg = MIMENonMultipart(*mimetype.split('/', 1)) to = list(arg_to_iter( to)) #arg_to_iter 就是如果是None就返回None 如果是__iter__就返回本身 其他返回[传入参数] cc = list(arg_to_iter(cc)) msg['From'] = self.mailfrom msg['To'] = COMMASPACE.join(to) msg['Date'] = formatdate(localtime=True) #默认就是当前时间戳 msg['Subject'] = subject rcpts = to[:] #deepcopy if cc: rcpts.extend(cc) msg['Cc'] = COMMASPACE.join(cc) if charset: msg.set_charset(charset) if attachs: msg.attach(MIMEText(body, 'plain', charset or 'us-ascii')) for attach_name, mimetype, f in attachs: part = MIMEBase(*mimetype.split('/')) part.set_payload(f.read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment', filename=attach_name) msg.attach(part) else: msg.set_payload(body) if _callback: _callback(to=to, subject=subject, body=body, cc=cc, attach=attachs, msg=msg) if self.debug: logger.debug( 'Debug mail sent OK: To=%(mailto)s Cc=%(mailcc)s ' 'Subject="%(mailsubject)s" Attachs=%(mailattachs)d', { 'mailto': to, 'mailcc': cc, 'mailsubject': subject, 'mailattachs': len(attachs) }) return #debug以后 就不进行真的邮件发送了 ## 这里的dfd是我们self._sendmail返回的deferred对象 dfd = self._sendmail(rcpts, msg.as_string().encode(charset or 'utf-8')) # deferred常用的回调添加方法 dfd.addCallbacks( callback=self._sent_ok, errback=self._sent_failed, callbackArgs=[to, cc, subject, len(attachs)], errbackArgs=[to, cc, subject, len(attachs)], ) #添加trigger 让他这个在结束前发出 reactor.addSystemEventTrigger('before', 'shutdown', lambda: dfd) return dfd
def send_email(sender, cc, bcc, subject, body, attachments=None): """ Send an email. All arguments should be Unicode strings (plain ASCII works as well). Only the real name part of sender and recipient addresses may contain non-ASCII characters. The email will be properly MIME encoded and delivered though SMTP to 172.17.0.1. This is easy to change if you want something different. The charset of the email will be the first one out of US-ASCII, ISO-8859-1 and UTF-8 that can represent all the characters occurring in the email. """ recipients = cc + bcc # combined recipients # Header class is smart enough to try US-ASCII, then the charset we # provide, then fall back to UTF-8. header_charset = "ISO-8859-1" # We must choose the body charset manually for body_charset in "US-ASCII", "ISO-8859-1", "UTF-8": try: body.encode(body_charset) except UnicodeError: pass else: break # Split real name (which is optional) and email address parts sender_name, sender_addr = parseaddr(sender) parsed_cc = [parseaddr(rec) for rec in cc] parsed_bcc = [parseaddr(rec) for rec in bcc] # We must always pass Unicode strings to Header, otherwise it will # use RFC 2047 encoding even on plain ASCII strings. unicode_parsed_cc = [] for recipient_name, recipient_addr in parsed_cc: recipient_name = str(Header(str(recipient_name), header_charset)) # Make sure email addresses do not contain non-ASCII characters recipient_addr = recipient_addr.encode("ascii") recipient_addr = recipient_addr.decode() unicode_parsed_cc.append((recipient_name, recipient_addr)) unicode_parsed_bcc = [] for recipient_name, recipient_addr in parsed_bcc: recipient_name = str(Header(str(recipient_name), header_charset)) # Make sure email addresses do not contain non-ASCII characters recipient_addr = recipient_addr.encode("ascii") recipient_addr = recipient_addr.decode() unicode_parsed_bcc.append((recipient_name, recipient_addr)) # Create the message ('plain' stands for Content-Type: text/plain) msg = MIMEMultipart() msg["CC"] = COMMASPACE.join([ formataddr((recipient_name, recipient_addr)) for recipient_name, recipient_addr in unicode_parsed_cc ]) msg["BCC"] = COMMASPACE.join([ formataddr((recipient_name, recipient_addr)) for recipient_name, recipient_addr in unicode_parsed_bcc ]) msg["Subject"] = Header(str(subject), header_charset) msg["FROM"] = "*****@*****.**" msg.attach(MIMEText(body.encode(body_charset), "plain", body_charset)) # Add attachments if isinstance(attachments, dict): for fname in attachments: part = MIMEBase("application", "octet-stream") part.set_payload(attachments[fname]) encoders.encode_base64(part) part.add_header("Content-Disposition", 'attachment; filename="%s"' % fname) msg.attach(part) # Send the message via SMTP to docker host smtp_url = "smtp://%s:25" % get_container_host_ip() print("smtp_url : %s", smtp_url) smtp = SMTP(get_container_host_ip()) smtp.sendmail(sender, recipients, msg.as_string()) smtp.quit()
def send_email(client_emaillist, subject, file_path, emailattachments, log_path): """Send email via O365""" message = "\n\nPreparing email results\n" print message send_to = client_emaillist.split(";") send_from = '*****@*****.**' server = "smtp.office365.com" #https://stackoverflow.com/questions/3362600/how-to-send-email-attachments import base64 from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate import os from os.path import basename from shutil import copy import smtplib msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject from os import listdir from os.path import isfile, join, exists onlyfiles = [join(file_path, f) for f in listdir(file_path) if isfile(join(file_path, f))] msgbody = subject + "\n\n" if not emailattachments: msgbody += "Attachments disabled: Result files can be accessed on the import client.\n\n" msgbody += "Log Directory: {}\n\n".format(log_path) for file_name in onlyfiles: if contains_data(file_name) and ".sent" not in file_name: msgbody += "\t{}, with {} rows\n".format(basename(file_name), file_linecount(file_name)) if emailattachments or (contains_error(subject) and "log" in file_name.lower()) or contains_error(file_name.lower()): with open(file_name, "rb") as file_name_open: part = MIMEApplication( file_name_open.read(), Name=basename(file_name) ) # After the file is closed part['Content-Disposition'] = 'attachment; filename="%s"' % basename(file_name) msg.attach(part) # Rename file so do not attached again sent_file = join(file_path, file_name) filename, file_extension = os.path.splitext(sent_file) sent_file = "{}.sent{}".format(filename, file_extension) if exists(sent_file): os.remove(sent_file) os.rename(file_name, sent_file) #Save copy to log directory copy(sent_file, log_path) print msgbody msg.attach(MIMEText(msgbody)) server = smtplib.SMTP(server, 587) server.starttls() server_password = os.environ['SERVER_EMAIL_PASSWORD'] server.login(send_from, base64.b64decode(server_password)) text = msg.as_string() server.sendmail(send_from, send_to, text) server.quit() message = "\nSent email results\n" print message
write_to_log(log, 'Word banned: ' + word + ' Computer locked.') print('Gotcha') subprocess.check_call(["gnome-screensaver-command", "-l"]) print(phrase.segments(detailed=True)) write_to_log(log, 'Program terminated. ') #Append log.txt to history.txt log = open('log.txt', 'r') history = open('history.txt', 'a+') history.write(log.read()) #Send a message with the log.txt attached via gmail msg = MIMEMultipart() msg['From'] = email_info.get('user') msg['To'] = COMMASPACE.join(email_info.get('to')) time_text = time.strftime('[%l:%M%p %z on %b %d, %Y ] ') msg['Subject'] = 'Log ' + time_text msg.attach(MIMEText('')) with open('log.txt', "rb") as fil: part = MIMEApplication(fil.read(), Name=basename('log.txt')) part['Content-Disposition'] = 'attachment; filename="%s"' % basename( 'log.txt') msg.attach(part) server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() server.login(email_info.get('user'), email_info.get('password'))
def send_mail(send_from, send_to, subject, user_name, password, text='', html='', img='', files=[], cc_to=[], server="localhost", port=465, logger=LOGGER): """Send email with plain text or HTML text. :param list send_from: sender email address. :param list send_to: receiver emails address list. :param str subject: title of email. :param str user_name: user name of email account. :param str password: password of email account. :param str text: plain text to send. :param str html: HTML text to send. :param str img: image file path to send. :param list files: files list as attachement. :param list cc_to: cc emails address list. :param str server: email SMTP server IP or domain. :param int port: email SMTP server port. """ assert type(send_to) == list assert type(cc_to) == list assert type(files) == list # msg = MIMEMultipart('alternative') msg = MIMEMultipart('related') # msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['cc'] = COMMASPACE.join(cc_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject # Encapsulate the plain and HTML versions of the message body in an # 'alternative' part, so message agents can decide which they want to display. # msgAlternative = MIMEMultipart('alternative') # msg.attach(msgAlternative) if text != '': msg.attach(MIMEText(text, 'plain', 'utf-8')) if html != '': msg.attach(MIMEText(html, 'html', 'utf-8')) # imgf = r'/img/path/' if img != '': fp = open(img, 'rb') msgImage = MIMEImage(fp.read()) fp.close() msgImage.add_header('Content-ID', '<image1>') msgImage.add_header('Content-Disposition', 'inline', filename=img) msg.attach(msgImage) for f in files: part = MIMEBase('application', "octet-stream") # part.set_payload( open(f, "rb").read() ) part.set_payload(codecs.open(f, "rb").read()) encoders.encode_base64(part) # print(os.path.basename(f).encode('utf8')) # part.add_header('Content-Disposition', 'attachment', # filename=('utf8', '', os.path.basename(f).encode('utf8'))) part.add_header('Content-Disposition', 'attachment', filename=Header(os.path.basename(f), 'utf8').encode()) # part.add_header('Content-Disposition', 'attachment; filename=ss.xlsx') # print(os.path.basename(f)) msg.attach(part) try: smtp = smtplib.SMTP_SSL(server, port) smtp.login(user_name, password) smtp.sendmail(send_from, send_to, msg.as_string()) except Exception: # print('Error happened:\n', sys.exc_info()) if logger: logger.error('Error happened:\n', sys.exc_info()) return False smtp.close() return True
def create_message(sender, to, subject, message_text, attachment_paths=None): def __generate_msg_part(part): assert isinstance(part, dict) assert 'text' in part if 'type' not in part: msg_type = 'plain' else: msg_type = part['type'] mime_part = MIMEText(part['text'].encode('utf-8'), _subtype=msg_type, _charset='utf-8') return mime_part if not isinstance(to, list): to = [to] if message_text is None or isinstance(message_text, (unicode, str)): msgs = [MIMEText(message_text.encode('utf-8'), _charset='utf-8')] elif isinstance(message_text, dict): msgs = [__generate_msg_part(message_text)] elif isinstance(message_text, list): msgs = [ __generate_msg_part(message_part) for message_part in message_text ] else: raise TypeError( 'Types accepted for message_text: string, dict, or list of dicts') message = MIMEMultipart() message['to'] = COMMASPACE.join(to) message['from'] = sender message['subject'] = subject # separate part for text etc message_alt = MIMEMultipart('alternative') message.attach(message_alt) # html portions have to be under a separate 'related' part under 'alternative' part # sequence matters, text > related (html > inline image) > attachments. ascending priority # if message text is a list, it's providing alternatives. # eg. if both plain and html are available, Gmail will choose HTML over plain # attach text first (lower priority) for msg in msgs: if msg.get_content_subtype() == 'plain': message_alt.attach(msg) # create 'related' part if html is required content_msgs = filter( lambda x: x.get_content_subtype() == 'html' or x.get_content_maintype( ) == 'image', msgs) if len(content_msgs) > 0: message_related = MIMEMultipart('related') message_alt.attach(message_related) for msg in content_msgs: message_related.attach(msg) # different treatment if contains attachments if attachment_paths is not None: if isinstance(attachment_paths, str): attachment_paths = [attachment_paths] elif not isinstance(attachment_paths, list): raise TypeError( 'Invalid input. Only acceptable types are str and list objects' ) for file_path in attachment_paths: content_type, encoding = mimetypes.guess_type(file_path) if content_type is None or encoding is not None: content_type = 'application/octet-stream' main_type, sub_type = content_type.split('/', 1) with open(file_path, 'rb') as fp: if main_type == 'text': msg = MIMEText(fp.read(), _subtype=sub_type) elif main_type == 'image': msg = MIMEImage(fp.read(), _subtype=sub_type) else: msg = MIMEBase(main_type, sub_type) msg.set_payload(fp.read()) msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file_path)) message.attach(msg) return {'raw': base64.urlsafe_b64encode(message.as_string())}
def build_email( self, email_from, email_to, subject, body, email_cc=None, email_bcc=None, reply_to=False, attachments=None, message_id=None, references=None, object_id=False, subtype="plain", headers=None, body_alternative=None, subtype_alternative="plain", ): """ copy-pasted from odoo/addons/base/models/ir_mail_server.py::build_email """ ftemplate = "__image-%s__" fcounter = 0 attachments = attachments or [] pattern = re.compile(r'"data:image/png;base64,[^"]*"') pos = 0 new_body = "" body = body or "" while True: match = pattern.search(body, pos) if not match: break s = match.start() e = match.end() data = body[s + len('"data:image/png;base64,') : e - 1] new_body += body[pos:s] fname = ftemplate % fcounter fcounter += 1 attachments.append((fname, base64.b64decode(data))) new_body += '"cid:%s"' % fname pos = e new_body += body[pos:] body = new_body email_from = email_from or tools.config.get("email_from") assert email_from, ( "You must either provide a sender address explicitly or configure " "a global sender address in the server configuration or with the " "--email-from startup parameter." ) # Note: we must force all strings to to 8-bit utf-8 when crafting message, # or use encode_header() for headers, which does it automatically. headers = headers or {} # need valid dict later if not email_cc: email_cc = [] if not email_bcc: email_bcc = [] if not body: body = u"" email_body_utf8 = ustr(body).encode("utf-8") email_text_part = MIMEText(email_body_utf8, _subtype=subtype, _charset="utf-8") msg = MIMEMultipart() if not message_id: if object_id: message_id = tools.generate_tracking_message_id(object_id) else: message_id = make_msgid() msg["Message-Id"] = encode_header(message_id) if references: msg["references"] = encode_header(references) msg["Subject"] = encode_header(subject) msg["From"] = encode_rfc2822_address_header(email_from) del msg["Reply-To"] if reply_to: msg["Reply-To"] = encode_rfc2822_address_header(reply_to) else: msg["Reply-To"] = msg["From"] msg["To"] = encode_rfc2822_address_header(COMMASPACE.join(email_to)) if email_cc: msg["Cc"] = encode_rfc2822_address_header(COMMASPACE.join(email_cc)) if email_bcc: msg["Bcc"] = encode_rfc2822_address_header(COMMASPACE.join(email_bcc)) msg["Date"] = formatdate() # Custom headers may override normal headers or provide additional ones for key, value in headers.items(): msg[ustr(key).encode("utf-8")] = encode_header(value) if subtype == "html" and not body_alternative and html2text: # Always provide alternative text body ourselves if possible. text_utf8 = tools.html2text(email_body_utf8.decode("utf-8")).encode("utf-8") alternative_part = MIMEMultipart(_subtype="alternative") alternative_part.attach( MIMEText(text_utf8, _charset="utf-8", _subtype="plain") ) alternative_part.attach(email_text_part) msg.attach(alternative_part) elif body_alternative: # Include both alternatives, as specified, within a multipart/alternative part alternative_part = MIMEMultipart(_subtype="alternative") body_alternative_utf8 = ustr(body_alternative).encode("utf-8") alternative_body_part = MIMEText( body_alternative_utf8, _subtype=subtype_alternative, _charset="utf-8" ) alternative_part.attach(alternative_body_part) alternative_part.attach(email_text_part) msg.attach(alternative_part) else: msg.attach(email_text_part) if attachments: for (fname, fcontent) in attachments: filename_rfc2047 = encode_header_param(fname) part = MIMEBase("application", "octet-stream") # The default RFC2231 encoding of Message.add_header() works in Thunderbird but not GMail # so we fix it by using RFC2047 encoding for the filename instead. part.sudo().set_param("name", filename_rfc2047) part.add_header( "Content-Disposition", "attachment", filename=filename_rfc2047 ) part.add_header("Content-ID", "<%s>" % filename_rfc2047) # NEW STUFF part.set_payload(fcontent) encoders.encode_base64(part) msg.attach(part) return msg
def send_notification(self, event, alert, template_name, sender, recipients, recipients_cc=[], recipients_bcc=[], context={}): all_recipients = recipients + recipients_cc + recipients_bcc self.log.info( "Start trying to send notification to %s with event=%s of alert %s" % (str(all_recipients), event, alert)) mail_template = self.get_email_template(template_name) if mail_template != False: self.log.debug( "Found template file (%s). Ready to send notification." % json.dumps(mail_template)) # Parse html template with django try: # Parse body as django template template = self.env.get_template( mail_template['template_file']) content = template.render(context) #self.log.debug("Parsed message body. Context was: %s" % (json.dumps(context))) text_content = strip_tags(content) # Parse subject as django template subject_template = Template(source=mail_template['subject'], variable_start_string='$', variable_end_string='$') subject = subject_template.render(context) self.log.debug("Parsed message subject: %s" % subject) # Prepare message self.log.debug("Preparing SMTP message...") msgRoot = MIMEMultipart('related') msgRoot['Subject'] = subject msgRoot['From'] = sender msgRoot['Date'] = formatdate(localtime=True) smtpRecipients = [] msg = MIMEMultipart('alternative') msgRoot.attach(msg) #msg.preamble = text_content if len(recipients) > 0: smtpRecipients = smtpRecipients + recipients msgRoot['To'] = COMMASPACE.join(recipients) if len(recipients_cc) > 0: smtpRecipients = smtpRecipients + recipients_cc msgRoot['CC'] = COMMASPACE.join(recipients_cc) if len(recipients_bcc) > 0: smtpRecipients = smtpRecipients + recipients_bcc msgRoot['BCC'] = COMMASPACE.join(recipients_bcc) # Add message body if mail_template['content_type'] == "html": msg.attach(MIMEText(content, 'html')) else: msg.attach(MIMEText(text_content, 'plain')) # Add attachments if 'attachments' in mail_template and mail_template[ 'attachments'] != None and mail_template[ 'attachments'] != "": attachment_list = mail_template['attachments'].split(" ") self.log.debug( "Have to add attachments to this notification. Attachment list: %s" % json.dumps(attachment_list)) for attachment in attachment_list or []: local_file = os.path.join( os.environ.get('SPLUNK_HOME'), "etc", "apps", "alert_manager", "local", "templates", "attachments", attachment) default_file = os.path.join( os.environ.get('SPLUNK_HOME'), "etc", "apps", "alert_manager", "default", "templates", "attachments", attachment) attachment_file = None if os.path.isfile(local_file): attachment_file = local_file self.log.debug( "%s exists in local, using this one..." % attachment) else: self.log.debug( "%s not found in local folder, checking if there's one in default..." % attachment) if os.path.isfile(default_file): attachment_file = default_file self.log.debug( "%s exists in default, using this one..." % attachment) else: self.log.warn( "%s doesn't exist, won't add it to the message." % attachment) if attachment_file != None: ctype, encoding = mimetypes.guess_type( attachment_file) if ctype is None or encoding is not None: ctype = "application/octet-stream" maintype, subtype = ctype.split("/", 1) msgAttachment = None if maintype == "text": try: fp = open(attachment_file) # Note: we should handle calculating the charset msgAttachment = MIMEText(fp.read(), _subtype=subtype) finally: fp.close() elif maintype == "image": try: fp = open(attachment_file, "rb") msgAttachment = MIMEImage(fp.read(), _subtype=subtype) finally: fp.close() elif maintype == "audio": try: fp = open(attachment_file, "rb") msgAttachment = MIMEAudio(fp.read(), _subtype=subtype) finally: fp.close() else: try: fp = open(attachment_file, "rb") msgAttachment = MIMEBase(maintype, subtype) msgAttachment.set_payload(fp.read()) encoders.encode_base64(msgAttachment) finally: fp.close() if msgAttachment != None: msgAttachment.add_header( "Content-ID", "<" + basename(attachment_file) + "@splunk>") msgAttachment.add_header( "Content-Disposition", "attachment", filename=basename(attachment_file)) msgRoot.attach(msgAttachment) #self.log.debug("Mail message: %s" % msg.as_string()) #self.log.debug("Settings: %s " % json.dumps(self.settings)) self.log.debug("smtpRecipients: %s type: %s" % (smtpRecipients, type(smtpRecipients))) self.log.info("Connecting to mailserver=%s ssl=%s tls=%s" % (self.settings["MAIL_SERVER"], self.settings["EMAIL_USE_SSL"], self.settings["EMAIL_USE_TLS"])) if not self.settings["EMAIL_USE_SSL"]: s = smtplib.SMTP(self.settings["MAIL_SERVER"]) else: s = smtplib.SMTP_SSL(self.settings["MAIL_SERVER"]) if self.settings["EMAIL_USE_TLS"]: s.starttls() if len(self.settings["EMAIL_HOST_USER"]) > 0: s.login(str(self.settings["EMAIL_HOST_USER"]), str(self.settings["EMAIL_HOST_PASSWORD"])) self.log.info("Sending emails....") s.sendmail(sender, smtpRecipients, msgRoot.as_string().encode('utf-8')) s.quit() self.log.info("Notifications sent successfully") #except TemplateSyntaxError, e: # self.log.error("Unable to parse template %s. Error: %s. Continuing without sending notification..." % (mail_template['template_file'], e)) #except smtplib.SMTPServerDisconnected, e: # self.log.error("SMTP server disconnected the connection. Error: %s" % e) except socket.error, e: self.log.error( "Wasn't able to connect to mailserver. Reason: %s" % e) #except TemplateDoesNotExist, e: # self.log.error("Template %s not found in %s nor %s. Continuing without sending notification..." % (mail_template['template_file'], local_dir, default_dir)) except Exception as e: self.log.error( "Unable to send notification. Continuing without sending notification. Unexpected Error: %s" % (traceback.format_exc()))
def order_placed(): print("REQUEST RULE::") print(flask.request.url_rule) # Lookup user data = flask.request.get_json() order_data = data['data'] store_hash = "4atxht2sgv" store = db.session.query(Store).filter_by(store_hash=store_hash).first() # for key, value in data.items(): # Construct api client client = BigcommerceApi(client_id=client_id(), store_hash=store_hash, access_token=store.access_token) # Fetch a few orders order = client.Orders.get(order_data['id']) customer = client.Customers.get(order['customer_id']) print(order) print(customer) order_products = client.OrderProducts.all(parentid=order['id']) # todo: iterate order_shipping_address = client.OrderShippingAddresses.all(parentid=order['id'])[0] print(order_products) print(order_shipping_address) billing_address = order['billing_address'] datetime_created = datetime.strptime(order['date_created'], '%a, %d %b %Y %X +%f') order_date = datetime_created.strftime('%Y%m%d') order_due = (datetime_created + timedelta(days=1)).strftime('%Y%m%d') # todo: mapper un sku à une table sl_values_array = [] line_number = 1 for product in order_products: billing_address_street = ' '.join([billing_address['street_1'], billing_address['street_2']]) shipping_address_street = ' '.join([order_shipping_address['street_1'], order_shipping_address['street_2']]) sl_values = [ "BeerMyGuest", "Logistique", str(order['id']), order_date, order_due, (billing_address['last_name'] + ' ' + billing_address['first_name'])[:20], billing_address['company'][:40] if len(billing_address['company']) > 0 else "particulier", billing_address_street[:20], billing_address_street[20:40], billing_address_street[40:60], str(billing_address['zip'])[:15], billing_address['city'][:40], billing_address['state'][:40], billing_address['country'][:40], (billing_address['last_name'] + ' ' + billing_address['first_name'])[:40], str(billing_address['phone'])[:25], '', billing_address['email'][:100], (order_shipping_address['last_name'] + ' ' + order_shipping_address['first_name'])[:20], order_shipping_address['company'][:40] if len(order_shipping_address['company']) > 0 else "particulier", shipping_address_street[:20], shipping_address_street[20:40], shipping_address_street[40:60], str(order_shipping_address['zip'])[:15], order_shipping_address['city'][:40], order_shipping_address['state'][:40], order_shipping_address['country'][:40], (order_shipping_address['last_name'] + ' ' + order_shipping_address['first_name'])[:40], str(order_shipping_address['phone'])[:25], '', order_shipping_address['email'][:100], 'DPD', 'PREDICT', order['customer_message'][:100], str(line_number), # str(product['order_address_id'])[:20], str(product['sku'])[:20], str(product['quantity'])[:5], '', # unavailable in bigcommerce 'BigCommerce' ] sl_values_array.append(sl_values) line_number = line_number + 1 keys_string = '\t'.join(sl_keys()) values_strings_array = map(lambda values: '\t'.join(values), sl_values_array) values_string = '\n'.join(values_strings_array) file_data = '\n'.join([keys_string, values_string]) print(file_data) # send emails server = smtplib.SMTP('mail.infomaniak.com', 587) server.ehlo() server.starttls() server.ehlo() server.login("*****@*****.**", "Premium_Beer_2018") send_from = "*****@*****.**" send_to = ['*****@*****.**'] msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = "[StarLogistiqueManager] New Order " + str(order['id']) attachment_filename = "PREPBEERMYGUEST" + datetime_created.strftime('%Y%m%d%H%M') + ".txt" msg.attach(MIMEText("Veuillez trouver ci-joint la commande BeerMyGuest #" + str(order['id']) + " à traiter.")) part = MIMEApplication( file_data, Name=attachment_filename ) part['Content-Disposition'] = 'attachment; filename="%s"' % attachment_filename msg.attach(part) server.sendmail(send_from, send_to, msg.as_string()) server.close() # todo: fix double call return flask.Response('OK', status=200)
def send_mail(host, user, password, to_list, **kwargs): """ 发邮件 :param {string} host: 连接smtp服务器 :param {string} user: 登陆账号 :param {string} password: 登陆密码 :param {list} to_list: 收信人列表, 如: ["收件人1 <*****@*****.**>", "*****@*****.**"] :param {string} From: 收到信时显示的发信人设置,如:"测试邮件<*****@*****.**>" :param {string} Cc: 抄送人, 多人用英文逗号分开, 如:"[email protected], [email protected]" :param {string} BCc: 暗抄邮箱(有抄送效果,但抄送人列表不展示), 多人用英文逗号分开, 如:"[email protected], [email protected]" :param {string} Subject: 邮件主题 :param {string} html: HTML 格式的邮件正文内容 :param {string} text: 纯文本 格式的邮件正文内容(html格式的及纯文本格式的,只能传其中一个,以html参数优先) :param {list} files: 附件列表,需填入附件路径,如:["d:\\123.txt"] :return {bool}: 发信成功则返回 True,否则返回 False """ # 添加邮件内容 msg = MIMEMultipart() msg['Date'] = formatdate(localtime=True) # 发信人 from_address = str_util.to_unicode(kwargs.get('From')) msg['From'] = from_address # 邮件主题 Subject = kwargs.get('Subject') if Subject: msg['Subject'] = str_util.to_unicode(Subject) # 转编码,以免客户端看起来是乱码的 # 邮件正文内容 html = kwargs.get('html') text = kwargs.get('text') # HTML 格式的邮件正文内容 if html: html = str_util.to_str(html) msg.attach(MIMEText(html, _subtype='html', _charset='utf-8')) # 纯文本 格式的邮件正文内容 elif text: text = str_util.to_str(text) msg.attach(MIMEText(text, _subtype='plain', _charset='utf-8')) # 收信人列表 if isinstance(to_list, basestring): to_list = [to_list] assert type(to_list) == list to_address = [str_util.to_str(to) for to in to_list] msg['To'] = COMMASPACE.join( to_address) # COMMASPACE==', ' # 收件人邮箱, 多人逗号分开 # 抄送人, 多人用英文逗号分开 cc_address = kwargs.get('Cc') if cc_address: msg['Cc'] = str_util.to_str(cc_address) # 暗抄邮箱, 多人用英文逗号分开 bcc_address = kwargs.get('BCc') if bcc_address: msg['BCc'] = str_util.to_str(bcc_address) # 添加附件 if 'files' in kwargs: files = kwargs.get('files') or [] for file_path in files: # 文件路径 file_path = str_util.to_unicode(file_path) # 文件名(不包含路径) file_name = os.path.basename(file_path) disposition = str_util.to_str( u'attachment; filename="%s"') % str_util.to_str(file_name) #disposition = str_util.to_str(disposition) # 取文件后缀 suffix = file_path.split('.')[-1] suffix = suffix.lower() file_content = open(file_path, 'rb').read() # 处理图片附件 if suffix in ( 'jpg', 'jpeg', 'bmp', 'png', 'gif', ): image = MIMEImage(file_content) image.add_header('Content-ID', '<image1>') image.add_header('Content-Disposition', disposition) msg.attach(image) # 传送 txt 文件 elif suffix == 'txt': att1 = MIMEText(file_content, _subtype='base64', _charset='utf-8') att1["Content-Type"] = 'application/octet-stream' att1["Content-Disposition"] = disposition msg.attach(att1) # 其它附件 else: part = MIMEBase('application', 'octet-stream') #'octet-stream': binary data part.set_payload(file_content) encoders.encode_base64(part) part.add_header('Content-Disposition', disposition) msg.attach(part) # 发送邮件 try: smtp = smtplib.SMTP() smtp.connect(host) # 连接smtp服务器 smtp.login(user, password) # 登陆服务器 smtp.sendmail(from_address, to_address, msg.as_string()) # 发送邮件 smtp.close() return True except Exception, e: logger.error(u'发邮件错误:%s', e, exc_info=True) return False
def sendMail(self): try: sender = self.senderName.text() with open(self.email_path, 'r', encoding='utf-8') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') next(csv_reader) smtp = smtplib.SMTP(self.ui.host, self.ui.port) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.login(self.ui.username, self.ui.passWWord) for row in csv_reader: emaillist = row if emaillist: usern = emaillist[0].split('@')[0].capitalize() fulldomain = emaillist[0].split('@')[1] domainn = fulldomain.split('.')[0].capitalize() email_msg = EmailMessage() email_msg['From'] = formataddr( (str(Header(sender, 'utf-8')), self.ui.username)) email_msg['To'] = COMMASPACE.join(emaillist) email_msg['Subject'] = self.subject.text() email_msg['Reply-To'] = self.ui.username email_msg['Date'] = formatdate(localtime=True) messagebody = self.message.toHtml().replace('usern', usern).replace('domainn', domainn) \ .replace('fulldomain', fulldomain) if self.attachment_path is None: email_msg.set_content(messagebody, subtype='html') else: email_msg.set_content(messagebody, subtype='html') ctype, encoding = mimetypes.guess_type( self.attachment_path) if ctype is None or encoding is not None: # No guess could be made, or the file is encoded (compressed), so # use a generic bag-of-bits type. ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) filename = os.path.basename(self.attachment_path) with open(self.attachment_path, 'rb') as fp: email_msg.add_attachment(fp.read(), maintype=maintype, subtype=subtype, filename=filename) smtp.send_message(email_msg) for x in emaillist: a = 'Message successfully sent to ' + x self.log.append(a) smtp.quit() except SMTPHeloError: self.log.setText('Server did not reply.') except SMTPNotSupportedError: self.log.setText("SMTP NOT SUPPORTED") except SMTPAuthenticationError: self.log.setText('Incorrect Username or Password.') except SMTPRecipientsRefused as e: self.log.setText(e) except SMTPException: self.log.setText('Authentication failed!') except SMTPConnectError: self.log.setText("Connection Error!") except SMTPDataError as e: self.log.setText(e) except FileNotFoundError: self.log.setText('File not found!')
def send_email(self, subject=myutils.get_username()): ''' Zip and send logfiles by email for the specified logger. We use the email settings specified in the .ini file for the logger. ''' self.logger.debug('Initiating log email.') if self.subsettings['Zip']['Enable Zip'] is False: self.mainapp.event_threads[ self.loggername].timer_threads['Zip'].task_function() try: self.latest_zip_emailed = "" # in case emaillog doesn't exist. emaillog = open( os.path.join(self.log_full_dir, "_internal_emaillog.txt"), 'r') self.latest_zip_emailed = emaillog.readline() emaillog.close() except: self.logger.debug( "Cannot open _internal_emaillog.txt. " "Will email all available zip files.", exc_info=True) self.dir_lock.acquire() try: zipfile_list = os.listdir(self.log_full_dir) # removing elements from a list while iterating over it produces # undesirable results so we make a copy zipfile_list_copy = copy.deepcopy(zipfile_list) self.logger.debug(str(zipfile_list)) if len(zipfile_list) > 0: for filename in zipfile_list_copy: if not self.needs_emailing(filename): zipfile_list.remove(filename) self.logger.debug("removing %s from " "zipfilelist." % filename) self.logger.debug(str(zipfile_list)) # set up the message msg = MIMEMultipart() msg['From'] = self.subsettings['E-mail']['E-mail From'] msg['To'] = COMMASPACE.join( self.subsettings['E-mail']['E-mail To'].split(";")) msg['Date'] = formatdate(localtime=True) msg['Subject'] = self.subsettings['E-mail'][ 'E-mail Subject'] + ' - Sujeto: ' + subject msg.attach( MIMEText(self.subsettings['E-mail']['E-mail Message Body'])) if len(zipfile_list) == 0: msg.attach(MIMEText("No new logs present.")) if len(zipfile_list) > 0: for fname in zipfile_list: part = MIMEBase('application', "octet-stream") part.set_payload( open(os.path.join(self.log_full_dir, fname), "rb").read()) Encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(fname)) msg.attach(part) finally: self.dir_lock.release() # set up the server and send the message # wrap it all in a try/except, so that everything doesn't hang up # in case of network problems and whatnot. try: mysmtp = smtplib.SMTP(self.subsettings['E-mail']['SMTP Server'], self.subsettings['E-mail']['SMTP Port']) if self.cmdoptions.debug: mysmtp.set_debuglevel(1) if self.subsettings['E-mail']['SMTP Use TLS'] is True: # we find that we need to use two ehlos (one before and one # after starttls) # otherwise we get "SMTPException: SMTP AUTH extension not # supported by server" # thanks for this solution go to # http://forums.belution.com/en/python/000/009/17.shtml mysmtp.ehlo() mysmtp.starttls() mysmtp.ehlo() if self.subsettings['E-mail']['SMTP Needs Login'] is True: mysmtp.login( self.subsettings['E-mail']['SMTP Username'], myutils.password_recover( self.subsettings['E-mail']['SMTP Password'])) sendingresults = mysmtp.sendmail( self.subsettings['E-mail']['E-mail From'], self.subsettings['E-mail']['E-mail To'].split(";"), msg.as_string()) self.logger.debug("Email sending errors (if any): " "%s \n" % str(sendingresults)) # need to put the quit in a try, since TLS connections may error # out due to bad implementation with # socket.sslerror: (8, 'EOF occurred in violation of protocol') # Most SSL servers and clients (primarily HTTP, but some SMTP # as well) are broken in this regard: # they do not properly negotiate TLS connection shutdown. # This error is otherwise harmless. # reference URLs: # http://groups.google.de/group/comp.lang.python/msg/252b421a7d9ff037 # http://mail.python.org/pipermail/python-list/2005-August/338280.html try: mysmtp.quit() except: pass # write the latest emailed zip to log for the future if len(zipfile_list) > 0: zipfile_list.sort() emaillog = open( os.path.join(self.log_full_dir, "_internal_emaillog.txt"), 'w') emaillog.write(zipfile_list.pop()) emaillog.close() except: self.logger.debug('Error sending email.', exc_info=True) pass # better luck next time