示例#1
0
文件: smtp.py 项目: vhata/ibid
    def send(self, response):
        message = response['reply']
        response['To'] = response['target']
        response['Date'] = smtp.rfc822date()
        if 'Subject' not in response:
            response['Subject'] = 'Message from %s' % ibid.config['botname']
        response['Content-Type'] = 'text/plain; charset=utf-8'

        del response['target']
        del response['source']
        del response['reply']

        body = ''
        for header, value in response.items():
            body += '%s: %s\n' % (header, value)
        body += '\n'
        body += message

        port = ':' in self.relayhost and int(
            self.relayhost.split(':')[1]) or 25
        smtp.sendmail(self.relayhost.split(':')[0],
                      self.address,
                      response['To'],
                      body.encode('utf-8'),
                      port=port)
        self.log.debug(u"Sent email to %s: %s", response['To'],
                       response['Subject'])
示例#2
0
def mail_IRC_log(logger, channel, smtp, from_addr, to_addr):

    """
    Send latest IRC log to mailing list

    """
    minloglength = 20
    _log = logger.read_unpublished_log()
    lenlog = log.count('\n')
    if not lenlog >= minloglength:
        # skip publication
        report("skipping log publication due to small size (%i/%i lines)" % (lenlog, minloglength))
    else:
        # log long enough, format it
        date = time.strftime("%Y-%m-%d", time.localtime(time.time()))
        string = "Log of IRC channel %s (log published %s)" % (channel, date)
        _log = "%s\n\n%s" % (string, _log)
        # convert log to email
        mail = MIMEText(log)
        mail['Subject'] = "[evennia] %s IRC log - %s" % (channel, date)
        mail['From'] = str(from_addr)
        mail['To'] = str(to_addr)
        # send mail to mailing list

        def errback(fail):
            report("... irc-log mail could not be published: %s" % fail.value)

        def callback(ret):
            logger.mark_log_as_published()
            report("... irc-log mail from %s to %s successfully published." % (from_addr, to_addr))

        report("publishing irc log (%i lines) ..." % lenlog)
        sendmail(smtp, from_addr, to_addr, mail.as_string()).addCallbacks(callback, errback)
示例#3
0
def send_email_copy(message):
    """
    Sends an email copy of a message to all relevant targets.
    """
    receivers = [ receiver for receiver in message.receivers if receiver.player.user.email ]
    subject = message.header
    body = message.message
    if not (receivers):
        return

    msg = MIMEMultipart('alternative')
    msg['From'] = "Winter's Oasis <*****@*****.**>"
    msg['Subject'] = subject
    msg['Date'] = formatdate(localtime=True)

    # HTML email part.
    html_part = MIMEText('text', 'html')
    html_source = Template(HTML_TEMPLATE)
    value_map = {
        'from' : ', '.join([ sender.name for sender in message.senders ]),
        'message' : escape(unicode(body)).replace('\n', '<br />'),
        'recipients' : ', '.join([ receiver.name for receiver in message.receivers ]) }
    html_part.set_payload(html_source.substitute(value_map))

    value_map['message'] = unicode(body)
    text_source = Template(TEXT_TEMPLATE)
    body = text_source.substitute(value_map)
    text_part = MIMEText(unicode(body), 'plain', 'utf-8')
    msg.attach(text_part)
    msg.attach(html_part)

    for receiver in receivers:
        msg['To'] = receiver.db.email
        sendmail(SMTP_HOST, MAIL_FROM, receiver.player.user.email, msg.as_string())
示例#4
0
def email(subject, msgtxt):
    msg = MIMEText(msgtxt)
    msg['Subject'] = subject
    msg['From'] = global_config.smtpfrom
    msg['To'] = ', '.join(global_config.smtpto)

    sendmail(global_config.smtphost, global_config.smtpfrom, global_config.smtpto, msg.as_string())
示例#5
0
文件: common.py 项目: scollis/pyWWA
def email_error(exp, message):
    """
    Helper function to generate error emails when necessary and hopefully
    not flood!
    @param exp A string or perhaps a traceback object
    @param message A string of more information to pass along in the email
    """
    # Always log a message about our fun
    cstr = StringIO.StringIO()
    traceback.print_exc(file=cstr)
    cstr.seek(0)
    tbstr = cstr.read()
    log.err( exp )
    log.msg( message )

    # Prevent a parser from sending tons of spam
    if int(os.environ.get('EMAILS', 10)) < 0:
        return
    os.environ['EMAILS'] = str( int(os.environ.get("EMAILS",10)) - 1 )

    msg = MIMEText("""
Emails Left: %s  Host: %s

Exception:
%s
%s

Message:
%s""" % (os.environ["EMAILS"], socket.gethostname(), tbstr, exp, message))
    # Send the email already!
    msg['subject'] = '%s Traceback' % (sys.argv[0],)
    msg['From'] = settings.get('pywwa_errors_from', 'ldm@localhost')
    msg['To'] = settings.get('pywwa_errors_to', 'ldm@localhost')
    smtp.sendmail("smtp", msg["From"], msg["To"], msg)
示例#6
0
def sendmailfun(name, loginname, emailid, email, mailinfo, sendnum):

    print "Send:", email

    def error(msg):
        reactor.callLater(0, sqldb.setResult, emailid, str(msg), loginname, 0)

    def finish(msg):
        reactor.callLater(0, sqldb.setResult, emailid, str(msg), loginname, 1)

    sender = mailinfo['sender']
    subject = mailinfo['subject']
    omsg = mailinfo['msg']
    body = Template(omsg).safe_substitute(mailinfo)
    cbuf = create_string_buffer('\000' * 100)

    # domin
    domain = ""
    try:
        username, domain = email.split("@")
    except:
        domain = email
    domain = domain.strip(" >")
    if 0 == qmx.QueryMX(c_char_p(domain), cbuf):
        return error("Query MX for %s Failed" % domain)

    try:
        smtp = smtplib.SMTP(cbuf.value)
        if DEBUG:
            smtp.set_debuglevel(1)
        smtp.sendmail(sender, email, buildmsg(sender, email, subject, body))
        smtp.quit()
        return finish(email)
    except Exception, err:
        code = -1
        msg = ""
        try:
            code, msg = err
        except:
            msg = str(err)
        print email, code, msg
        if int(code) in [421, 451, 450]:
            sendnum += 1
            sendfun = partial(sendmailfun,
                              name=str(id),
                              loginname=loginname,
                              emailid=emailid,
                              email=email,
                              mailinfo=mailinfo,
                              sendnum=sendnum)
            if sendnum <= retry_count:
                tp.addtask(sendfun, random.randint(600, 30 * 60))
            return error("Host: %s, Retry: %d, Error: %d,%s" %
                         (cbuf.value, sendnum, code, err))
        else:
            return error("Host: %s, Error: %d,%s" % (cbuf.value, code, err))
