コード例 #1
0
def send_mail(recipient, subject, body, attachments="", encoding='utf-8'):
    session = None
    if attachments == "":
        msg = MIMEText(body, 'plain', encoding)
        msg['Subject'] = Header(subject, encoding)
        msg['From'] = Header(u'"{0}" <{1}>'.format(SENDER_NAME, SENDER_EMAIL), encoding)
        msg['To'] = recipient
        msg['Date'] = formatdate()
    else:
        msg = MIMEMultipart()
        msg['Subject'] = Header(subject, encoding)
        msg['From'] = Header(u'"{0}" <{1}>'.format(SENDER_NAME, SENDER_EMAIL), encoding)
        msg['To'] = recipient
        msg['Date'] = formatdate()

        # This is the textual part:
        part = MIMEText(body)
        msg.attach(part)

        # That is what u see if dont have an email reader:
        msg.preamble = 'Multipart massage.\n'

        attachment_list = attachments.split(",")
        # Loop and print each city name.
        for attachment in attachment_list:
            print "attach file: ", attachment
            # This is the binary part(The Attachment):
            part = MIMEApplication(open(attachment,"rb").read())
            part.add_header('Content-Disposition', 'attachment', filename=attachment+".txt")
            msg.attach(part)

    try:
        if SMTP_SSL_TYPE == 'SMTP_SSL':
            session = smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT)
        else:
            session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
            if SMTP_SSL_TYPE == 'SMTP_TLS':
                session.ehlo()
                session.starttls()
                session.ehlo()
        session.login(SMTP_USERNAME, SMTP_PASSWORD)
        session.sendmail(SENDER_EMAIL, recipient, msg.as_string())
    except Exception as e:
        raise e
    finally:
        # close session
        if session:
            session.quit()
コード例 #2
0
	def sendMail(self, success = True):
		with open("editlog.txt","rb") as text :
			msg = MIMEText(text.read())
			
		msg['From'] = "*****@*****.**"
		msg['To'] = self.client.email
		msg['Subject'] = "Update on SpreadSheet "
		msg.preamble = "Edit Log"	
		server = smtplib.SMTP()
		server.connect('smtp.gmail.com', 587)
		server.ehlo()
		server.starttls()
		server.ehlo()
		server.login("####@gmail.com","password")
		message = msg.as_string()
		server.sendmail('#from_email', self.client.email, message)
		os.remove("editlog.txt")
コード例 #3
0
ファイル: forms.py プロジェクト: daskilet/django3
 def send_mail(self):
     # готовим контекст для сообщения
     response = self.cleaned_data['response']
     msg = MIMEText(response,_charset='utf-8')
     msg.preamble = "From blog"
     emaill = self.cleaned_data['email']
     subject = self.cleaned_data['topic']
     msg["Subject"] = mkh([(subject, "utf-8")])
     msg["From"] = mkh([("User_of_blog", "utf-8"), ("<%s>"%emaill, "us-ascii")])
     msg["To"] = mkh([("Admin", "utf-8"), ("<%s>"%admin_mail, "us-ascii")])
     msg = msg.as_string()
     message=msg
     toaddr = admin_mail
     fromaddr = fictive_mail 
     password = admin_mail_password 
     connection = SMTP('pop.rambler.ru',25)
     SMTP.login(connection,fromaddr,password)
     connection.sendmail(fromaddr,toaddr,message)
     connection.quit()
