Did I find the right examples for you? yes no      Crawl my project      Python Jobs

All Samples(4)  |  Call(3)  |  Derive(0)  |  Import(1)

        def sendmail(job, subject, text, attachments, log, status):

    errmsg=''     
    if (job['mail']==False or (job['mail']=='fail' and status=='OK')) and not job['magikmon']:
        return None

    sender=job['sender']
    recipients=job['recipients']
    attachment_size=job['attachment_size']
    attachment_gzip=job['attachment_gzip']

    msg=MIMEMultipart()
    msg.preamble='' # This line is not visible on mime enable MUA
    msg.epilogue=''
    
    msg['From'] = formataddr((sender, sender)) # Display name, email address
    msg['To'] =  ', '.join([ formataddr((recipient, recipient)) for recipient in recipients ])
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject
    msg['Messsage-Id']=email.Utils.make_msgid('mksbackup')

    core=MIMEText(text.encode('utf-8'), 'plain', 'utf-8')
    msg.attach(core)
    
    for filename, target, data, maintype, subtype, charset in attachments:
        
        if not data and target and os.path.exists(target):
            data=open(target, 'rb').read(attachment_size)

        if data==None:
            data=''

        if len(data)>attachment_gzip:
            log.info('gzip attachment %s', filename)
            file_out=StringIO.StringIO()
            zfile=gzip.GzipFile(filename, 'wb', 9, file_out)
            if maintype=='text':
                # all txt gzip file are encode in UTF8 to avoid the loose of the charset 
                data=data.decode(charset).encode('utf-8')
            zfile.write(data)
            zfile.close()
            data=file_out.getvalue()
            file_out.close()
            filename+='.gz'
            maintype, subtype='application', 'x-gzip'

        if len(data)>attachment_size:
            log.warning('attachment is too big, skipped: %s', filename)
            # replace attachment by an "error"
            data='attachment is too big: %s\n' % (filename, )
            filename=os.path.splitext(filename)[0]+'-error.txt'
            maintype, subtype, charset='text', 'plain', 'ascii'
            
        #maintype, subtype = 'application', 'octet-stream'
        if maintype=='text':
            attachment=MIMEText(data, subtype, charset)
        else:
            attachment=MIMEBase(maintype, subtype)
            attachment.set_payload(data) #, charset) #dont use the charset, here !
            email.Encoders.encode_base64(attachment)

        attachment.add_header('Content-Disposition', 'attachment', filename=filename)
        msg.attach(attachment)
    
    body=msg.as_string()

    # first try send by http             
    if job['magikmon'] and job['program']!='esxmon':
        try:
            data=urllib.urlencode(dict(body=body))
            try:
                urllib2.urlopen(job['magikmon'], data, timeout=30)
            except TypeError:
                # python 2.4
                urllib2.urlopen(job['magikmon'], data)
        except Exception, e:
            log.exception('error sending mail to MagiKmon url: %s (%s)', job['magikmon'], e)
            if not errmsg:
                errmsg='error sending mail to MagiKmon url'
        else:
            log.debug('mail sent to MagiKmon url: %s', job['magikmon'])
            # Don't send the mail twice via HTTP and SMTP to the same MagiKmon monitoring service
            # remove the redundant recipient if any
            # http://monitoring.magikmon.com/sendbackup/XX/secret
            # b.XX@monitoring.magikmon.com
            #    
            domain, tld, path=url_re.match(job['magikmon']).group('domain', 'tld', 'path')
            match=re.match('/sendbackup/(?P[0-9]+)(/.*)?', path)
            if match:
                service_id=int(match.group('service_id'))
                mkm_address='b.%d@%s%s' % (service_id, domain, tld)
                for recipient in recipients[:]:
                    if recipient.lower()==mkm_address.lower():
                        log.info('"%s" removed from the list of recipients', recipient)
                        recipients.remove(recipient)
                
    if (job['mail']==True or (job['mail']=='fail' and status!='OK')) and recipients:
        smtp_host=job['smtp_host']
        smtp_port=job['smtp_port']
        smtp_mode=job['smtp_mode']
        smtp_login=job['smtp_login']
        smtp_password=job['smtp_password']
    
        rcpt=[]
        try:
            if smtp_mode=='ssl':
                smtp=smtplib.SMTP_SSL(smtp_host, smtp_port)
            else:
                smtp=smtplib.SMTP(smtp_host, smtp_port)
                if smtp_mode=='tls':
                    smtp.starttls()
                    
            if smtp_login and smtp_password:
                # login and password must be encoded because HMAC used in CRAM_MD5 require non unicode string
                smtp.login(smtp_login.encode('utf-8'), smtp_password.encode('utf-8'))
    
            ret=smtp.sendmail(sender, recipients, body)
            smtp.quit()
        except (socket.error, ), e:
            errmsg='server %s:%s not responding: %s' % (smtp_host, smtp_port, e)
        except smtplib.SMTPAuthenticationError, e:
            errmsg='authentication error: %s' % (e, )
        except smtplib.SMTPRecipientsRefused, e:
            # code, errmsg=e.recipients[recipient_addr]
            errmsg='recipients refused: '+', '.join(e.recipients.keys())
        except smtplib.SMTPSenderRefused, e:
            # e.sender, e.smtp_code, e.smtp_error
            errmsg='sender refused: %s' % (e.sender, )
        except smtplib.SMTPDataError, e:
            errmsg='SMTP protocol mismatch: %s' % (e, )
        except smtplib.SMTPHeloError, e:
            errmsg="server didn't reply properly to the HELO greeting: %s" % (e, )
        except smtplib.SMTPException, e:
            errmsg='SMTP error: %s' % (e, )
        except Exception, e:
            errmsg=str(e)
            log.exception('unexpected error sending mail: %s', e)
        else:
            rcpt=recipients[:]
            if ret:
                errmsg='recipients refused: '+', '.join(ret.keys())        
                for r in ret.keys():
                    rcpt.remove(r)
    
            if log:
                log.info('mail sent to: %s', ', '.join(rcpt))
    
        if log:
            if errmsg:
                log.error('sending mail: %s', errmsg)

    return errmsg
        


src/m/k/mksbackup-1.0.4/mksbackuplib/main.py   mksbackup(Download)
from datetime import datetime, timedelta
 
from archiver import boolean, check_mail_config, Destinations, sendmail, Manager, send_mail_report, write_status, ftp_url_re
 
import cron
        msg_body+='\nminor error when attaching logging\n'                      
 
    errmsg=sendmail(job, subject, msg_body, attachments, manager.log, 'exception')
 
 
                attachments=manager.attachments[:]
                attachments.append(('status.txt', None, status.encode('utf-8'), 'text', 'plain', 'utf-8')),
                errmsg=sendmail(job, subject, msg_body, attachments, manager.log, 'err')
                if cmd_options.statusdir:
                    write_status(status, cmd_options.statusdir, job['name'])
            if job['mail'] and command=='checkmail':
                subject='MKSBACKUP %s OK %s ' % (command_display, job['name'], )
                errmsg=sendmail(job, subject, msg_body, manager.attachments, manager.log, 'check')
            continue