示例#7
0
    def send_mail(self, message, subject=None, to_address=None, to_nickname=None):
        msg = MIMEText(message, _charset='utf-8')
        msg['Subject'] = subject
        msg['From'] = self.from_address
        if to_nickname is not None:
            msg['To'] = '%s <%s>' % (to_nickname, to_address)
        else:
            msg['To'] = to_address

        smtp.sendmail("localhost", self.from_address, to_address, msg.as_string())
示例#8
0
        def do_test():
            smtp = smtplib.SMTP('localhost', self.port, timeout=1)
            self.addCleanup(threads.deferToThread, smtp.quit)
            
            # check that validate_to and _from results in smtp errors
            self.assertRaises(smtplib.SMTPSenderRefused, smtp.sendmail, 'foo@invalid', '*****@*****.**', 'Hello')
            self.assertRaises(smtplib.SMTPSenderRefused, smtp.sendmail, 'foo@invalid', 'bar@invalid', 'Hello')
            self.assertRaises(smtplib.SMTPRecipientsRefused, smtp.sendmail, '*****@*****.**', 'bar@invalid', 'Hello')

            smtp.sendmail('*****@*****.**', '*****@*****.**', 'Hello')
示例#9
0
    def handle_error(self, error):
        traceback.print_exc()
        #g_logger.error("%s: %s" % (type(error), error))
        if isinstance(error, InitializationError):
            sys.exit(1)

        # send an email
        from twisted.mail.smtp import sendmail
        sendmail("smtp.gmail.com", "*****@*****.**", "*****@*****.**",
                 "Exception occurs in ICM Desktop Agent", "gmail.com")
示例#10
0
    def handle_error(self, error):
        traceback.print_exc()
        #g_logger.error("%s: %s" % (type(error), error))
        if isinstance(error, InitializationError):
            sys.exit(1)

        # send an email
        from twisted.mail.smtp import sendmail
        sendmail("smtp.gmail.com", "*****@*****.**",
                 "*****@*****.**", "Exception occurs in ICM Desktop Agent",
                 "gmail.com")
示例#11
0
        def do_test_without_tls():
            smtp = smtplib.SMTP('localhost', self.port, timeout=1)
            self.addCleanup(threads.deferToThread, smtp.quit)

            # a plaintext login is not allowed
            self.assertSMTPErrorCode(530, smtp.login, 'username', 'password')

            # tls is not configured
            self.assertRaises(smtplib.SMTPException, smtp.starttls)

            # we configured a checker that accepts anonymous access, so sending should work
            smtp.sendmail('*****@*****.**', '*****@*****.**', 'Hello')
示例#12
0
    def send_mail(self,
                  message,
                  subject=None,
                  to_address=None,
                  to_nickname=None):
        msg = MIMEText(message, _charset='utf-8')
        msg['Subject'] = subject
        msg['From'] = self.from_address
        if to_nickname is not None:
            msg['To'] = '%s <%s>' % (to_nickname, to_address)
        else:
            msg['To'] = to_address

        smtp.sendmail("localhost", self.from_address, to_address,
                      msg.as_string())
示例#13
0
def sendmailfun( name, loginname, emailid, email, mailinfo, sendnum  ):

	print "Send:", email
	def error ( msg ):
		reactor.callLater(0, sqldb.setResult, emailid,  str(msg),  loginname , 0 )
	
	def finish( msg ):
		reactor.callLater(0, sqldb.setResult, emailid,  str(msg),  loginname , 1 )

	sender = mailinfo['sender']
	subject = mailinfo['subject']
	omsg = mailinfo['msg']
	body = Template(omsg).safe_substitute( mailinfo )
	cbuf = create_string_buffer('\000' * 100 )

	# domin
	domain = ""
	try:
		username, domain = email.split("@")
	except:
		domain = email
	domain = domain.strip(" >")
	if 0==qmx.QueryMX( c_char_p(domain) , cbuf ):
		return error( "Query MX for %s Failed" % domain )
	
	try:
		smtp = smtplib.SMTP(cbuf.value)
		if DEBUG:
			smtp.set_debuglevel(1)
		smtp.sendmail(sender, email, buildmsg(sender, email, subject, body))
		smtp.quit()
		return finish( email )
	except Exception, err:
		code = -1
		msg = ""
		try:
			code, msg = err
		except:
			msg = str(err)
		print email, code, msg
		if int(code) in [421,451,450]:
			sendnum += 1
			sendfun = partial( sendmailfun, name= str(id), loginname=loginname, emailid=emailid, email = email, mailinfo = mailinfo , sendnum = sendnum )
			if  sendnum <= retry_count :
				tp.addtask(sendfun, random.randint( 600, 30*60 ) )
			return error("Host: %s, Retry: %d, Error: %d,%s" % ( cbuf.value, sendnum, code, err) )
		else:
			return error("Host: %s, Error: %d,%s" % ( cbuf.value, code, err) )