コード例 #4
0
ファイル: simplemail.py プロジェクト: CuonDeveloper/cuon
    def send(self):
        """
        de: Sendet die Email an den Empfaenger.
            Wird das Email nur an einen Empfaenger gesendet, dann wird bei
            Erfolg <True> zurueck gegeben. Wird das Email an mehrere Empfaenger
            gesendet und wurde an mindestens einen der Empfaenger erfolgreich
            ausgeliefert, dann wird ebenfalls <True> zurueck gegeben.
            
            Wird das Email nur an einen Empfaenger gesendet, dann wird bei
            Misserfolg <False> zurueck gegeben. Wird das Email an mehrere 
            Empfaenger gesendet und wurde an keinen der Empfaenger erfolgreich
            ausgeliefert, dann wird <False> zurueck gegeben.
        """

        #
        # pruefen ob alle notwendigen Informationen angegeben wurden
        #
        if len(self.from_address.strip()) == 0:
            raise NoFromAddress_Exception
        if self.recipients.count() == 0:
            if (
                (self.cc_recipients.count() == 0) and 
                (self.bcc_recipients.count() == 0)
            ):
                raise NoToAddress_Exception
        if len(self.subject.strip()) == 0:
            raise NoSubject_Exception

        #
        # Email zusammensetzen
        #
        if self.attachments.count() == 0:
            # Nur Text
            msg = MIMEText(
                _text = self.message,
                _subtype = self.content_subtype,
                _charset = self.content_charset
            )
        else:
            # Multipart
            msg = MIMEMultipart()
            if self.message:
                att = MIMEText(
                    _text = self.message,
                    _subtype = self.content_subtype,
                    _charset = self.content_charset
                )
                msg.attach(att)

        # Empfänger, CC, BCC, Absender, User-Agent, Antwort-an 
        # und Betreff hinzufügen
        from_str = formataddr((self.from_caption, self.from_address))
        msg["From"] = from_str
        if self.reply_to_address:
            reply_to_str = formataddr((self.reply_to_caption, self.reply_to_address))
            msg["Reply-To"] = reply_to_str
        if self.recipients.count() > 0:
            msg["To"] = ", ".join(self.recipients.get_list())
        if self.cc_recipients.count() > 0:
            msg["Cc"] = ", ".join(self.cc_recipients.get_list())
        msg["Date"] = formatdate(time.time())
        msg["User-Agent"] = self.user_agent
        try:
            msg["Subject"] = Header(
                self.subject, self.header_charset
            )
        except(UnicodeDecodeError):
            msg["Subject"] = Header(
                self.subject, self.content_charset
            )
        msg.preamble = "You will not see this in a MIME-aware mail reader.\n"
        msg.epilogue = ""

        # Falls MULTIPART --> zusammensetzen
        if self.attachments.count() > 0:
            for filename in self.attachments.get_list():
                # Pruefen ob Datei existiert
                if not os.path.isfile(filename):
                    raise AttachmentNotFound_Exception, filename
                # Datentyp herausfinden
                ctype, encoding = mimetypes.guess_type(filename)
                if ctype is None or encoding is not None:
                    ctype = 'application/octet-stream'
                maintype, subtype = ctype.split('/', 1)
                if maintype == 'text':
                    fp = file(filename)
                    # Note: we should handle calculating the charset
                    att = MIMEText(fp.read(), _subtype=subtype)
                    fp.close()
                elif maintype == 'image':
                    fp = file(filename, 'rb')
                    att = MIMEImage(fp.read(), _subtype=subtype)
                    fp.close()
                elif maintype == 'audio':
                    fp = file(filename, 'rb')
                    att = MIMEAudio(fp.read(), _subtype=subtype)
                    fp.close()
                else:
                    fp = file(filename, 'rb')
                    att = MIMEBase(maintype, subtype)
                    att.set_payload(fp.read())
                    fp.close()
                    # Encode the payload using Base64
                    Encoders.encode_base64(att)
                # Set the filename parameter
                att.add_header(
                    'Content-Disposition', 
                    'attachment', 
                    filename = os.path.split(filename)[1].strip()
                )
                msg.attach(att)

        #
        # Am SMTP-Server anmelden und evt. authentifizieren
        #
        smtp = smtplib.SMTP()
        if self.smtp_server:
            smtp.connect(self.smtp_server)
        else:
            smtp.connect()
        if self.smtp_user:
            smtp.login(user = self.smtp_user, password = self.smtp_password)

        #
        # Email versenden
        #
        self.statusdict = smtp.sendmail(
            from_str, 
            (
                self.recipients.get_list() + 
                self.cc_recipients.get_list() + 
                self.bcc_recipients.get_list()
            ), 
            msg.as_string()
        )
        smtp.close()

        # Rueckmeldung
        return True
コード例 #5
0
ファイル: mail.py プロジェクト: Distrotech/docutils
    def send(self):
        """
        Send the mail. Returns True if successfully sent to at least one
        recipient.
        """

        # validation
        if len(self.from_address.strip()) == 0:
            raise NoFromAddress_Exception
        if self.recipients.count() == 0:
            if (
                (self.cc_recipients.count() == 0) and
                (self.bcc_recipients.count() == 0)
            ):
                raise NoToAddress_Exception
        if len(self.subject.strip()) == 0:
            raise NoSubject_Exception

        # assemble
        if self.attachments.count() == 0:
            msg = MIMEText(
                _text = self.message,
                _subtype = self.content_subtype,
                _charset = self.content_charset
            )
        else:
            msg = MIMEMultipart()
            if self.message:
                att = MIMEText(
                    _text = self.message,
                    _subtype = self.content_subtype,
                    _charset = self.content_charset
                )
                msg.attach(att)

        # add headers
        from_str = formataddr((self.from_caption, self.from_address))
        msg["From"] = from_str
        if self.reply_to_address:
            reply_to_str = formataddr((self.reply_to_caption, self.reply_to_address))
            msg["Reply-To"] = reply_to_str
        if self.recipients.count() > 0:
            msg["To"] = ", ".join(self.recipients.get_list())
        if self.cc_recipients.count() > 0:
            msg["Cc"] = ", ".join(self.cc_recipients.get_list())
        msg["Date"] = formatdate(time.time())
        msg["User-Agent"] = self.user_agent
        try:
            msg["Subject"] = Header(
                self.subject, self.header_charset
            )
        except(UnicodeDecodeError):
            msg["Subject"] = Header(
                self.subject, self.content_charset
            )
        msg.preamble = "You will not see this in a MIME-aware mail reader.\n"
        msg.epilogue = ""

        # assemble multipart
        if self.attachments.count() > 0:
            for typ, info in self.attachments.get_list():
                if typ == 'file':
                    filename = info
                    if not os.path.isfile(filename):
                        raise AttachmentNotFound_Exception, filename
                    mimetype, encoding = mimetypes.guess_type(filename)
                    if mimetype is None or encoding is not None:
                        mimetype = 'application/octet-stream'
                    if mimetype.startswith('text/'):
                        fp = file(filename)
                    else:
                        fp = file(filename, 'rb')
                    text = fp.read()
                    fp.close()
                else:
                    filename, text, mimetype = info
                maintype, subtype = mimetype.split('/', 1)
                if maintype == 'text':
                    # Note: we should handle calculating the charset
                    att = MIMEText(text, _subtype=subtype)
                elif maintype == 'image':
                    att = MIMEImage(text, _subtype=subtype)
                elif maintype == 'audio':
                    att = MIMEAudio(text, _subtype=subtype)
                else:
                    att = MIMEBase(maintype, subtype)
                    att.set_payload(text)
                    # Encode the payload using Base64
                    Encoders.encode_base64(att)
                # Set the filename parameter
                att.add_header(
                    'Content-Disposition',
                    'attachment',
                    filename = os.path.basename(filename).strip()
                )
                msg.attach(att)

        # connect to server
        smtp = smtplib.SMTP()
        if self.smtp_server:
            smtp.connect(self.smtp_server)
        else:
            smtp.connect()

        # TLS?
        if self.use_tls:
            smtp.ehlo()
            smtp.starttls()
            smtp.ehlo()

        # authenticate
        if self.smtp_user:
            smtp.login(user = self.smtp_user, password = self.smtp_password)

        # send
        self.statusdict = smtp.sendmail(
            from_str,
            (
                self.recipients.get_list() +
                self.cc_recipients.get_list() +
                self.bcc_recipients.get_list()
            ),
            msg.as_string()
        )
        smtp.close()

        return True
コード例 #6
0
ファイル: ingestion_check.py プロジェクト: davehunt/datazilla
    def handle(self, *args, **options):

        settings_file = os.path.join(
            os.path.dirname(__file__),
            '../../../../../',
            'settings',
            'ingestion_alerts.json',
            )

        profiles = Profiles(settings_file)
        for profile in profiles:
            ptm = self.get_ptm(profile['product']['product'])

            # verify values against database and canonicalise
            self.canonicalise(ptm, profile, 'machine', \
                'machine', 'type')
            self.canonicalise(ptm, profile['product'], 'product', \
                'product', 'product')
            self.canonicalise(ptm, profile['product'], 'branch', \
                'product', 'branch')
            self.canonicalise(ptm, profile['product'], 'version', \
                'product', 'version')
            self.canonicalise(ptm, profile, 'tests', 'test', 'name')
            self.canonicalise(ptm, profile, 'pages', 'pages', 'url')

            alert_messages = {}
            # get the last test_run date
            test_run_data = ptm.get_last_test_run_date(
                profile['machine'],
                profile['product']['product'],
                profile['product']['branch'],
                profile['product']['version'],
                profile['tests'],
                profile['pages'],
            )

            for datum in test_run_data:
                # check if we need to alert
                if datum['date_run']:
                    last_run_date = datetime.datetime.fromtimestamp(datum['date_run']) or None
                    diff = datetime.datetime.now() - last_run_date
                    age = (diff.microseconds +
                        (diff.seconds + diff.days * 24 * 3600) * 1e6) / 1e6
                    if age / 60 < profile['alert_minutes']:
                        continue
                    else:
                        datum['age'] = self.human_duration(age)

                        if datum['test'] not in alert_messages:
                            alert_messages[datum['test']] = []

                        alert_messages[datum['test']].append(datum)

            if alert_messages:

                efrom = '*****@*****.**'

                border = "------------------------------------------------------------\n"
                subject = "Ingestion alert for {0} on {1} {2} {3}".format(
                    profile['machine'], profile['product']['product'],
                    profile['product']['branch'], profile['product']['version'])

                alert = "Device Type: {0}, Product: {1}, {2}, {3}\n".format(
                    profile['machine'], profile['product']['product'],
                    profile['product']['branch'], profile['product']['version'])

                alert += border

                for test in alert_messages:
                    alert += "Test: {0}\n".format(test)
                    for m in alert_messages[test]:
                        alert += "   App: {0}, no data in {1}\n".format(
                            m['app'], m['age']
                            )
                    alert += "\n"

                alert += border

                for recipient in profile['alert_recipients']:
                    if settings.DEBUG:
                        message = "From: %s\nTo: %s\nSubject: %s\n\n%s" \
                            % (efrom, recipient, subject, alert)
                        print message
                        print "SMTP_HOST: {0}".format(settings.SMTP_HOST)
                    else:


                        msg = MIMEText(alert)
                        msg['Subject'] = subject
                        msg['From'] = efrom
                        msg['To'] = recipient
                        msg.preamble = 'Datazilla ingestion alert'

                        s = smtplib.SMTP(settings.SMTP_HOST)
                        s.sendmail(efrom, recipient, msg.as_string())

        for key in self.models:
            self.models[key].disconnect()