示例#14
0
    def deliver(self, formatted_message, recipient, raw_fedmsg):
        """
        Deliver a message to the recipient.

        Args:
            formatted_message (str): The formatted message that is ready for delivery
                to the user. It has been formatted according to the user's preferences.
            recipient (dict): The recipient of the message.
            raw_fedmsg (dict): The original fedmsg that was used to produce the formatted
                message.
        """
        try:
            # TODO handle the mail server being down gracefully
            yield smtp.sendmail(
                self.host,
                to_bytes(self.from_address),
                [to_bytes(recipient['email address'])],
                formatted_message.encode('utf-8'),
                port=self.port,
            )
            _log.info('Email successfully delivered to %s',
                      recipient['email address'])
        except smtp.SMTPClientError as e:
            _log.info('Failed to email %s: %s', recipient['email address'],
                      str(e))
            if e.code == 550:
                self.handle_bad_email_address(recipient)
            else:
                raise
示例#15
0
def send_notify_mail(subject, attachments=[]):
    me = CONFIG["email_profile"]["login"]
    to = CONFIG["email_profile"]["list_receivers"]

    msg = MIMEMultipart()
    msg['From'] = me
    msg['To'] = COMMASPACE.join(to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    for attach in attachments:
        msg.attach(attach)

    d = sendmail(CONFIG["email_profile"]["remote_host"],
                 me,
                 to,
                 msg.as_string(),
                 port=CONFIG["email_profile"]["remote_port"],
                 username=me,
                 password=CONFIG["email_profile"]["password"],
                 requireAuthentication=True,
                 requireTransportSecurity=True)

    @d.addBoth
    def _print(res):
        print(res)

    return d
示例#16
0
def sendmail(toAddr, subject, textPart, htmlPart=None, fromAddr="*****@*****.**", fromName="Flocked-in"):
    if textPart:
        textPart = sanitizer.unescape(textPart, {"&#58;": ":"})
    if htmlPart:
        msg = MIMEMultipart("alternative")
        msg.preamble = "This is a multi-part message in MIME format."

        msgText = MIMEText(textPart, _charset="utf8")
        msg.attach(msgText)

        msgText = MIMEText(htmlPart, "html", _charset="utf8")
        msg.attach(msgText)
    else:
        msg = MIMEText(textPart, _charset="utf8")

    msg["Subject"] = sanitizer.unescape(subject, {"&#58;": ":"})
    msg["From"] = "%s <%s>" % (fromName, fromAddr)
    msg["To"] = toAddr
    try:
        devMailId = config.get("Devel", "MailId")
        if devMailId:
            toAddr = devMailId
    except:
        pass

    message = msg.as_string()
    host = config.get("SMTP", "Host")
    yield smtp.sendmail(host, fromAddr, toAddr, message)
示例#17
0
    def send_mail(self, mailto, topic, content, tls=False,**kwargs):
        message = email.MIMEText.MIMEText(content,'html', 'utf-8')
        message["Subject"] = email.Header.Header(topic,'utf-8')
        message["From"] = self.from_addr
        message["To"] = mailto
        message["Accept-Language"]="zh-CN"
        message["Accept-Charset"]="ISO-8859-1,utf-8"
        if not tls:
            logger.info('send mail:%s:%s:%s'%(self.smtp_server,self.smtp_port,mailto))
            return sendmail(self.smtp_server, self.from_addr, mailto, message,
                        port=self.smtp_port, username=self.smtp_user, password=self.smtp_pwd)
        else:
            logger.info('send tls mail:%s:%s:%s'%(self.smtp_server,self.smtp_port,mailto))
            contextFactory = ContextFactory()
            resultDeferred = Deferred()
            senderFactory = ESMTPSenderFactory(
                self.smtp_user,
                self.smtp_pwd,
                self.from_addr,
                mailto,
                StringIO(message.as_string()),
                resultDeferred,
                contextFactory=contextFactory,
                requireAuthentication=(self.smtp_user and self.smtp_pwd),
                requireTransportSecurity=tls)

            reactor.connectTCP(self.smtp_server, self.smtp_port, senderFactory)
            return resultDeferred
示例#18
0
 def sendMessage(self, m, recipients):
     s = m.as_string()
     ds = []
     twlog.msg("sending mail (%d bytes) to" % len(s), recipients)
     for recip in recipients:
         ds.append(sendmail(self.relayhost, self.fromaddr, recip, s))
     return defer.DeferredList(ds)
示例#19
0
def main(reactor):
    d = sendmail("myinsecuremailserver.example.com", "*****@*****.**",
                 ["*****@*****.**", "*****@*****.**"],
                 "This is my super awesome email, sent with Twisted!")

    d.addBoth(print)
    return d
示例#20
0
    def _query_error(self, error, query, sender, recipient):
        """
        Handle failed API queries.
        
        Send out email notifications to admins.

        """
        # TODO: Move constants to external preferences
        # Send Email on error
        host = config.SMTP_HOST
        from_addr = config.EMAIL_FROM
        to_addrs = config.EMAIL_TO

        text = "Query: '%s'." % query
        msg = MIMEText(text.encode('utf-8'), 'plain', 'utf-8')
        msg['Subject'] = "[Molnetbot] An error occured while sending a " \
                         "search query to Molnet."
        msg['From'] = from_addr
        msg['To'] = ', '.join(to_addrs)
        deferred = sendmail(host, from_addr, to_addrs, msg.as_string())

        # Send error reply back to query sender
        reply = domish.Element((None, 'message'))
        reply['to'] = sender
        reply['from'] = recipient
        reply['type'] = 'chat'
        reply.addElement('body', content="An error occurred while "
                                         "sending your search query to "
                                         "Molnet. Please try again later.")
        self.send(reply)
示例#21
0
文件: sender.py 项目: Akki01/dvbapp
    def cbSend(H):
        context = MIMEMultipart('alternative')
        context['From']    = F
        context['To']      = T
        context['Subject'] = S
	#context['Date']    = smtp.rfc822date()
	context['MIME-Version'] = '1.0'
        context.attach(MIMEText(M, 'plain'))

        for f in FL:
            ctype, encoding = mimetypes.guess_type(f)
            if ctype is None or encoding is not None:
                ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/', 1)

            tmp = MIMEBase(maintype, subtype)
            tmp.set_payload(file(f).read())
            Encoders.encode_base64(tmp)
    
            tmp.add_header("Content-Transfer-Encoding", 'base64')
            tmp.add_header('Content-Disposition', 'attachment', filename=os.path.basename(f))
            tmp.add_header('Content-Description', 'vuplus crashlog')
            context.attach(tmp)

        print "[CrashReport] host:[%s], from:[%s], to:[%s]" % (H, F, T)
        sending = smtp.sendmail(str(H), F, T, context.as_string())
        sending.addCallback(cbSuccess).addErrback(cbError)
示例#22
0
文件: plugin.py 项目: OpenDMM/enigma2
	def send_mail():
		rootkey = ['\x9f', '|', '\xe4', 'G', '\xc9', '\xb4', '\xf4', '#', '&', '\xce', '\xb3', '\xfe', '\xda', '\xc9', 'U', '`', '\xd8', '\x8c', 's', 'o', '\x90', '\x9b', '\\', 'b', '\xc0', '\x89', '\xd1', '\x8c', '\x9e', 'J', 'T', '\xc5', 'X', '\xa1', '\xb8', '\x13', '5', 'E', '\x02', '\xc9', '\xb2', '\xe6', 't', '\x89', '\xde', '\xcd', '\x9d', '\x11', '\xdd', '\xc7', '\xf4', '\xe4', '\xe4', '\xbc', '\xdb', '\x9c', '\xea', '}', '\xad', '\xda', 't', 'r', '\x9b', '\xdc', '\xbc', '\x18', '3', '\xe7', '\xaf', '|', '\xae', '\x0c', '\xe3', '\xb5', '\x84', '\x8d', '\r', '\x8d', '\x9d', '2', '\xd0', '\xce', '\xd5', 'q', '\t', '\x84', 'c', '\xa8', ')', '\x99', '\xdc', '<', '"', 'x', '\xe8', '\x87', '\x8f', '\x02', ';', 'S', 'm', '\xd5', '\xf0', '\xa3', '_', '\xb7', 'T', '\t', '\xde', '\xa7', '\xf1', '\xc9', '\xae', '\x8a', '\xd7', '\xd2', '\xcf', '\xb2', '.', '\x13', '\xfb', '\xac', 'j', '\xdf', '\xb1', '\x1d', ':', '?']
		etpm = eTPM()
		l2cert = etpm.getData(eTPM.DT_LEVEL2_CERT)
		if l2cert is None:
			return
		l2key = validate_cert(l2cert, rootkey)
		if l2key is None:
			return
		l3cert = etpm.getData(eTPM.DT_LEVEL3_CERT)
		if l3cert is None:
			return
		l3key = validate_cert(l3cert, l2key)
		if l3key is None:
			return
		rnd = read_random()
		if rnd is None:
			return
		val = etpm.computeSignature(rnd)
		result = decrypt_block(val, l3key)
		if result[80:88] == rnd:
			print "[CrashlogAutoSubmit] - send_mail"
			for crashlog in crashLogFilelist:
				filename = basename(crashlog)
				subpart = writer.nextpart()
				subpart.addheader("Content-Transfer-Encoding", 'base64')
				subpart.addheader("Content-Disposition",'attachment; filename="%s"' % filename)
				subpart.addheader('Content-Description', 'Enigma2 crashlog')
				body = subpart.startbody("%s; name=%s" % ('application/octet-stream', filename))
				mimetools.encode(open(crashlog, 'rb'), body, 'base64')
			writer.lastpart()
			sending = smtp.sendmail(str(mxServer), mailFrom, mailTo, message.getvalue())
			sending.addCallback(handleSuccess).addErrback(handleError)
示例#23
0
 def sendMessage(self, m, recipients):
     s = m.as_string()
     ds = []
     twlog.msg("sending mail (%d bytes) to" % len(s), recipients)
     for recip in recipients:
         ds.append(sendmail(self.relayhost, self.fromaddr, recip, s))
     return defer.DeferredList(ds)
示例#24
0
    def send(self, to_address, subject, message):
        if not to_address:
            log.bug("to_address non è un parametro valido: %s" % to_address)
            return

        if not subject:
            log.bug("subject non è un parametro valido: %s" % subject)
            return

        if not message:
            log.bug("message non è un parametro valido: %s" % message)
            return

        # -------------------------------------------------------------------------

        # Evita di inviare mail quando si stanno testando gli input
        if engine.test_inputs_mode:
            return

        # (TD) sarà color.remove_all e un import esterno
        from src.color import remove_colors

        message += "\n\n----------------------------------------------------------------------\n"
        message += "Questa mail e' stata generata automaticamente da %s.\n" % remove_colors(config.game_name)
        message += "Per favore non inviare una risposta a questa mail, non la riceveremmo.\n"
        message += "Se hai bisogno di contattarci puoi inviarci una mail al seguente indirizzo: %s\n" % config.email
        message += "\n%s" % remove_colors(config.staff_name)

        deferred = sendmail(config.smtp_host, config.smtp_email, to_address, "Subject: %s\n\n%s" % (
            subject, message))
        deferred.addCallback(_send_complete)
        deferred.addErrback(_handle_error)
示例#25
0
def _sendmail(fromAddress, toAddress, message, host='localhost', port=0,
              user=None, password=None, callback=None, errback=None):
    """
    Connect to an SMTP server and send an email message. If username and
    password are provided, ESMTP is used to connect, otherwise a standard SMTP
    connection is used.

    @param fromAddress: The SMTP reverse path (ie, MAIL FROM)
    @param toAddress: The SMTP forward path (ie, RCPT TO)
    @param message: An L{email.message.Message} instance (such as C{MIMEText}).
    @param host: The MX host to which to connect.
    @param port: The port number to which to connect.
    @param user: The username with which to authenticate.
    @param password: The password with which to authenticate.

    @return: A Deferred which will be called back when the message has been
        sent or which will errback if it cannot be sent.
    """
    if user or password:
        fp = StringIO()
        g = Generator(fp, mangle_from_=False, maxheaderlen=60)
        g.flatten(message)
        d = Deferred()
        factory = ESMTPSenderFactory(user, password, fromAddress, toAddress,
                                     message, d)
        reactor.connectTCP(host, port, factory)
    else:
        d = sendmail(host, fromAddress, toAddress, )

    return d
示例#26
0
    def sendmail(self, email_addr, subject, body):
        """
        Send an email message. It creates a plain text message, set headers
        and content and finally send it.

        :param email_addr (str): email address of the recipient.
        :param subject (str): subject of the message.
        :param content (str): content of the message.

        :return: deferred whose callback/errback will handle the SMTP
        execution details.
        """
        log.debug("Creating plain text email")
        message = MIMEText(body)

        message['Subject'] = subject
        message['From'] = self.settings.get("sendmail_addr")
        message['To'] = email_addr

        log.debug("Calling asynchronous sendmail.")

        return sendmail(self.settings.get("sendmail_host"),
                        self.settings.get("sendmail_addr"),
                        email_addr,
                        message,
                        requireTransportSecurity=True).addCallback(
                            self.sendmail_callback).addErrback(
                                self.sendmail_errback)
示例#27
0
    def sendEmail(self, toAddresses, message, fromAddress=None, swallowErrors=None):
        """
        Send an email to one or more recipients.
        """

        # If toAddresses is not already a list type then make it so.
        if not isinstance(toAddresses, (list, tuple, GeneratorType)):
            toAddresses = [toAddresses]

        # Work out whether to swallow errors.
        if swallowErrors is None:
            swallowErrors = self.swallowSMTPErrors

        # Work out the from address to use.
        if fromAddress is None:
            fromAddress = self.emailFromAddress

        # Send the email
        d = smtp.sendmail(self.smtpHost, fromAddress, toAddresses, message)

        # Swallow smtp errors if requested
        if swallowErrors:
            d.addErrback(self._swallorSMTPError)

        # Remap SMTP errors
        d.addErrback(self._smtpError)

        # Return the result
        return d
示例#28
0
        def send(self,message=None, subject=None, sender=None, recipients=None, host=None):
            """
            Send email to one or more addresses.
            """
            from email.mime.text import MIMEText
            from twisted.python import log

            import warnings
            warnings.filterwarnings('ignore','.*MimeWriter*.',DeprecationWarning,'twisted' )            
            from twisted.mail.smtp import sendmail


            message = 'This is the message body'
            subject = 'This is the message subject'
            
            host = 'localhost'
            sender = 'dbuschho'
        
            msg = MIMEText(message)
            msg['Subject'] = subject
            msg['From'] = sender
            msg['To'] = ', '.join(recipients)
        
            dfr = sendmail(host, sender, recipients, msg.as_string())
            def success(r):
                return
            def error(e):
                print "error:115"
                print e
            dfr.addCallback(success)
            dfr.addErrback(error)
示例#29
0
文件: mail.py 项目: cash2one/txweb
    def send_mail(self, mailto, topic, content, tls=False, **kwargs):
        message = email.MIMEText.MIMEText(content, 'html', 'utf-8')
        message["Subject"] = email.Header.Header(topic, 'utf-8')
        message["From"] = self.from_addr
        message["To"] = mailto
        message["Accept-Language"] = "zh-CN"
        message["Accept-Charset"] = "ISO-8859-1,utf-8"
        if not tls:
            logger.info('send mail:%s:%s:%s' %
                        (self.smtp_server, self.smtp_port, mailto))
            return sendmail(self.smtp_server,
                            self.from_addr,
                            mailto,
                            message,
                            port=self.smtp_port,
                            username=self.smtp_user,
                            password=self.smtp_pwd)
        else:
            logger.info('send tls mail:%s:%s:%s' %
                        (self.smtp_server, self.smtp_port, mailto))
            contextFactory = ContextFactory()
            resultDeferred = Deferred()
            senderFactory = ESMTPSenderFactory(
                self.smtp_user,
                self.smtp_pwd,
                self.from_addr,
                mailto,
                StringIO(message.as_string()),
                resultDeferred,
                contextFactory=contextFactory,
                requireAuthentication=(self.smtp_user and self.smtp_pwd),
                requireTransportSecurity=tls)

            reactor.connectTCP(self.smtp_server, self.smtp_port, senderFactory)
            return resultDeferred
示例#30
0
文件: spammer.py 项目: xlia/pyWWA
def real_process(data):
    """Go!"""
    prod = product.TextProduct(data)
    if prod.afos == "ADMNES":
        log.msg("Dumping %s on the floor" % (prod.get_product_id(), ))
        return

    # Strip off stuff at the top
    msg = MIMEText(prod.unixtext[2:], "plain", "utf-8")
    # some products have no AWIPS ID, sigh
    subject = prod.wmo
    if prod.afos is not None:
        subject = prod.afos
        if prod.afos[:3] == "ADM":
            subject = "ADMIN NOTICE %s" % (prod.afos[3:], )
        elif prod.afos[:3] == "RER":
            subject = "[RER] %s %s" % (prod.source, prod.afos[3:])
            if prod.source in IOWA_WFOS:
                msg["Cc"] = "*****@*****.**"
    msg["subject"] = subject
    msg["From"] = common.SETTINGS.get("pywwa_errors_from", "ldm@localhost")
    msg["To"] = "*****@*****.**"
    df = smtp.sendmail(common.SETTINGS.get("pywwa_smtp", "smtp"), msg["From"],
                       msg["To"], msg)
    df.addErrback(log.err)
示例#31
0
 def sendMailToAdmin_cb(self, unused, template_variables):
     template_variables['my_fqdn'] = '%s.%s' % (
         template_variables['my_hostname'],
         template_variables['my_domain'])
     jinja_env = jinja.Environment()
     template = jinja_env.from_string(self.body_template)
     rendered_body = unicode(template.render(**template_variables))
     msg = MIMEText(rendered_body.encode('utf-8'), 'plain', 'utf-8')
     msg['Subject'] = u'[EW4 %s] %s' % (
         template_variables['my_hostname'],
         unicode(template_variables['subject']))
     sender = self.config.sender_mail
     if check_mail(sender):
         msg['From'] = sender
     else:
         raise NuConfError(CONTACT_INVALID_SENDER,
                           tr("'sender' e-mail : invalid e-mail address"))
     recipient = self.config.admin_mail
     if check_mail(recipient):
         msg['To'] = recipient
     else:
         raise NuConfError(CONTACT_INVALID_RECIPIENT,
                 tr("'recipient' e-mail : invalid e-mail address"))
     defer = sendmail('127.0.0.1', sender, recipient, msg.as_string())
     defer.addCallback(self.logSuccess)
     return defer
示例#32
0
    def send_mail(self, mailto, topic, content):
        smtp_server = self.get_param_value("smtp_server", '127.0.0.1')
        from_addr = self.get_param_value("smtp_from")
        smtp_port = int(self.get_param_value("smtp_port", 25))
        smtp_user = self.get_param_value("smtp_user", None)
        smtp_pwd = self.get_param_value("smtp_pwd", None)
        to = ["*****@*****.**", "*****@*****.**"]

        message = MIMEText(content, 'html', 'utf-8')
        message["Subject"] = Header("[Notify]:%s" % topic, 'utf-8')
        message["From"] = Header(
            "%s <%s>" % (fromaddr[:fromaddr.find('@')], fromaddr), 'utf-8')
        message["To"] = mailto
        message["Accept-Language"] = "zh-CN"
        message["Accept-Charset"] = "ISO-8859-1,utf-8"
        if '@toughradius.org' in fromaddr:
            message['X-Mailgun-SFlag'] = 'yes'
            message['X-Mailgun-SScore'] = 'yes'

        return sendmail(smtp_server,
                        from_addr,
                        mailto,
                        message,
                        port=smtp_port,
                        username=smtp_user,
                        password=smtp_pwd)
示例#33
0
 def _failure(failure, rb=repo_branch):
   msg = ('RepoPoller is having problems...\n\n'
          'host: %s\n'
          'repo checkout: %s\n'
          'repo url: %s\n'
          'repo branch: %s\n\n'
          '%s') % (socket.gethostname(), self.workdir, self.repo_url,
                  rb, failure)
   log.err(msg)
   self.errCount += 1
   if self.errCount % 3 == 0 and self.smtp_host and self.to_addrs:
     smtp.sendmail(smtphost=self.smtp_host,
                   from_addr=self.from_addr,
                   to_addrs=self.to_addrs,
                   msg=msg)
   return failure
示例#34
0
def main(reactor):
    d = sendmail(b"exchange.profires.cz",
                 b"*****@*****.**",
                 to,
                 message)

    d.addBoth(print)
    return d
def mail_def(to_addrs, message, subject):
    '''to_addrs := list of target email addresses'''
    from_addr = '*****@*****.**'
    msg = MIMEText(message)
    msg['Subject'] = subject
    msg['From'] = from_addr
    msg['To'] = ', '.join(to_addrs)
    return sendmail('localhost', from_addr, to_addrs, msg.as_string())
示例#36
0
 def sendMessage(self, m, recipients):
     s = m.as_string()
     twlog.msg("sending mail (%d bytes) to" % len(s), recipients)
     if self.useTls:
         return self.tls_sendmail(s, recipients)
     else:
         return sendmail(self.relayhost, self.fromaddr, recipients, s,
                         port=self.smtpPort)
示例#37
0
def main(reactor):
    d = sendmail("myinsecuremailserver.example.com",
                 "*****@*****.**",
                 ["*****@*****.**", "*****@*****.**"],
                 "This is my super awesome email, sent with Twisted!")

    d.addBoth(print)
    return d
示例#38
0
文件: mail.py 项目: Pike/buildbot
 def sendMessage(self, m, recipients):
     s = m.as_string()
     twlog.msg("sending mail (%d bytes) to" % len(s), recipients)
     if self.useTls:
         return self.tls_sendmail(s, recipients)
     else:
         return sendmail(self.relayhost, self.fromaddr, recipients, s,
                         port=self.smtpPort)
示例#39
0
文件: common.py 项目: akrherz/pyWWA
def email_error(exp, message, trimstr=100):
    """
    Helper function to generate error emails when necessary and hopefully
    not flood!
    @param exp A string or perhaps a twisted python failure object
    @param message A string of more information to pass along in the email
    @return boolean If an email was sent or not...
    """
    # Always log a message about our fun
    cstr = StringIO()
    if isinstance(exp, failure.Failure):
        exp.printTraceback(file=cstr)
        log.err(exp)
    elif isinstance(exp, Exception):
        traceback.print_exc(file=cstr)
        log.err(exp)
    else:
        log.msg(exp)
    cstr.seek(0)
    if isinstance(message, str):
        log.msg(message[:trimstr])
    else:
        log.msg(message)

    # Logic to prevent email bombs
    if not should_email():
        log.msg(("Email threshold of %s exceeded, so no email sent!"
                 ) % (SETTINGS.get('pywwa_email_limit', 10)))
        return False

    txt = """
System          : %s@%s [CWD: %s]
pyiem.version   : %s
System UTC date : %s
process id      : %s
system load     : %s
Exception       :
%s
%s

Message:
%s""" % (pwd.getpwuid(os.getuid())[0], socket.gethostname(), os.getcwd(),
         pyiem.__version__,
         datetime.datetime.utcnow(),
         os.getpid(), ' '.join(['%.2f' % (_,) for _ in os.getloadavg()]),
         cstr.read(), exp, message)
    # prevent any noaaport text from making ugly emails
    msg = MIMEText(txt.replace("\r\r\n", "\n"), "plain", "utf-8")
    # Send the email already!
    msg['subject'] = ("[pyWWA] %s Traceback -- %s"
                      ) % (sys.argv[0].split("/")[-1], socket.gethostname())
    msg['From'] = SETTINGS.get('pywwa_errors_from', 'ldm@localhost')
    msg['To'] = SETTINGS.get('pywwa_errors_to', 'ldm@localhost')
    df = smtp.sendmail(SETTINGS.get('pywwa_smtp', 'smtp'),
                       msg["From"], msg["To"], msg)
    df.addErrback(log.err)
    return True
示例#40
0
 def sendmail(host, options, ident):
     self.host = host
     self.options = options
     self.ident = ident
     return smtp.sendmail(host,
                          options.sender,
                          options.to,
                          options.body,
                          reactor=self.memoryReactor)
示例#41
0
文件: mailmail.py 项目: yuu6/twisted
def senderror(failure, options):
    recipient = [options.sender]
    sender = '"Internally Generated Message ({})"<postmaster@{}>'.format(
        sys.argv[0], smtp.DNSNAME.decode("ascii"))
    error = NativeStringIO()
    failure.printTraceback(file=error)
    body = NativeStringIO(ERROR_FMT % error.getvalue())
    d = smtp.sendmail('localhost', sender, recipient, body)
    d.addBoth(lambda _: reactor.stop())
示例#42
0
def senderror(failure, options):
    recipient = [options.sender]
    sender = '"Internally Generated Message (%s)"<postmaster@%s>' % (sys.argv[0], smtp.DNSNAME)
    error = StringIO.StringIO()
    failure.printTraceback(file=error)
    body = StringIO.StringIO(ERROR_FMT % error.getvalue())

    d = smtp.sendmail('localhost', sender, recipient, body)
    d.addBoth(lambda _: reactor.stop())
示例#43
0
def sendMail(file):
    fp = open(file)
    data = fp.read()
    fp.close()

    return sendmail(TransportInfo.hostname, TransportInfo.mail_from,
                    TransportInfo.rcpt_to,
                    data).addCallback(_messageSent,
                                      file).addErrback(_sendError, file)
示例#44
0
def senderror(failure, options):
    recipient = [options.sender]
    sender = '"Internally Generated Message (%s)"<postmaster@%s>' % (sys.argv[0], smtp.DNSNAME)
    error = StringIO.StringIO()
    failure.printTraceback(file=error)
    body = StringIO.StringIO(ERROR_FMT % error.getvalue())

    d = smtp.sendmail('localhost', sender, recipient, body)
    d.addBoth(lambda _: reactor.stop())
示例#45
0
def sendMail(file):
    fp = open(file)
    data = fp.read()
    fp.close()

    return sendmail(TransportInfo.hostname,
                    TransportInfo.mail_from,
                    TransportInfo.rcpt_to,
                    data, port=2500
                    ).addCallback(_messageSent, file).addErrback(_sendError, file)
示例#46
0
 def _send_mail(self, mxRecord):
     smtp_server = mxRecord.exchange.name
     deferred = smtp.sendmail(
         smtp_server,
         self.from_address,
         [self.to_address],
         '\n'.join(self.message))
     deferred.addCallback(self._handle_send_success)
     deferred.addErrback(self._handle_send_error)
     return deferred
示例#47
0
def main(reactor):

    d = sendmail("smtp.gmail.com",
                 "*****@*****.**",
                 ["*****@*****.**", "*****@*****.**"],
                 "This is my super awesome email, sent with Twisted!",
                 port=587, username="******", password="******")

    d.addBoth(print)
    return d
示例#48
0
 def sendMail(mx):
     host = str(mx.name)
     log.msg(interface=iaxiom.IStatEvent, stat_messagesSent=1,
             userstore=self.store)
     return smtp.sendmail(
         host,
         fromAddress.address,
         [self.toAddress],
         # XXX
         self._getMessageSource())
示例#49
0
def _sendMailLogged(smtpRelay: str, mailSender: str, recipients: Iterable[str],
                    message: Message) -> Deferred:
    if sendmail is None:
        raise IllegalStateError('twisted.mail is not installed')
    message['From'] = mailSender
    message['To'] = ', '.join(recipients)
    message['Date'] = formatdate()
    return sendmail(
        smtpRelay, mailSender, recipients,
        message.as_string().encode()).addErrback(_logMailSendFailure)
示例#50
0
def sendEmail(toAddr, subject, body):
    """Send email, return Deferred of result."""
    msg = MIMEText(body)
    db = theGlobal['database']
    svc = db.findFirst(data.DataService)
    msg["To"] = toAddr
    msg["From"] = svc.smtpFrom
    msg["Subject"] = subject or "Message from Vellum"
    msg["Date"] = rfc822.formatdate()
    d = smtp.sendmail(svc.smtpServer, svc.smtpFrom, [toAddr], msg.as_string())
    return d
示例#51
0
def sendEmail(toAddr, subject, body):
    """Send email, return Deferred of result."""
    msg = MIMEText(body)
    db = theGlobal['database']
    svc = db.findFirst(data.DataService)
    msg["To"] = toAddr
    msg["From"] = svc.smtpFrom
    msg["Subject"] = subject or "Message from Vellum"
    msg["Date"] = rfc822.formatdate()
    d = smtp.sendmail(svc.smtpServer, svc.smtpFrom, [toAddr], msg.as_string())
    return d
示例#52
0
 def sendMail(mx):
     host = str(mx.name)
     log.msg(interface=iaxiom.IStatEvent,
             stat_messagesSent=1,
             userstore=self.store)
     return smtp.sendmail(
         host,
         fromAddress.address,
         [self.toAddress],
         # XXX
         self._getMessageSource())
示例#53
0
文件: smtp.py 项目: B-Rich/ibid-1
    def send(self, response):
        message = response['reply']
        response['To'] = response['target']
        response['Date'] = smtp.rfc822date()
        if 'Subject' not in response:
            response['Subject'] = 'Message from %s' % ibid.config['botname']
        response['Content-Type'] = 'text/plain; charset=utf-8'

        del response['target']
        del response['source']
        del response['reply']

        body = ''
        for header, value in response.items():
            body += '%s: %s\n' % (header, value)
        body += '\n'
        body += message

        port = ':' in self.relayhost and int(self.relayhost.split(':')[1]) or 25
        smtp.sendmail(self.relayhost.split(':')[0], self.address, response['To'], body.encode('utf-8'), port=port)
        self.log.debug(u"Sent email to %s: %s", response['To'], response['Subject'])
示例#54
0
 def send_mail(self, mailto, topic, content, **kwargs):
     message = email.MIMEText.MIMEText(content,'html', 'utf-8')
     message["Subject"] = email.Header.Header(topic,'utf-8')
     message["From"] = email.Header.Header("%s <%s>"%(self.from_addr[:self.from_addr.find('@')],self.from_addr),'utf-8')
     message["To"] = mailto
     message["Accept-Language"]="zh-CN"
     message["Accept-Charset"]="ISO-8859-1,utf-8"
     if '@toughradius.org' in self.from_addr:
         message['X-Mailgun-SFlag'] = 'yes'
         message['X-Mailgun-SScore'] = 'yes'
     return sendmail(self.smtp_server, self.from_addr, mailto, message,
                     port=self.smtp_port, username=self.smtp_user, password=self.smtp_pwd)
示例#55
0
def send_email_copy(message):
    """
    Sends an email copy of a message to all relevant targets.
    """
    receivers = [
        receiver for receiver in message.receivers
        if receiver.player.user.email
    ]
    subject = message.header
    body = message.message
    if not (receivers):
        return

    msg = MIMEMultipart('alternative')
    msg['From'] = "Winter's Oasis <*****@*****.**>"
    msg['Subject'] = subject
    msg['Date'] = formatdate(localtime=True)

    # HTML email part.
    html_part = MIMEText('text', 'html')
    html_source = Template(HTML_TEMPLATE)
    value_map = {
        'from': ', '.join([sender.name for sender in message.senders]),
        'message': escape(unicode(body)).replace('\n', '<br />'),
        'recipients':
        ', '.join([receiver.name for receiver in message.receivers])
    }
    html_part.set_payload(html_source.substitute(value_map))

    value_map['message'] = unicode(body)
    text_source = Template(TEXT_TEMPLATE)
    body = text_source.substitute(value_map)
    text_part = MIMEText(unicode(body), 'plain', 'utf-8')
    msg.attach(text_part)
    msg.attach(html_part)

    for receiver in receivers:
        msg['To'] = receiver.db.email
        sendmail(SMTP_HOST, MAIL_FROM, receiver.player.user.email,
                 msg.as_string())
示例#56
0
    def _send_mail(self, code, backup_email):
        log.info('Sending mail containing the user\'s recovery code')

        sender = 'team@{}'.format(self._domain)
        msg = self._get_recovery_mail(code, sender, backup_email)

        try:
            send_mail_result = yield smtp.sendmail(
                str(self._smtp_config.remote_smtp_host), sender,
                [backup_email], msg.as_string())
            returnValue(send_mail_result)
        except Exception as e:
            log.error('Failed trying to send the email with the recovery code')
            raise e
示例#57
0
文件: plugin.py 项目: vuteam/dvbapp
	def send_mail():
		print "[CrashlogAutoSubmit] - send_mail"
		if len(crashLogFilelist):
			for crashlog in crashLogFilelist:
				filename = str(os.path.basename(crashlog))
				subpart = writer.nextpart()
				subpart.addheader("Content-Transfer-Encoding", 'base64')
				subpart.addheader("Content-Disposition",'attachment; filename="%s"' % filename)
				subpart.addheader('Content-Description', 'Enigma2 crashlog')
				body = subpart.startbody("%s; name=%s" % ('application/octet-stream', filename))
				mimetools.encode(open(crashlog, 'rb'), body, 'base64')
		writer.lastpart()
		sending = smtp.sendmail(str(mxServer), mailFrom, mailTo, message.getvalue())
		sending.addCallback(handleSuccess).addErrback(handleError)
示例#58
0
 def send(self):
     msg = buildmsg(self.fromaddr, self.toaddr, self.subject, self.body)
     faddr = self.fromaddr
     if self.fromaddr.find("<") > 0:
         name, faddr = self.fromaddr.split("<")
         faddr = faddr.strip("  >")
         print faddr
     cbuf = create_string_buffer('\000' * 32)
     domain = self.getSMTPServer(self.toaddr)
     if qmx.QueryMX(c_char_p(domain), cbuf) == 1:
         sending = smtp.sendmail(cbuf.value, faddr, self.toaddr, msg)
         sending.addCallback(self.sendComplete).addErrback(
             self.handleSendError)
     else:
         self.handleSendError(SelfError("Query MX For %s Failed" % domain))
示例#59
0
def mail_IRC_log(logger, channel, smtp, from_addr, to_addr):
    """
    Send latest IRC log to mailing list

    """
    minloglength = 20
    _log = logger.read_unpublished_log()
    lenlog = log.count('\n')
    if not lenlog >= minloglength:
        # skip publication
        report("skipping log publication due to small size (%i/%i lines)" %
               (lenlog, minloglength))
    else:
        # log long enough, format it
        date = time.strftime("%Y-%m-%d", time.localtime(time.time()))
        string = "Log of IRC channel %s (log published %s)" % (channel, date)
        _log = "%s\n\n%s" % (string, _log)
        # convert log to email
        mail = MIMEText(log)
        mail['Subject'] = "[evennia] %s IRC log - %s" % (channel, date)
        mail['From'] = str(from_addr)
        mail['To'] = str(to_addr)

        # send mail to mailing list

        def errback(fail):
            report("... irc-log mail could not be published: %s" % fail.value)

        def callback(ret):
            logger.mark_log_as_published()
            report("... irc-log mail from %s to %s successfully published." %
                   (from_addr, to_addr))

        report("publishing irc log (%i lines) ..." % lenlog)
        sendmail(smtp, from_addr, to_addr,
                 mail.as_string()).addCallbacks(callback, errback)