コード例 #7
0
ファイル: smtp_transporter.py プロジェクト: mcruse/monotone
    def transport(self, data):
        if type(data) != type(''):
            # @todo Add warning that stream is being ignored
            # @todo Assuming that not string means stream.
            a = array.array('c')
            stream_data = data.read(1024)
            while stream_data:
                a.fromstring(stream_data)
                stream_data = data.read(1024)
            data = a.tostring()

        headers = {}
        splitdata = data.split('\r\n\r\n')
        if len(splitdata) > 1:
            headerdata = splitdata[0]
            data = string.join(splitdata[1:], '\r\n\r\n')
            for header in headerdata.split('\r\n'):
                splitheader = header.split(':')
                name = splitheader[0].strip()
                value = string.join(splitheader[1:], ':').strip()
                headers[name] = value

        if self.subtype:
            text_subtype = self.subtype
        else: text_subtype = 'plain'
        if text_subtype == 'plain':
            default_extension = 'txt'
        else:
            default_extension = text_subtype
        if text_subtype != 'xml' and data[:16].strip()[:5] == '<?xml':
            msglog.log('broadway', msglog.types.WARN,
                       'Transporter overriding configured subtype to "xml".')
            text_subtype='xml'
            default_extension = 'xml'
        msg = MIMEText(data, _subtype=text_subtype)
        subject = headers.get('Subject')
        if subject is None or subject == 'None' or subject == '':
            subject = self.subject
        #CSCtg54105
        else:
            if self.subject is not None and self.subject != 'None' and self.subject != '':
                subject = self.subject + ': ' + subject
        if subject:
            msg.add_header('Thread-Topic', subject)
            msg.add_header('Subject', subject)
        msg.add_header('From', self.sender)
        msg.add_header('To', COMMASPACE.join(self._recipients))
        date = headers.get('Date', formatdate(time.time(), True))
        msg.add_header('Date', date)

        message_id = make_msgid()
        if self.as_attachment:
            # @fixme: Make configurable
            default_filename = "%s.%s" % (
                message_id[1:-1].split("@")[0],
                default_extension
                )
            msg.add_header('Content-Disposition', 'attachment',
                           filename=default_filename)
            msg.set_param('name',  default_filename)
        # @fixme: Make configurable
        msg.add_header('Content-Class', 'urn:content-classes:message')
        # @fixme: Make configurable
        msg.add_header('X-Mailer', 'Mediator SMTP Transport')
        msg.add_header('Message-ID', message_id)
        # @fixme: Make configurable
        msg.add_header('Importance', 'normal')
        # @fixme: Make configurable
        msg.add_header('Priority', 'normal')
        msg.preamble = ''
        # To guarantee the message ends with a newline
        msg.epilogue = ''

        smtp = self.SMTP()
        if self.debug:
            smtp.set_debuglevel(self.debug)
        smtp.connect(self.host,self.port,self.timeout)
        if self.custom_domain:
            if not (200 <= smtp.ehlo(self.custom_domain)[0] <= 299):
                (code, resp) = smtp.helo(self.custom_domain)
                if not (200 <= code <= 299):
                    raise smtp.SMTPHeloError(code, resp)
        if self.authenticate:
            try:
                smtp.login(self.username,self.password)
            except smtplib.SMTPAuthenticationError:
                msglog.log('broadway',msglog.types.WARN,
                           'SMTP Authentication failed.' +
                           '  Invalid username/password.')
                raise
        failures = smtp.sendmail(self.sender,self._recipients,
                                 msg.as_string())
        for recipient in failures.keys():
            msglog.log('broadway',msglog.types.WARN,
                       'Error sending mail to %s -> %s' %
                       (recipient,failures[recipient]))
        smtp.close()
コード例 #8
0
    def transport(self, data):
        if type(data) != type(''):
            # @todo Add warning that stream is being ignored
            # @todo Assuming that not string means stream.
            a = array.array('c')
            stream_data = data.read(1024)
            while stream_data:
                a.fromstring(stream_data)
                stream_data = data.read(1024)
            data = a.tostring()

        headers = {}
        splitdata = data.split('\r\n\r\n')
        if len(splitdata) > 1:
            headerdata = splitdata[0]
            data = string.join(splitdata[1:], '\r\n\r\n')
            for header in headerdata.split('\r\n'):
                splitheader = header.split(':')
                name = splitheader[0].strip()
                value = string.join(splitheader[1:], ':').strip()
                headers[name] = value

        if self.subtype:
            text_subtype = self.subtype
        else:
            text_subtype = 'plain'
        if text_subtype == 'plain':
            default_extension = 'txt'
        else:
            default_extension = text_subtype
        if text_subtype != 'xml' and data[:16].strip()[:5] == '<?xml':
            msglog.log('broadway', msglog.types.WARN,
                       'Transporter overriding configured subtype to "xml".')
            text_subtype = 'xml'
            default_extension = 'xml'
        msg = MIMEText(data, _subtype=text_subtype)
        subject = headers.get('Subject')
        if subject is None or subject == 'None' or subject == '':
            subject = self.subject
        #CSCtg54105
        else:
            if self.subject is not None and self.subject != 'None' and self.subject != '':
                subject = self.subject + ': ' + subject
        if subject:
            msg.add_header('Thread-Topic', subject)
            msg.add_header('Subject', subject)
        msg.add_header('From', self.sender)
        msg.add_header('To', COMMASPACE.join(self._recipients))
        date = headers.get('Date', formatdate(time.time(), True))
        msg.add_header('Date', date)

        message_id = make_msgid()
        if self.as_attachment:
            # @fixme: Make configurable
            default_filename = "%s.%s" % (message_id[1:-1].split("@")[0],
                                          default_extension)
            msg.add_header('Content-Disposition',
                           'attachment',
                           filename=default_filename)
            msg.set_param('name', default_filename)
        # @fixme: Make configurable
        msg.add_header('Content-Class', 'urn:content-classes:message')
        # @fixme: Make configurable
        msg.add_header('X-Mailer', 'Mediator SMTP Transport')
        msg.add_header('Message-ID', message_id)
        # @fixme: Make configurable
        msg.add_header('Importance', 'normal')
        # @fixme: Make configurable
        msg.add_header('Priority', 'normal')
        msg.preamble = ''
        # To guarantee the message ends with a newline
        msg.epilogue = ''

        smtp = self.SMTP()
        if self.debug:
            smtp.set_debuglevel(self.debug)
        smtp.connect(self.host, self.port, self.timeout)
        if self.custom_domain:
            if not (200 <= smtp.ehlo(self.custom_domain)[0] <= 299):
                (code, resp) = smtp.helo(self.custom_domain)
                if not (200 <= code <= 299):
                    raise smtp.SMTPHeloError(code, resp)
        if self.authenticate:
            try:
                smtp.login(self.username, self.password)
            except smtplib.SMTPAuthenticationError:
                msglog.log(
                    'broadway', msglog.types.WARN,
                    'SMTP Authentication failed.' +
                    '  Invalid username/password.')
                raise
        failures = smtp.sendmail(self.sender, self._recipients,
                                 msg.as_string())
        for recipient in failures.keys():
            msglog.log(
                'broadway', msglog.types.WARN,
                'Error sending mail to %s -> %s' %
                (recipient, failures[recipient]))
        smtp.close()
コード例 #9
0
ファイル: NotificationTool.py プロジェクト: smetsjp/erp5
def buildEmailMessage(from_url, to_url, msg=None,
                      subject=None, attachment_list=None,
                      extra_headers=None,
                      additional_headers=None,
                      cc_url=None, bcc_url=None):
  """
    Builds a mail message which is ready to be
    sent by Zope MailHost.

    * attachment_list is a list of dictionaries with those keys:
     - name : name of the attachment,
     - content: data of the attachment
     - mime_type: mime-type corresponding to the attachment
    * extra_headers is a dictionary of custom headers to add to the email.
      "X-" prefix is automatically added to those headers.
    * additional_headers is similar to extra_headers, but no prefix is added.
  """

  if attachment_list == None:
    # Create non multi-part MIME message.
    message = MIMEText(msg, _charset='utf-8')
    attachment_list = []
  else:
    # Create multi-part MIME message.
    message = MIMEMultipart()
    message.preamble = "If you can read this, your mailreader\n" \
                        "can not handle multi-part messages!\n"
    message.attach(MIMEText(msg, _charset='utf-8'))

  if extra_headers:
    for key, value in extra_headers.items():
      message.add_header('X-%s' % key, value)

  if additional_headers:
    for key, value in additional_headers.items():
      message.add_header(key, value)

  if subject:
    message.add_header('Subject',
                        make_header([(subject, 'utf-8')]).encode())
  if from_url:
    message.add_header('From', from_url)
  if to_url:
    message.add_header('To', to_url)
  if cc_url: 
    message.add_header('Cc', cc_url)
  if bcc_url: 
    message.add_header('Bcc', bcc_url)

  for attachment in attachment_list:
    attachment_name = attachment.get('name', '')
    attachment_name = attachment_name or '' # Prevent None params

    # try to guess the mime type
    if not attachment.has_key('mime_type'):
      mime_type, encoding = guess_type( attachment_name )
      if mime_type is not None:
        attachment['mime_type'] = mime_type
      else:
        attachment['mime_type'] = 'application/octet-stream'

    # attach it
    if attachment['mime_type'] == 'text/plain':
      part = MIMEText(attachment['content'], _charset='utf-8')
    else:
      major, minor = attachment['mime_type'].split('/', 1)
      if major == 'text':
        part = MIMEText(attachment['content'], _subtype=minor)
      elif major == 'image':
        part = MIMEImage(attachment['content'], _subtype=minor)
      elif major == 'audio':
        part = MIMEAudio(attachment['content'], _subtype=minor)
      else:
        #  encode non-plaintext attachment in base64      
        part = MIMEBase(major, minor)
        part.set_payload(attachment['content'])
        Encoders.encode_base64(part)

    part.add_header('Content-Disposition', 'attachment',
                    filename=attachment_name)
    part.add_header('Content-ID', '<%s>' % \
                    ''.join(['%s' % ord(i) for i in attachment_name]))
    message.attach(part)

  return message
コード例 #10
0
ファイル: Email.py プロジェクト: jaygonzales/EmailPro
    def send(self):
        """
        Send the email message represented by this object.
        """
        # Validate message
        if self._textBody is None and self._htmlBody is None:
            raise Exception(
                "Error! Must specify at least one body type (HTML or Text)")
        if len(self._to) == 0:
            raise Exception("Must specify at least one recipient")

        # Create the message part
        if self._textBody is not None and self._htmlBody is None:
            msg = MIMEText(self._textBody, "plain")
        elif self._textBody is None and self._htmlBody is not None:
            msg = MIMEText(self._htmlBody, "html")
        else:
            msg = MIMEMultipart("alternative")
            msg.attach(MIMEText(self._textBody, "plain"))
            msg.attach(MIMEText(self._htmlBody, "html"))

        # Add attachments, if any
        if len(self._attach) != 0:
            tmpmsg = msg
            msg = MIMEMultipart()
            msg.attach(tmpmsg)
        for fname, attachname in self._attach:
            if not os.path.exists(fname):
                raise Exception(
                    "File '{0}' does not exist.  Not attaching to email.".
                    format(fname))
                continue
            if not os.path.isfile(fname):
                raise Exception(
                    "Attachment '{0}' is not a file.  Not attaching to email.".
                    format(fname))
                continue
            # Guess at encoding type
            ctype, encoding = mimetypes.guess_type(fname)
            if ctype is None or encoding is not None:
                # No guess could be made so use a binary type.
                ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/', 1)
            if maintype == 'text':
                fp = open(fname)
                attach = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'image':
                fp = open(fname, 'rb')
                attach = MIMEImage(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'audio':
                fp = open(fname, 'rb')
                attach = MIMEAudio(fp.read(), _subtype=subtype)
                fp.close()
            else:
                fp = open(fname, 'rb')
                attach = MIMEBase(maintype, subtype)
                attach.set_payload(fp.read())
                fp.close()
                # Encode the payload using Base64
                encoders.encode_base64(attach)
            # Set the filename parameter
            if attachname is None:
                filename = os.path.basename(fname)
            else:
                filename = attachname
            attach.add_header('Content-Disposition',
                              'attachment',
                              filename=filename)
            msg.attach(attach)

        # Complete header
        # This is where To, CC, BCC are differentiated
        msg['Subject'] = self._subject
        msg['From'] = self._from
        msg['To'] = ", ".join(self._to)
        msg['CC'] = ", ".join(self._cc)
        msg['BCC'] = ", ".join(self._bcc)
        if self._replyTo is not None:
            msg['reply-to'] = self._replyTo
        msg.preamble = "You need a MIME enabled mail reader to see this message"
        msg = msg.as_string()
        allRecipients = self._to + self._cc + self._bcc

        # Send message
        try:
            server = smtplib.SMTP(self._smtpServer, self._smtpPort,
                                  self._hostname, 5)
            server.set_debuglevel(self._debugLevel)
            server.ehlo()
            if self._username:
                if server.has_extn('STARTTLS'):
                    server.starttls()
                else:
                    server.quit()
                    server = smtplib.SMTP_SSL(self._smtpServer, self._smtpPort,
                                              self._hostname)
                    server.set_debuglevel(self._debugLevel)
                server.ehlo()  # re-identify ourselves over secure connection
                server.login(self._username, self._password)

            result = server.sendmail(self._from, allRecipients, msg)
        except Exception, err:
            raise err
コード例 #11
0
ファイル: send-email.py プロジェクト: gesquive/send-email
    def send(self):
        """
        Send the email message represented by this object.
        """
        # Validate message
        if self._text_body is None and self._html_body is None:
            raise Exception("Error! Must specify at least one body type (HTML or Text)")
        if len(self._to) == 0:
            raise Exception("Must specify at least one recipient")

        # Create the message part
        if self._text_body is not None and self._html_body is None:
            msg = MIMEText(self._text_body, "plain")
        elif self._text_body is None and self._html_body is not None:
            msg = MIMEText(self._html_body, "html")
        else:
            msg = MIMEMultipart("alternative")
            msg.attach(MIMEText(self._text_body, "plain"))
            msg.attach(MIMEText(self._html_body, "html"))
        # Add attachments, if any
        if len(self._attach) != 0:
            tmpmsg = msg
            msg = MIMEMultipart()
            msg.attach(tmpmsg)
        for fname,attachname in self._attach:
            if not os.path.exists(fname):
                print "File '%s' does not exist.  Not attaching to email." % fname
                continue
            if not os.path.isfile(fname):
                print "Attachment '%s' is not a file.  Not attaching to email." % fname
                continue
            # Guess at encoding type
            ctype, encoding = mimetypes.guess_type(fname)
            if ctype is None or encoding is not None:
                # No guess could be made so use a binary type.
                ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/', 1)
            if maintype == 'text':
                fp = open(fname)
                attach = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'image':
                fp = open(fname, 'rb')
                attach = MIMEImage(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'audio':
                fp = open(fname, 'rb')
                attach = MIMEAudio(fp.read(), _subtype=subtype)
                fp.close()
            else:
                fp = open(fname, 'rb')
                attach = MIMEBase(maintype, subtype)
                attach.set_payload(fp.read())
                fp.close()
                # Encode the payload using Base64
                encoders.encode_base64(attach)
            # Set the filename parameter
            if attachname is None:
                filename = os.path.basename(fname)
            else:
                filename = attachname
            attach.add_header('Content-Disposition', 'attachment', filename=filename)
            msg.attach(attach)
        # Some header stuff
        msg['Subject'] = self._subject
        msg['From'] = self._from
        msg['To'] = ", ".join(self._to)
        if self._reply_to:
            msg['Reply-To'] = self._reply_to
        if len(self._cc) > 0:
            msg['Cc'] = ", ".join(self._cc)
        if len(self._bcc) > 0:
            msg['Bcc'] = ", ".join(self._bcc)
        msg.preamble = "You need a MIME enabled mail reader to see this message"
        # Send message
        msg = msg.as_string()
        server = None
        if self._smtp_ssl:
            server = smtplib.SMTP_SSL(host=self._smtp_server,
                port=self._smtp_port)
        else:
            server = smtplib.SMTP(host=self._smtp_server, port=self._smtp_port)
        if self._smtp_user:
            server.login(self._smtp_user, self._smtp_password)
        server.sendmail(self._from, self._to, msg)
        server.quit()
コード例 #12
0
ファイル: Email.py プロジェクト: DonovanChan/EmailPro
    def send(self):
        """
        Send the email message represented by this object.
        """
        # Validate message
        if self._textBody is None and self._htmlBody is None:
            raise Exception("Error! Must specify at least one body type (HTML or Text)")
        if len(self._to) == 0:
            raise Exception("Must specify at least one recipient")

        # Create the message part
        if self._textBody is not None and self._htmlBody is None:
            msg = MIMEText(self._textBody, "plain")
        elif self._textBody is None and self._htmlBody is not None:
            msg = MIMEText(self._htmlBody, "html")
        else:
            msg = MIMEMultipart("alternative")
            msg.attach(MIMEText(self._textBody, "plain"))
            msg.attach(MIMEText(self._htmlBody, "html"))

        # Add attachments, if any
        if len(self._attach) != 0:
            tmpmsg = msg
            msg = MIMEMultipart()
            msg.attach(tmpmsg)
        for fname, attachname in self._attach:
            if not os.path.exists(fname):
                raise Exception("File '{0}' does not exist.  Not attaching to email.".format(fname))
                continue
            if not os.path.isfile(fname):
                raise Exception("Attachment '{0}' is not a file.  Not attaching to email.".format(fname))
                continue
            # Guess at encoding type
            ctype, encoding = mimetypes.guess_type(fname)
            if ctype is None or encoding is not None:
                # No guess could be made so use a binary type.
                ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/', 1)
            if maintype == 'text':
                fp = open(fname)
                attach = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'image':
                fp = open(fname, 'rb')
                attach = MIMEImage(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'audio':
                fp = open(fname, 'rb')
                attach = MIMEAudio(fp.read(), _subtype=subtype)
                fp.close()
            else:
                fp = open(fname, 'rb')
                attach = MIMEBase(maintype, subtype)
                attach.set_payload(fp.read())
                fp.close()
                # Encode the payload using Base64
                encoders.encode_base64(attach)
            # Set the filename parameter
            if attachname is None:
                filename = os.path.basename(fname)
            else:
                filename = attachname
            attach.add_header('Content-Disposition', 'attachment', filename=filename)
            msg.attach(attach)

        # Complete header
        # This is where To, CC, BCC are differentiated
        msg['Subject'] = self._subject
        msg['From'] = self._from
        msg['To'] = ", ".join(self._to)
        msg['CC'] = ", ".join(self._cc)
        msg['BCC'] = ", ".join(self._bcc)
        if self._replyTo is not None:
            msg['reply-to'] = self._replyTo
        msg.preamble = "You need a MIME enabled mail reader to see this message"
        msg = msg.as_string()
        allRecipients = self._to + self._cc + self._bcc

        # Send message
        try:
            server = smtplib.SMTP(self._smtpServer, self._smtpPort, self._hostname, 5)
            server.set_debuglevel(self._debugLevel)
            server.ehlo()
            if self._username:
                if server.has_extn('STARTTLS'):
                    server.starttls()
                else:
                    server.quit()
                    server = smtplib.SMTP_SSL(self._smtpServer, self._smtpPort, self._hostname)
                    server.set_debuglevel(self._debugLevel)
                server.ehlo()  # re-identify ourselves over secure connection
                server.login(self._username, self._password)

            result = server.sendmail(self._from, allRecipients, msg)
        except Exception, err:
            raise err
コード例 #13
0
ファイル: mail.py プロジェクト: wiless/IMTAphy
    def send(self):
        """
        Send the mail. Returns True if successfully sent to at least one
        recipient.
        """

        # validation
        if len(self.from_address.strip()) == 0:
            raise NoFromAddress_Exception
        if self.recipients.count() == 0:
            if ((self.cc_recipients.count() == 0)
                    and (self.bcc_recipients.count() == 0)):
                raise NoToAddress_Exception
        if len(self.subject.strip()) == 0:
            raise NoSubject_Exception

        # assemble
        if self.attachments.count() == 0:
            msg = MIMEText(_text=self.message,
                           _subtype=self.content_subtype,
                           _charset=self.content_charset)
        else:
            msg = MIMEMultipart()
            if self.message:
                att = MIMEText(_text=self.message,
                               _subtype=self.content_subtype,
                               _charset=self.content_charset)
                msg.attach(att)

        # add headers
        from_str = formataddr((self.from_caption, self.from_address))
        msg["From"] = from_str
        if self.reply_to_address:
            reply_to_str = formataddr(
                (self.reply_to_caption, self.reply_to_address))
            msg["Reply-To"] = reply_to_str
        if self.recipients.count() > 0:
            msg["To"] = ", ".join(self.recipients.get_list())
        if self.cc_recipients.count() > 0:
            msg["Cc"] = ", ".join(self.cc_recipients.get_list())
        msg["Date"] = formatdate(time.time())
        msg["User-Agent"] = self.user_agent
        try:
            msg["Subject"] = Header(self.subject, self.header_charset)
        except (UnicodeDecodeError):
            msg["Subject"] = Header(self.subject, self.content_charset)
        msg.preamble = "You will not see this in a MIME-aware mail reader.\n"
        msg.epilogue = ""

        # assemble multipart
        if self.attachments.count() > 0:
            for typ, info in self.attachments.get_list():
                if typ == 'file':
                    filename = info
                    if not os.path.isfile(filename):
                        raise AttachmentNotFound_Exception, filename
                    mimetype, encoding = mimetypes.guess_type(filename)
                    if mimetype is None or encoding is not None:
                        mimetype = 'application/octet-stream'
                    if mimetype.startswith('text/'):
                        fp = file(filename)
                    else:
                        fp = file(filename, 'rb')
                    text = fp.read()
                    fp.close()
                else:
                    filename, text, mimetype = info
                maintype, subtype = mimetype.split('/', 1)
                if maintype == 'text':
                    # Note: we should handle calculating the charset
                    att = MIMEText(text, _subtype=subtype)
                elif maintype == 'image':
                    att = MIMEImage(text, _subtype=subtype)
                elif maintype == 'audio':
                    att = MIMEAudio(text, _subtype=subtype)
                else:
                    att = MIMEBase(maintype, subtype)
                    att.set_payload(text)
                    # Encode the payload using Base64
                    Encoders.encode_base64(att)
                # Set the filename parameter
                att.add_header('Content-Disposition',
                               'attachment',
                               filename=os.path.basename(filename).strip())
                msg.attach(att)

        # connect to server
        smtp = smtplib.SMTP()
        if self.smtp_server:
            smtp.connect(self.smtp_server)
        else:
            smtp.connect()

        # TLS?
        if self.use_tls:
            smtp.ehlo()
            smtp.starttls()
            smtp.ehlo()

        # authenticate
        if self.smtp_user:
            smtp.login(user=self.smtp_user, password=self.smtp_password)

        # send
        self.statusdict = smtp.sendmail(
            from_str,
            (self.recipients.get_list() + self.cc_recipients.get_list() +
             self.bcc_recipients.get_list()), msg.as_string())
        smtp.close()

        return True
コード例 #14
0
ファイル: ingestion_check.py プロジェクト: davehunt/datazilla
    def handle(self, *args, **options):

        settings_file = os.path.join(
            os.path.dirname(__file__),
            '../../../../../',
            'settings',
            'ingestion_alerts.json',
        )

        profiles = Profiles(settings_file)
        for profile in profiles:
            ptm = self.get_ptm(profile['product']['product'])

            # verify values against database and canonicalise
            self.canonicalise(ptm, profile, 'machine', \
                'machine', 'type')
            self.canonicalise(ptm, profile['product'], 'product', \
                'product', 'product')
            self.canonicalise(ptm, profile['product'], 'branch', \
                'product', 'branch')
            self.canonicalise(ptm, profile['product'], 'version', \
                'product', 'version')
            self.canonicalise(ptm, profile, 'tests', 'test', 'name')
            self.canonicalise(ptm, profile, 'pages', 'pages', 'url')

            alert_messages = {}
            # get the last test_run date
            test_run_data = ptm.get_last_test_run_date(
                profile['machine'],
                profile['product']['product'],
                profile['product']['branch'],
                profile['product']['version'],
                profile['tests'],
                profile['pages'],
            )

            for datum in test_run_data:
                # check if we need to alert
                if datum['date_run']:
                    last_run_date = datetime.datetime.fromtimestamp(
                        datum['date_run']) or None
                    diff = datetime.datetime.now() - last_run_date
                    age = (diff.microseconds +
                           (diff.seconds + diff.days * 24 * 3600) * 1e6) / 1e6
                    if age / 60 < profile['alert_minutes']:
                        continue
                    else:
                        datum['age'] = self.human_duration(age)

                        if datum['test'] not in alert_messages:
                            alert_messages[datum['test']] = []

                        alert_messages[datum['test']].append(datum)

            if alert_messages:

                efrom = '*****@*****.**'

                border = "------------------------------------------------------------\n"
                subject = "Ingestion alert for {0} on {1} {2} {3}".format(
                    profile['machine'], profile['product']['product'],
                    profile['product']['branch'],
                    profile['product']['version'])

                alert = "Device Type: {0}, Product: {1}, {2}, {3}\n".format(
                    profile['machine'], profile['product']['product'],
                    profile['product']['branch'],
                    profile['product']['version'])

                alert += border

                for test in alert_messages:
                    alert += "Test: {0}\n".format(test)
                    for m in alert_messages[test]:
                        alert += "   App: {0}, no data in {1}\n".format(
                            m['app'], m['age'])
                    alert += "\n"

                alert += border

                for recipient in profile['alert_recipients']:
                    if settings.DEBUG:
                        message = "From: %s\nTo: %s\nSubject: %s\n\n%s" \
                            % (efrom, recipient, subject, alert)
                        print message
                        print "SMTP_HOST: {0}".format(settings.SMTP_HOST)
                    else:

                        msg = MIMEText(alert)
                        msg['Subject'] = subject
                        msg['From'] = efrom
                        msg['To'] = recipient
                        msg.preamble = 'Datazilla ingestion alert'

                        s = smtplib.SMTP(settings.SMTP_HOST)
                        s.sendmail(efrom, recipient, msg.as_string())

        for key in self.models:
            self.models[key].disconnect()