Пример #1
0
def sendmail(authenticationUsername, authenticationSecret, fromAddress, toAddress, messageFile, smtpHost, smtpPort=25):
    """
    Sends an email using SSLv3 over SMTP

    @param authenticationUsername: account username
    @param authenticationSecret: account password
    @param fromAddress: the from address field of the email
    @param toAddress: the to address field of the email
    @param messageFile: the message content
    @param smtpHost: the smtp host
    @param smtpPort: the smtp port
    """
    contextFactory = ClientContextFactory()

    # evilaliv3:
    #   in order to understand and before change this settings please
    #   read the comment inside tor2web.utils.ssl
    contextFactory.method = SSL.SSLv23_METHOD

    resultDeferred = defer.Deferred()

    senderFactory = ESMTPSenderFactory(
        authenticationUsername,
        authenticationSecret,
        fromAddress,
        toAddress,
        messageFile,
        resultDeferred,
        contextFactory=contextFactory)

    reactor.connectTCP(smtpHost, smtpPort, senderFactory)

    return resultDeferred
Пример #2
0
def sendmail(config, to, messageFile):
    """
    Sends an email
    """
    contextFactory = ClientContextFactory()

    # evilaliv3:
    #   in order to understand and before change this settings please
    #   read the comment inside tor2web.utils.tls
    contextFactory.method = SSL.SSLv23_METHOD

    resultDeferred = defer.Deferred()

    senderFactory = ESMTPSenderFactory(
        config.smtpuser.encode('utf-8'),
        config.smtppass.encode('utf-8'),
        config.smtpmail,
        to,
        messageFile,
        resultDeferred,
        contextFactory=contextFactory,
        requireAuthentication=True,
        requireTransportSecurity=(config.smtpsecurity != 'SSL'),
        retries=0,
        timeout=15)

    if config.security == "SSL":
        senderFactory = tls.TLSMemoryBIOFactory(contextFactory, True, senderFactory)

    reactor.connectTCP(config.smtpdomain, config.smtpport, senderFactory)

    return resultDeferred
Пример #3
0
def sendmail(authenticationUsername,
             authenticationSecret,
             fromAddress,
             toAddress,
             messageFile,
             smtpHost,
             smtpPort=25):
    """
    """

    contextFactory = ClientContextFactory()
    contextFactory.method = SSL.SSLv3_METHOD

    resultDeferred = Deferred()

    senderFactory = ESMTPSenderFactory(authenticationUsername,
                                       authenticationSecret,
                                       fromAddress,
                                       toAddress,
                                       messageFile,
                                       resultDeferred,
                                       contextFactory=contextFactory)

    reactor.connectTCP(smtpHost, smtpPort, senderFactory)

    return resultDeferred
Пример #4
0
def sendmail(username, password, fromAddress, toAddress, message, smtpHost,
             smtpPort=25):
    """
    @param username: The username with which to authenticate.
    @param password: The password with which to authenticate.
    @param fromAddress: The SMTP reverse path (ie, MAIL FROM)
    @param toAddress: The SMTP forward path (ie, RCPT TO)
    @param message: text containing the headers and body of the message to send.
    @param smtpHost: The MX host to which to connect.
    @param smtpPort: The port number to which to connect.

    @return: A Deferred which will be called back when the message has been
    sent or which will errback if it cannot be sent.
    """
    # Create a context factory which only allows SSLv3 and does not verify
    # the peer's certificate.
    contextFactory = ClientContextFactory()
    contextFactory.method = SSLv3_METHOD
    d = Deferred()
    senderFactory = ESMTPSenderFactory(
        username,
        password,
        fromAddress,
        toAddress,
        StringIO(message),
        d,
        contextFactory=contextFactory)
    reactor.connectTCP(smtpHost, smtpPort, senderFactory)
    return d
Пример #5
0
def sendmail(username,
             password,
             fromAddress,
             toAddress,
             message,
             smtpHost,
             smtpPort=25):
    """
    @param username: The username with which to authenticate.
    @param password: The password with which to authenticate.
    @param fromAddress: The SMTP reverse path (ie, MAIL FROM)
    @param toAddress: The SMTP forward path (ie, RCPT TO)
    @param message: text containing the headers and body of the message to send.
    @param smtpHost: The MX host to which to connect.
    @param smtpPort: The port number to which to connect.

    @return: A Deferred which will be called back when the message has been
    sent or which will errback if it cannot be sent.
    """
    # Create a context factory which only allows SSLv3 and does not verify
    # the peer's certificate.
    contextFactory = ClientContextFactory()
    contextFactory.method = SSLv3_METHOD
    d = Deferred()
    senderFactory = ESMTPSenderFactory(username,
                                       password,
                                       fromAddress,
                                       toAddress,
                                       StringIO(message),
                                       d,
                                       contextFactory=contextFactory)
    reactor.connectTCP(smtpHost, smtpPort, senderFactory)
    return d
Пример #6
0
def sendmail(authenticationUsername, authenticationSecret, fromAddress, toAddress, messageFile, smtpHost, smtpPort=25):
    """
    Sends an email using SSLv3 over SMTP

    @param authenticationUsername: account username
    @param authenticationSecret: account password
    @param fromAddress: the from address field of the email
    @param toAddress: the to address field of the email
    @param messageFile: the message content
    @param smtpHost: the smtp host
    @param smtpPort: the smtp port
    """
    contextFactory = ClientContextFactory()
    contextFactory.method = SSL.SSLv3_METHOD

    resultDeferred = defer.Deferred()

    senderFactory = ESMTPSenderFactory(
        authenticationUsername,
        authenticationSecret,
        fromAddress,
        toAddress,
        messageFile,
        resultDeferred,
        contextFactory=contextFactory)

    reactor.connectTCP(smtpHost, smtpPort, senderFactory)

    return resultDeferred
Пример #7
0
   def send(self, usemime=True):
      log.info("Sending email from "+str(self.sender)+" to "+str(self.to)+" with subject "+str(self.subject))
      contextFactory = ClientContextFactory()
      contextFactory.method = SSLv3_METHOD
         
      if usemime:
         msg = MIMEText(self.message)
         msg["Subject"] = self.subject
         msg["From"] = self.sender
         msg["To"] = self.to
         msgstring = msg.as_string()
      else:
         msgstring = self.message

      d = defer.Deferred()
      senderFactory = ESMTPSenderFactory(
         self.username,
         self.password,
         self.sender.split()[-1],
         self.tolist,
         StringIO(msgstring),
         d,
         contextFactory=contextFactory,
         requireAuthentication=self.needauth,
         requireTransportSecurity=self.tls
      )

      self.reactor = reactor.connectTCP(self.server, self.port, senderFactory)
      return d.addCallbacks(self.end, self.end)
Пример #8
0
    def _sendmail(self, to_addrs, email_msg_file):
        from sshg import config
        deferred = defer.Deferred()
        contextFactory = ClientContextFactory()
        contextFactory.method = SSLv3_METHOD
        if config.notification.smtp_user and config.notification.smtp_pass:
            requireAuthentication = True
        else:
            requireAuthentication = False

        sender_factory = ESMTPSenderFactory(
            config.notification.smtp_user,
            config.notification.smtp_pass,
            config.notification.smtp_from,
            to_addrs,
            email_msg_file,
            deferred,
            retries=5,
            timeout=30,
            contextFactory=contextFactory,
            heloFallback=False,
            requireAuthentication=requireAuthentication,
            requireTransportSecurity=config.notification.use_tls
        )
        reactor.connectTCP(config.notification.smtp_server,
                           config.notification.smtp_port, sender_factory)
        return deferred
Пример #9
0
def sendmail(mailconf, message):
    """Takes a regular dictionary as mailconf, as follows.

    Example::

        mailconf = dict(
            host="smtp.gmail.com",  # required
            port=25,                # optional, default 25 or 587 for SSL/TLS
            username=foo,           # optional, no default
            password=bar,           # optional, no default
            tls=True,               # optional, default False
        )

        d = mail.sendmail(mailconf, msg)
        d.addCallback(on_response)
    """
    if not isinstance(mailconf, types.DictType):
        raise TypeError("mailconf must be a regular python dictionary")

    if not isinstance(message, Message):
        raise TypeError("message must be an instance of cyclone.mail.Message")

    host = mailconf.get("host")

    if isinstance(host, unicode):
        host = str(unicode)

    if not isinstance(host, types.StringType):
        raise ValueError("mailconf requires a 'host' configuration")

    use_tls = mailconf.get("tls")

    if use_tls:
        port = mailconf.get("port", 587)
        contextFactory = ClientContextFactory()
        contextFactory.method = SSLv3_METHOD
    else:
        port = mailconf.get("port", 25)
        contextFactory = None

    if not isinstance(port, types.IntType):
        raise ValueError("mailconf requires a proper 'port' configuration")

    result = Deferred()
    u = mailconf.get("username")
    p = mailconf.get("password")
    factory = ESMTPSenderFactory(u,
                                 p,
                                 quoteaddr(message.from_addr),
                                 message.to_addrs,
                                 message.render(),
                                 result,
                                 contextFactory=contextFactory,
                                 requireAuthentication=(u and p),
                                 requireTransportSecurity=use_tls)

    reactor.connectTCP(host, port, factory)
    return result
Пример #10
0
 def send(self):
     ctx=ClientContextFactory()
     ctx.method=SSLv3_METHOD
     result=Deferred()
     message=StringIO.StringIO(self._message.as_string())        
     sender=ESMTPSenderFactory(self._username, self._password, self._from, self._to, message, result, contextFactory=ctx)
     from twisted.internet import reactor                
     reactor.connectTCP(self._smtphost, self._port, sender)            
     return result
Пример #11
0
def sendmail(mailconf, message):
    """Takes a regular dictionary as mailconf, as follows.

    Example::

        mailconf = dict(
            host="smtp.gmail.com",  # required
            port=25,                # optional, default 25 or 587 for SSL/TLS
            username=foo,           # optional, no default
            password=bar,           # optional, no default
            tls=True,               # optional, default False
        )

        d = mail.sendmail(mailconf, msg)
        d.addCallback(on_response)
    """
    if not isinstance(mailconf, types.DictType):
        raise TypeError("mailconf must be a regular python dictionary")

    if not isinstance(message, Message):
        raise TypeError("message must be an instance of cyclone.mail.Message")

    host = mailconf.get("host")

    if isinstance(host, unicode):
        host = str(unicode)

    if not isinstance(host, types.StringType):
        raise ValueError("mailconf requires a 'host' configuration")

    use_tls = mailconf.get("tls")

    if use_tls:
        port = mailconf.get("port", 587)
        contextFactory = ClientContextFactory()
        contextFactory.method = SSLv3_METHOD
    else:
        port = mailconf.get("port", 25)
        contextFactory = None

    if not isinstance(port, types.IntType):
        raise ValueError("mailconf requires a proper 'port' configuration")

    result = Deferred()
    u = mailconf.get("username")
    p = mailconf.get("password")
    factory = ESMTPSenderFactory(u, p,
                                 quoteaddr(message.from_addr),
                                 message.to_addrs,
                                 message.render(),
                                 result,
                                 contextFactory=contextFactory,
                                 requireAuthentication=(u and p),
                                 requireTransportSecurity=use_tls)

    reactor.connectTCP(host, port, factory)
    return result
Пример #12
0
    def _get_noverify_context(self):
        """
        Use ClientContextFactory directly and set the method if necessary.

        This will perform no host verification at all.
        """
        from twisted.internet.ssl import ClientContextFactory
        context_factory = ClientContextFactory()
        if self.ssl_method is not None:
            context_factory.method = self.ssl_method
        return context_factory.getContext()
Пример #13
0
def sendmail(mailconf, message):
    """Takes a regular dictionary as mailconf, as follows:
    mailconf["host"] = "your.smtp.com" (required)
    mailconf["port"] = 25 (optional, default 25 or 587 for TLS)
    mailconf["username"] = "******" (optional)
    mailconf["password"] = "******" (optional)
    mailconf["ssl"] = True | False (optional, default False)
    mailconf["tls"] = True | False (optional, default False)
    mailconf["retries"] = 0 (optional, default 0)
    mailconf["timeout"] = 30 (optional, default 30)
    """
    if not isinstance(mailconf, types.DictType):
        raise TypeError("mailconf must be a regular python dictionary")
    
    if not isinstance(message, Message):
        raise TypeError("message must be an instance of nuswit.mail.Message")
    
    host = mailconf.get("host")
    if not isinstance(host, types.StringType):
        raise ValueError("mailconf requires a 'host' configuration")
    
    ssl = mailconf.get("ssl", True)
    tls = mailconf.get("tls", True)
    if ssl is True:
        port = mailconf.get("port", 587)
        contextFactory = ClientContextFactory()
        contextFactory.method = SSLv3_METHOD
    else:
        port = mailconf.get("port", 25)
        contextFactory = None
    
    retries = mailconf.get("retries", 0)
    timeout = mailconf.get("timeout", 30)
    
    if not isinstance(port, types.IntType):
        raise ValueError("mailconf requires a proper 'port' configuration")
    
    deferred = Deferred()
    username, password = mailconf.get("username"), mailconf.get("password")
    factory = ESMTPSenderFactory(
        username, password,
        message.from_addr, message.to_addrs, message.render(),
        deferred, contextFactory=contextFactory,
        requireAuthentication=(username and password),
        requireTransportSecurity=tls,
        retries=retries, timeout=timeout)
    
    if not ssl:
        connector = reactor.connectTCP(host, port, factory, timeout=timeout)
    else:
        connector = reactor.connectSSL(host, port, factory, contextFactory, timeout=timeout)
    
    return deferred, connector
Пример #14
0
def sendmail(mailconf, message):
    """Takes a regular dictionary as mailconf, as follows:
    mailconf["host"] = "your.smtp.com" (required)
    mailconf["port"] = 25 (optional, default 25 or 587 for TLS)
    mailconf["username"] = "******" (optional)
    mailconf["password"] = "******" (optional)
    mailconf["ssl"] = True | False (optional, default False)
    mailconf["tls"] = True | False (optional, default False)
    mailconf["retries"] = 0 (optional, default 0)
    mailconf["timeout"] = 30 (optional, default 30)
    """
    if not isinstance(mailconf, types.DictType):
        raise TypeError("mailconf must be a regular python dictionary")
    
    if not isinstance(message, Message):
        raise TypeError("message must be an instance of nuswit.mail.Message")
    
    host = mailconf.get("host")
    if not isinstance(host, types.StringType):
        raise ValueError("mailconf requires a 'host' configuration")
    
    ssl = mailconf.get("ssl", True)
    tls = mailconf.get("tls", True)
    if ssl is True:
        port = mailconf.get("port", 587)
        contextFactory = ClientContextFactory()
        contextFactory.method = SSLv3_METHOD
    else:
        port = mailconf.get("port", 25)
        contextFactory = None
    
    retries = mailconf.get("retries", 0)
    timeout = mailconf.get("timeout", 30)
    
    if not isinstance(port, types.IntType):
        raise ValueError("mailconf requires a proper 'port' configuration")
    
    deferred = Deferred()
    username, password = mailconf.get("username"), mailconf.get("password")
    factory = ESMTPSenderFactory(
        username, password,
        message.from_addr, message.to_addrs, message.render(),
        deferred, contextFactory=contextFactory,
        requireAuthentication=(username and password),
        requireTransportSecurity=tls,
        retries=retries, timeout=timeout)
    
    if not ssl:
        connector = reactor.connectTCP(host, port, factory, timeout=timeout)
    else:
        connector = reactor.connectSSL(host, port, factory, contextFactory, timeout=timeout)
    
    return deferred, connector
Пример #15
0
 def buildProtocol(self, addr):
     cf = ClientContextFactory()
     cf.method = SSLv3_METHOD
     p = self.protocol(self.account, self.src_doc, self.out_doc,
                       self.account.details.get("username", ""),
                       self.account.details.get("password", ""),
                       cf,
                       None, # identify???
                       logsize=30,
                       )
     p.deferred = self.deferred # ???????????
     p.factory = self
     return p
Пример #16
0
def sendmail_async(authenticationUsername,
                   authenticationSecret,
                   fromAddress,
                   toAddress,
                   messageFile,
                   smtpHost,
                   smtpPort=25):
    """
    @param authenticationUsername: The username with which to authenticate.
    @param authenticationSecret: The password with which to authenticate.
    @param fromAddress: The SMTP reverse path (ie, MAIL FROM)
    @param toAddress: The SMTP forward path (ie, RCPT TO)
    @param messageFile: A file-like object containing the headers and body of
    the message to send.
    @param smtpHost: The MX host to which to connect.
    @param smtpPort: The port number to which to connect.

    @return: A Deferred which will be called back when the message has been
    sent or which will errback if it cannot be sent.
    """

    # Create a context factory which only allows SSLv3 and does not verify
    # the peer's certificate.
    contextFactory = ClientContextFactory()
    contextFactory.method = SSLv3_METHOD

    resultDeferred = defer.Deferred()

    senderFactory = ESMTPSenderFactory(authenticationUsername,
                                       authenticationSecret,
                                       fromAddress,
                                       toAddress,
                                       messageFile,
                                       resultDeferred,
                                       contextFactory=contextFactory,
                                       heloFallback=True,
                                       requireTransportSecurity=False,
                                       requireAuthentication=False)

    #pylint: disable-msg=E1101
    s = reactor.connectTCP(smtpHost, smtpPort, senderFactory)

    #pylint: enable-msg=E1101

    def close_socket(d):
        s.disconnect()
        return d

    return resultDeferred.addBoth(close_socket)
Пример #17
0
 def send(self):
     ctx = ClientContextFactory()
     ctx.method = SSLv3_METHOD
     result = Deferred()
     message = StringIO.StringIO(self._message.as_string())
     sender = ESMTPSenderFactory(self._username,
                                 self._password,
                                 self._from,
                                 self._to,
                                 message,
                                 result,
                                 contextFactory=ctx)
     from twisted.internet import reactor
     reactor.connectTCP(self._smtphost, self._port, sender)
     return result
Пример #18
0
    def sendmail(self, fromAddress, toAddress, message):
        """
        @param fromAddress: The SMTP reverse path (ie, MAIL FROM)
        @param toAddress: The SMTP forward path (ie, RCPT TO)
        @param message: A file-like object containing the headers and body of
        the message to send.

        @return: A Deferred which will be called back when the message has been
        sent or which will errback if it cannot be sent.
        """

        if not hasattr(message, 'read'):
            # It's not a file
            message = StringIO(str(message))

        def cancel(d):
            """
            Cancel the L{mandrill.sendmail} call, tell the factory not to
            retry and disconnect the connection.

            @param d: The L{defer.Deferred} to be cancelled.
            """
            senderFactory.sendFinished = True
            if senderFactory.currentProtocol:
                senderFactory.currentProtocol.transport.abortConnection()
            else:
                # Connection hasn't been made yet
                connector.disconnect()

        # Create a context factory which only allows SSLv3 and does not verify
        # the peer's certificate.
        contextFactory = ClientContextFactory()
        contextFactory.method = SSLv3_METHOD

        resultDeferred = Deferred()

        senderFactory = ESMTPSenderFactory(
            self.username,
            self.secret,
            fromAddress,
            toAddress,
            message,
            resultDeferred,
            contextFactory=contextFactory)

        connector = reactor.connectTCP(self.smtpHost, self.smtpPort, senderFactory)

        return resultDeferred
Пример #19
0
def sendmail(username, password, smtpHost, smtpPort, fromEmail, toEmail, subject, body):
    resultDeferred = Deferred()
    contextFactory = ClientContextFactory()
    contextFactory.method = SSLv3_METHOD

    msg = createMessage(fromEmail, toEmail, subject, body)
    senderFactory = ESMTPSenderFactory(
        username,
        password,
        fromEmail,
        toEmail,
        StringIO(msg),
        resultDeferred,
        contextFactory=contextFactory)
    
    reactor.connectTCP(smtpHost, smtpPort, senderFactory)
    return resultDeferred
Пример #20
0
def sendmail(mailconf, message):
    """Takes a regular dictionary as mailconf, as follows:

    mailconf["host"] = "your.smtp.com" (required)
    mailconf["port"] = 25 (optional, default 25 or 587 for TLS)
    mailconf["username"] = "******" (optional)
    mailconf["password"] = "******" (optional)
    mailconf["tls"] = True | False (optional, default False)
    """
    if not isinstance(mailconf, types.DictType):
        raise TypeError("mailconf must be a regular python dictionary")

    if not isinstance(message, Message):
        raise TypeError("message must be an instance of cyclone.mail.Message")

    host = mailconf.get("host")
    if not isinstance(host, types.StringType):
        raise ValueError("mailconf requires a 'host' configuration")

    use_tls = mailconf.get("tls")

    if use_tls:
        port = mailconf.get("port", 587)
        contextFactory = ClientContextFactory()
        contextFactory.method = SSLv3_METHOD
    else:
        port = mailconf.get("port", 25)
        contextFactory = None

    if not isinstance(port, types.IntType):
        raise ValueError("mailconf requires a proper 'port' configuration")

    result = Deferred()
    u = mailconf.get("username")
    p = mailconf.get("password")
    factory = ESMTPSenderFactory(u, p,
                                 message.from_addr,
                                 message.to_addrs,
                                 message.render(),
                                 result,
                                 contextFactory=contextFactory,
                                 requireAuthentication=(u and p),
                                 requireTransportSecurity=use_tls)

    reactor.connectTCP(host, port, factory)
    return result
Пример #21
0
def sendmail(fromEmail, toEmail, subject, body):
    resultDeferred = Deferred()
    contextFactory = ClientContextFactory()
    contextFactory.method = SSLv3_METHOD

    msg = createMessage(fromEmail, toEmail, subject, body)
    senderFactory = ESMTPSenderFactory(
        USERNAME,
        PASSWORD,
        fromEmail,
        toEmail,
        StringIO(msg),
        resultDeferred,
        contextFactory=contextFactory)
    
    reactor.connectTCP('smtp.gmail.com', 587, senderFactory)
    return resultDeferred
Пример #22
0
def sendmail(mailconf, message):
    """Takes a regular dictionary as mailconf, as follows:

    mailconf["host"] = "your.smtp.com" (required)
    mailconf["port"] = 25 (optional, default 25 or 587 for TLS)
    mailconf["username"] = "******" (optional)
    mailconf["password"] = "******" (optional)
    mailconf["tls"] = True | False (optional, default False)
    """
    if not isinstance(mailconf, types.DictType):
        raise TypeError("mailconf must be a regular python dictionary")

    if not isinstance(message, Message):
        raise TypeError("message must be an instance of cyclone.mail.Message")

    host = mailconf.get("host")
    if not isinstance(host, types.StringType):
        raise ValueError("mailconf requires a 'host' configuration")

    use_tls = mailconf.get("tls")

    if use_tls:
        port = mailconf.get("port", 587)
        contextFactory = ClientContextFactory()
        contextFactory.method = SSLv3_METHOD
    else:
        port = mailconf.get("port", 25)
        contextFactory = None

    if not isinstance(port, types.IntType):
        raise ValueError("mailconf requires a proper 'port' configuration")

    result = Deferred()
    username, password = mailconf.get("username"), mailconf.get("password")
    factory = ESMTPSenderFactory(username,
                                 password,
                                 message.from_addr,
                                 message.to_addrs,
                                 message.render(),
                                 result,
                                 contextFactory=contextFactory,
                                 requireAuthentication=(username and password),
                                 requireTransportSecurity=use_tls)

    reactor.connectTCP(host, port, factory)
    return result
Пример #23
0
def sendTwistedMailAuth(host, port, login, password, ssl_flag, need_login, addr, to, subject, filename):
    dhnio.Dprint(14, 'transport_email.sendTwistedMailAuth to:%s ssl:%s auth:%s ' % (str(to),str(ssl_flag), str(need_login)))

    fin = file(filename, 'rb')
    bin_data = fin.read()
    fin.close()

    msg = email.MIMEMultipart.MIMEMultipart()
    msg["Subject"] = subject
    msg["From"]    = addr
    msg["To"]      = to

    part = email.MIMEBase.MIMEBase('application', "octet-stream")
    part.set_payload( bin_data+'end' )
    email.Encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(filename))
    msg.attach(part)


    try:
        port_ = int(port)
    except:
        port_ = 25
    messageText = msg.as_string()
    cf = ClientContextFactory()
    cf.method = SSLv3_METHOD
    result = Deferred()
    factory = MySenderFactory(
        login,
        password,
        addr,
        to,
        StringIO(messageText),
        result,
        contextFactory=cf,
        requireTransportSecurity=ssl_flag,
        requireAuthentication=need_login,)
    if ssl_flag:
        conn = reactor.connectSSL(host, port_, factory, cf)
    else:
        conn = reactor.connectTCP(host, port_, factory)
    return result
Пример #24
0
    def __init__(self, id, request, deferred):
        # Create a context factory which only allows SSLv3 and does not verify
        # the peer's certificate.
        contextFactory = ClientContextFactory()
        contextFactory.method = SSLv3_METHOD

        self.id = id
        self.request = request
        self.deferred = deferred
        self.sentDeferred = Deferred()
        self.sentDeferred.addErrback(self.deferred.errback)

        username = request.args.get("username", [request.getUser()])[0]
        password = request.args.get("password", [request.getPassword()])[0]
        fromEmail = request.args.get("from", username)[0]
        toEmail = request.args.get("to")[0]
        subject = request.args.get("subject")[0]
        message = StringIO.StringIO(
            """\
Date: Fri, 6 Feb 2004 10:14:39 -0800
From: %s
To: %s
Subject: %s

%s
"""
            % (fromEmail, toEmail, subject, request.args.get("body", [""])[0])
        )

        ESMTPSenderFactory.__init__(
            self,
            username,
            password,
            fromEmail,
            toEmail,
            message,
            self.sentDeferred,
            retries=0,
            contextFactory=contextFactory,
            requireAuthentication=False,
            requireTransportSecurity=False,
        )
Пример #25
0
def sendmail(config, messageFile):
    """
    Sends an email using SSLv3 over SMTP

    @param authenticationUsername: account username
    @param authenticationSecret: account password
    @param fromAddress: the from address field of the email
    @param toAddress: the to address field of the email
    @param messageFile: the message content
    @param smtpHost: the smtp host
    @param smtpPort: the smtp port
    """
    contextFactory = ClientContextFactory()

    # evilaliv3:
    #   in order to understand and before change this settings please
    #   read the comment inside tor2web.utils.ssl
    contextFactory.method = SSL.SSLv23_METHOD

    resultDeferred = defer.Deferred()

    senderFactory = ESMTPSenderFactory(
        config.smtpuser.encode('utf-8'),
        config.smtppass.encode('utf-8'),
        config.smtpmail,
        config.smtpmailto_exceptions,
        messageFile,
        resultDeferred,
        contextFactory=contextFactory,
        requireAuthentication=True,
        requireTransportSecurity=(config.smtpsecurity != 'SSL'),
        retries=0,
        timeout=15)

    if config.security == "SSL":
        senderFactory = tls.TLSMemoryBIOFactory(contextFactory, True,
                                                senderFactory)

    reactor.connectTCP(config.smtpdomain, config.smtpport, senderFactory)

    return resultDeferred
Пример #26
0
def sendmail(config, messageFile):
    """
    Sends an email using SSLv3 over SMTP

    @param authenticationUsername: account username
    @param authenticationSecret: account password
    @param fromAddress: the from address field of the email
    @param toAddress: the to address field of the email
    @param messageFile: the message content
    @param smtpHost: the smtp host
    @param smtpPort: the smtp port
    """
    contextFactory = ClientContextFactory()

    # evilaliv3:
    #   in order to understand and before change this settings please
    #   read the comment inside tor2web.utils.ssl
    contextFactory.method = SSL.SSLv23_METHOD

    resultDeferred = defer.Deferred()

    senderFactory = ESMTPSenderFactory(
        config.smtpuser.encode("utf-8"),
        config.smtppass.encode("utf-8"),
        config.smtpmail,
        config.smtpmailto_exceptions,
        messageFile,
        resultDeferred,
        contextFactory=contextFactory,
        requireAuthentication=True,
        requireTransportSecurity=(config.smtpsecurity != "SSL"),
        retries=0,
        timeout=15,
    )

    if config.security == "SSL":
        senderFactory = tls.TLSMemoryBIOFactory(contextFactory, True, senderFactory)

    reactor.connectTCP(config.smtpdomain, config.smtpport, senderFactory)

    return resultDeferred
Пример #27
0
    def send_mail(self, from_address, to_address, message):
        # Create a context factory which only allows SSLv3 and does not verify
        # the peer's certificate.
        context_factory = ClientContextFactory()
        context_factory.method = TLSv1_METHOD

        resultDeferred = Deferred()

        senderFactory = ESMTPSenderFactory(
            self.user,
            self.password,
            from_address,
            to_address,
            message,
            resultDeferred,
            contextFactory=context_factory,
            requireAuthentication=self.use_authentication)

        reactor.connectTCP(self.smtp_host, self.smtp_port, senderFactory)

        return resultDeferred
Пример #28
0
def sendmail(authenticationUsername, authenticationSecret, fromAddress, toAddress, messageFile, smtpHost, smtpPort=25):
    """
    """

    contextFactory = ClientContextFactory()
    contextFactory.method = SSL.SSLv3_METHOD

    resultDeferred = Deferred()

    senderFactory = ESMTPSenderFactory(
        authenticationUsername,
        authenticationSecret,
        fromAddress,
        toAddress,
        messageFile,
        resultDeferred,
        contextFactory=contextFactory)

    reactor.connectTCP(smtpHost, smtpPort, senderFactory)

    return resultDeferred
Пример #29
0
def sendmail(
   authenticationUsername, authenticationSecret,
   fromAddress, toAddress,
   messageFile,
   smtpHost, smtpPort=25, requiredAuth=False
   ):
   """
   @param authenticationUsername: The username with which to authenticate.
   @param authenticationSecret: The password with which to authenticate.
   @param fromAddress: The SMTP reverse path (ie, MAIL FROM)
   @param toAddress: The SMTP forward path (ie, RCPT TO)
   @param messageFile: A file-like object containing the headers and body of
   the message to send.
   @param smtpHost: The MX host to which to connect.
   @param smtpPort: The port number to which to connect.

   @return: A Deferred which will be called back when the message has been
   sent or which will errback if it cannot be sent.
   """

   # Create a context factory which only allows SSLv3 and does not verify
   # the peer's certificate.
   contextFactory = ClientContextFactory()
   contextFactory.method = SSLv3_METHOD

   resultDeferred = Deferred()

   senderFactory = ESMTPSenderFactory(
       authenticationUsername,
       authenticationSecret,
       fromAddress,
       toAddress,
       messageFile,
       resultDeferred,
       contextFactory=contextFactory,
       requireAuthentication=requiredAuth)

   reactor.connectTCP(smtpHost, smtpPort, senderFactory)

   return resultDeferred
Пример #30
0
    def __init__(self, id, request, deferred):
        # Create a context factory which only allows SSLv3 and does not verify
        # the peer's certificate.
        contextFactory = ClientContextFactory()
        contextFactory.method = SSLv3_METHOD

        self.id = id
        self.request = request
        self.deferred = deferred
        self.sentDeferred = Deferred()
        self.sentDeferred.addErrback(self.deferred.errback)

        username = request.args.get('username', [request.getUser()])[0]
        password = request.args.get('password', [request.getPassword()])[0]
        fromEmail = request.args.get('from', username)[0]
        toEmail = request.args.get('to')[0]
        subject = request.args.get('subject')[0]
        message = StringIO.StringIO('''\
Date: Fri, 6 Feb 2004 10:14:39 -0800
From: %s
To: %s
Subject: %s

%s
''' % (fromEmail, toEmail, subject, request.args.get('body', [''])[0]))

        ESMTPSenderFactory.__init__(
            self,
            username,
            password,
            fromEmail,
            toEmail,
            message,
            self.sentDeferred,
            retries=0,
            contextFactory=contextFactory,
            requireAuthentication=False,
            requireTransportSecurity=False,
        )
Пример #31
0
def sendMail(authUsername, authPassword, SMTPHost, SMTPPort, fromEmail, fromDisplayEmail, msg, reactor=None):

    if reactor == None:
        from twisted.internet import reactor

    contextFactory = ClientContextFactory()
    contextFactory.method = SSLv3_METHOD

    resultDeferred = Deferred()

    msg.replace_header("From", fromDisplayEmail)

    msgstring = msg.as_string(unixfrom=True)
    fp = StringIO(msgstring)

    senderFactory = ESMTPSenderFactory(
        authUsername, authPassword, fromEmail, msg.get("To"), fp, resultDeferred, contextFactory=contextFactory)
    senderFactory.noisy = False

    reactor.connectTCP(SMTPHost, SMTPPort, senderFactory)

    return resultDeferred
Пример #32
0
def sendmail(authenticationUsername,
             authenticationSecret,
             fromAddress,
             toAddress,
             messageFile,
             smtpHost,
             smtpPort=25):
    """
    Sends an email using SSLv3 over SMTP

    @param authenticationUsername: account username
    @param authenticationSecret: account password
    @param fromAddress: the from address field of the email
    @param toAddress: the to address field of the email
    @param messageFile: the message content
    @param smtpHost: the smtp host
    @param smtpPort: the smtp port
    """
    contextFactory = ClientContextFactory()

    # evilaliv3:
    #   in order to understand and before change this settings please
    #   read the comment inside tor2web.utils.ssl
    contextFactory.method = SSL.SSLv23_METHOD

    resultDeferred = defer.Deferred()

    senderFactory = ESMTPSenderFactory(authenticationUsername,
                                       authenticationSecret,
                                       fromAddress,
                                       toAddress,
                                       messageFile,
                                       resultDeferred,
                                       contextFactory=contextFactory)

    reactor.connectTCP(smtpHost, smtpPort, senderFactory)

    return resultDeferred
Пример #33
0
    def _send(self, _, to, message):
        """Internal function used to actually send the email.

        :param _: Callback return, ignored.
        :param to: A list of recipients.
        :param message: The message as string.
        """
        d = defer.Deferred()

        sender_factory = self._get_factory(to, StringIO(message), d)
        args = [self._server, self._port, sender_factory]

        if self._ssl:
            func = reactor.connectSSL

            context_factory = ClientContextFactory()
            context_factory.method = SSLv3_METHOD
            args.append(context_factory)
        else:
            func = reactor.connectTCP

        func(*args)

        return d
Пример #34
0
    def _send(self, _, to, message):
        """Internal function used to actually send the email.

        :param _: Callback return, ignored.
        :param to: A list of recipients.
        :param message: The message as string.
        """
        d = defer.Deferred()

        sender_factory = self._get_factory(to, StringIO(message), d)
        args = [self._server, self._port, sender_factory]

        if self._ssl:
            func = reactor.connectSSL

            context_factory = ClientContextFactory()
            context_factory.method = SSLv3_METHOD
            args.append(context_factory)
        else:
            func = reactor.connectTCP

        func(*args)

        return d
Пример #35
0
    def notify(self):
        smtpHost = 'smtp.gmail.com'
        smtpPort = 587
        contextFactory = ClientContextFactory()

        message = MIMEText(self.text)
        message['Subject'] = self.subject
        message['From'] = 'consider Project <' + self.fromAddress + '>'
        message['To'] = ', '.join(self.toAddresses)
        self.messageFile = StringIO.StringIO(message.as_string())

        contextFactory.method = TLSv1_METHOD

        def successCallback(result):
            log.msg('Sending email to ' + str(self.toAddresses) + ' suceeded')

        def errorCallback(result):
            log.err('Sending email to ' + str(self.toAddresses) + ' FAILED')
            log.err(str(result))

        resultDeferred = Deferred()
        resultDeferred.addCallback(successCallback)
        resultDeferred.addErrback(errorCallback)

        senderFactory = ESMTPSenderFactory(
                self.username,
                self.password,
                self.fromAddress,
                ' '.join(self.toAddresses),
                self.messageFile,
                resultDeferred,
                retries=2,
                timeout=10,
                contextFactory = contextFactory)

        reactor.connectTCP(smtpHost, smtpPort, senderFactory)
Пример #36
0
def sendmail(authentication_username,
             authentication_password,
             from_address,
             to_address,
             message_file,
             smtp_host,
             smtp_port,
             security,
             event=None):
    """
    Sends an email using SSLv3 over SMTP

    @param authentication_username: account username
    @param authentication_secret: account password
    @param from_address: the from address field of the email
    @param to_address: the to address field of the email
    @param message_file: the message content its a StringIO
    @param smtp_host: the smtp host
    @param smtp_port: the smtp port
    @param security: may need to be STRING, here is converted at start
    @param event: the event description, needed to keep track of failure/success
    """
    def printError(reason, event):

        # XXX is catch a wrong TCP port, but not wrong SSL protocol, here
        if event:
            log.err("** failed notification within event %s" % event.type)
        # TODO Enhance with retry
        # TODO specify a ticket - make event an Obj instead of a namedtuple
        # TODO It's defined in plugin/base.py

        if isinstance(reason, Failure):
            log.err("Failed to contact %s:%d (Sock Error %s)" %
                    (smtp_host, smtp_port, reason.type))
            log.debug(reason)

    def handle_error(reason, *args, **kwargs):
        # XXX event is not an argument here ?
        printError(reason, event)
        return result_deferred.errback(reason)

    def protocolConnectionLost(self, reason=protocol.connectionDone):
        """We are no longer connected"""
        if isinstance(reason, Failure):
            if not isinstance(reason.value, error.ConnectionDone):
                log.err("Failed to contact %s:%d (ConnectionLost Error %s)" %
                        (smtp_host, smtp_port, reason.type))
                log.debug(reason)

        self.setTimeout(None)
        self.mailFile = None

    def sendError(self, exc):
        if exc.code and exc.resp:
            error = re.match(r'^([0-9\.]+) ', exc.resp)
            error_str = ""
            if error:
                error_str = error.group(1)
                key = str(exc.code) + " " + error.group(1)
                if key in smtp_errors:
                    error_str += " " + smtp_errors[key]

            log.err("Failed to contact %s:%d (SMTP Error: %.3d %s)" %
                    (smtp_host, smtp_port, exc.code, error_str))
            log.debug("Failed to contact %s:%d (SMTP Error: %.3d %s)" %
                      (smtp_host, smtp_port, exc.code, exc.resp))
        SMTPClient.sendError(self, exc)

    try:
        security = str(security)
        result_deferred = Deferred()
        context_factory = ClientContextFactory()
        context_factory.method = SSL.SSLv3_METHOD

        if security != "SSL":
            requireTransportSecurity = True
        else:
            requireTransportSecurity = False

        esmtp_deferred = Deferred()
        esmtp_deferred.addErrback(handle_error, event)
        esmtp_deferred.addCallback(result_deferred.callback)

        factory = ESMTPSenderFactory(
            authentication_username,
            authentication_password,
            from_address,
            to_address,
            message_file,
            esmtp_deferred,
            contextFactory=context_factory,
            requireAuthentication=(authentication_username
                                   and authentication_password),
            requireTransportSecurity=requireTransportSecurity)

        factory.protocol.sendError = sendError
        factory.protocol.connectionLost = protocolConnectionLost

        if security == "SSL":
            factory = tls.TLSMemoryBIOFactory(context_factory, True, factory)

        if GLSetting.tor_socks_enable:
            socksProxy = TCP4ClientEndpoint(reactor, GLSetting.socks_host,
                                            GLSetting.socks_port)
            endpoint = SOCKS5ClientEndpoint(smtp_host.encode('utf-8'),
                                            smtp_port, socksProxy)
        else:
            endpoint = TCP4ClientEndpoint(reactor, smtp_host, smtp_port)

        d = endpoint.connect(factory)
        d.addErrback(handle_error, event)

    except Exception as excep:
        # we strongly need to avoid raising exception inside email logic to avoid chained errors
        log.err("unexpected exception in sendmail: %s" % str(excep))
        return fail()

    return result_deferred
Пример #37
0
def sendmail(authentication_username,
             authentication_password,
             from_address,
             to_address,
             message_file,
             smtp_host,
             smtp_port,
             security,
             event=None):
    """
    Sends an email using SMTPS/SMTP+TLS and torify the connection

    @param authentication_username: account username
    @param authentication_password: account password
    @param from_address: the from address field of the email
    @param to_address: the to address field of the email
    @param message_file: the message content its a StringIO
    @param smtp_host: the smtp host
    @param smtp_port: the smtp port
    @param security: may need to be STRING, here is converted at start
    @param event: the event description, needed to keep track of failure/success
    """

    notif_retries = 2
    notif_timeout = 10

    def printError(method, reason, event):
        if event:
            log.err("** failed notification within event %s" % event.type)

        if isinstance(reason, Failure):
            log.err(
                "Failed to connect to %s:%d (Sock Error: %s) (Method: %s)" %
                (smtp_host, smtp_port, reason.value, method))
            log.debug(reason)

    def esmtp_errback(reason, *args, **kwargs):
        printError("ESMTP", reason, event)
        return result_deferred.errback(reason)

    def socks_errback(reason, *args, **kwargs):
        printError("SOCKS5", reason, event)
        return result_deferred.errback(reason)

    def tcp4_errback(reason, *args, **kwargs):
        printError("TCP4", reason, event)
        return result_deferred.errback(reason)

    def result_errback(reason, *args, **kwargs):
        """To not report an error as unexpected in the log files"""
        return True

    def esmtp_sendError(self, exc):
        if exc.code and exc.resp:
            error_str = ""

            error = re.match(r'^([0-9\.]+) ', exc.resp)
            if error:
                key = str(exc.code) + " " + error.group(1)
                if key in smtp_errors:
                    error_str += " " + smtp_errors[key]

            verb = '[unknown]'
            if 'authentication' in exc.resp:
                verb = 'autenticate'
            if 'not support secure' in exc.resp:
                verb = 'negotiate TLS'

            log.err("Failed to %s to %s:%d (SMTP Code: %.3d) (%s)" %
                    (verb, smtp_host, smtp_port, exc.code, error_str))

        SMTPClient.sendError(self, exc)

    def esmtp_connectionLost(self, reason=protocol.connectionDone):
        """We are no longer connected"""
        if isinstance(reason, Failure):
            if not isinstance(reason.value, error.ConnectionDone):
                verb = 'unknown_verb'
                if 'OpenSSL' in str(reason.type):
                    verb = 'negotiate SSL'

                log.err("Failed to %s to %s:%d (%s)" %
                        (verb, smtp_host, smtp_port, reason.type))
                log.debug(reason)

        self.setTimeout(None)
        self.mailFile = None

    # TODO: validation?
    if from_address == '' or to_address == '':
        log.err(
            "Failed to init sendmail to %s:%s (Invalid from/to addresses)" %
            (from_address, to_address))
        return

    if security != "SSL" and security != "disabled":
        requireTransportSecurity = True
    else:
        requireTransportSecurity = False

    try:
        security = str(security)
        result_deferred = Deferred()
        result_deferred.addErrback(result_errback, event)

        context_factory = ClientContextFactory()

        # evilaliv3:
        #   this is the same solution I applied to tor2web:
        #     as discussed on https://trac.torproject.org/projects/tor/ticket/11598
        #     there is no way of enabling all TLS methods excluding SSL.
        #     the problem lies in the fact that SSL.TLSv1_METHOD | SSL.TLSv1_1_METHOD | SSL.TLSv1_2_METHOD
        #     is denied by OpenSSL.
        #
        #     As spotted by nickm the only good solution right now is to enable SSL.SSLv23_METHOD then explicitly
        #     use options: SSL_OP_NO_SSLv2 and SSL_OP_NO_SSLv3
        #
        #     This trick make openssl consider valid all TLS methods.
        #
        context_factory.method = SSL.SSLv23_METHOD

        esmtp_deferred = Deferred()
        esmtp_deferred.addErrback(esmtp_errback, event)
        esmtp_deferred.addCallback(result_deferred.callback)
    except Exception as excep:
        log.err(
            "Error in Twisted objects init - unexpected exception in sendmail: %s"
            % str(excep))
        return fail()

    try:
        factory = ESMTPSenderFactory(
            authentication_username,
            authentication_password,
            from_address,
            to_address,
            message_file,
            esmtp_deferred,
            contextFactory=context_factory,
            requireAuthentication=(authentication_username
                                   and authentication_password),
            requireTransportSecurity=requireTransportSecurity,
            retries=notif_retries,
            timeout=notif_timeout)

        factory.protocol.sendError = esmtp_sendError
        factory.protocol.connectionLost = esmtp_connectionLost

        if security == "SSL":
            factory = tls.TLSMemoryBIOFactory(context_factory, True, factory)

    except Exception as excep:
        log.err(
            "Error in factory init - unexpected exception in sendmail: %s" %
            str(excep))
        return fail()

    try:
        if not GLSettings.disable_mail_torification and GLSettings.memory_copy.notif_uses_tor:
            socksProxy = TCP4ClientEndpoint(reactor,
                                            GLSettings.socks_host,
                                            GLSettings.socks_port,
                                            timeout=notif_timeout)
            endpoint = SOCKS5ClientEndpoint(smtp_host.encode('utf-8'),
                                            smtp_port, socksProxy)
            d = endpoint.connect(factory)
            d.addErrback(socks_errback, event)
        else:
            endpoint = TCP4ClientEndpoint(reactor,
                                          smtp_host,
                                          smtp_port,
                                          timeout=notif_timeout)
            d = endpoint.connect(factory)
            d.addErrback(tcp4_errback, event)
    except Exception as excep:
        # we strongly need to avoid raising exception inside email logic to avoid chained errors
        log.err("unexpected exception in sendmail: %s" % str(excep))
        return fail()

    return result_deferred
Пример #38
0
def sendmail(authentication_username, authentication_password, from_address,
             to_address, message_file, smtp_host, smtp_port, security, event=None):
    """
    Sends an email using SMTPS/SMTP+TLS and torify the connection

    @param authentication_username: account username
    @param authentication_password: account password
    @param from_address: the from address field of the email
    @param to_address: the to address field of the email
    @param message_file: the message content its a StringIO
    @param smtp_host: the smtp host
    @param smtp_port: the smtp port
    @param security: may need to be STRING, here is converted at start
    @param event: the event description, needed to keep track of failure/success
    """

    notif_retries = 2
    notif_timeout = 10

    def printError(method, reason, event):
        if event:
            log.err("** failed notification within event %s" % event.type)

        if isinstance(reason, Failure):
            log.err("Failed to connect to %s:%d (Sock Error: %s) (Method: %s)" %
                    (smtp_host, smtp_port, reason.value, method))
            log.debug(reason)

    def esmtp_errback(reason, *args, **kwargs):
        printError("ESMTP", reason, event)
        return result_deferred.errback(reason)

    def socks_errback(reason, *args, **kwargs):
        printError("SOCKS5", reason, event)
        return result_deferred.errback(reason)

    def tcp4_errback(reason, *args, **kwargs):
        printError("TCP4", reason, event)
        return result_deferred.errback(reason)

    def result_errback(reason, *args, **kwargs):
        """To not report an error as unexpected in the log files"""
        return True

    def esmtp_sendError(self, exc):
        if exc.code and exc.resp:
            error_str = ""

            error = re.match(r'^([0-9\.]+) ', exc.resp)
            if error:
                key = str(exc.code) + " " + error.group(1)
                if key in smtp_errors:
                    error_str +=  " " + smtp_errors[key]

            verb = '[unknown]'
            if 'authentication' in exc.resp:
                verb = 'autenticate'
            if 'not support secure' in exc.resp:
                verb = 'negotiate TLS'

            log.err("Failed to %s to %s:%d (SMTP Code: %.3d) (%s)" %
                    (verb, smtp_host, smtp_port, exc.code, error_str))

        SMTPClient.sendError(self, exc)

    def esmtp_connectionLost(self, reason=protocol.connectionDone):
        """We are no longer connected"""
        if isinstance(reason, Failure):
            if not isinstance(reason.value, error.ConnectionDone):
                verb = 'unknown_verb'
                if 'OpenSSL' in str(reason.type):
                    verb = 'negotiate SSL'

                log.err("Failed to %s to %s:%d (%s)"
                        % (verb, smtp_host, smtp_port, reason.type))
                log.debug(reason)

        self.setTimeout(None)
        self.mailFile = None

    # TODO: validation?
    if from_address == '' or to_address == '':
        log.err("Failed to init sendmail to %s:%s (Invalid from/to addresses)" %
                (from_address, to_address))
        return

    if security != "SSL" and security != "disabled":
        requireTransportSecurity = True
    else:
        requireTransportSecurity = False

    try:
        security = str(security)
        result_deferred = Deferred()
        result_deferred.addErrback(result_errback, event)

        context_factory = ClientContextFactory()

        # evilaliv3:
        #   this is the same solution I applied to tor2web:
        #     as discussed on https://trac.torproject.org/projects/tor/ticket/11598
        #     there is no way of enabling all TLS methods excluding SSL.
        #     the problem lies in the fact that SSL.TLSv1_METHOD | SSL.TLSv1_1_METHOD | SSL.TLSv1_2_METHOD
        #     is denied by OpenSSL.
        #
        #     As spotted by nickm the only good solution right now is to enable SSL.SSLv23_METHOD then explicitly
        #     use options: SSL_OP_NO_SSLv2 and SSL_OP_NO_SSLv3
        #
        #     This trick make openssl consider valid all TLS methods.
        #
        context_factory.method = SSL.SSLv23_METHOD

        esmtp_deferred = Deferred()
        esmtp_deferred.addErrback(esmtp_errback, event)
        esmtp_deferred.addCallback(result_deferred.callback)
    except Exception as excep:
        log.err("Error in Twisted objects init - unexpected exception in sendmail: %s" % str(excep))
        return fail()

    try:
        factory = ESMTPSenderFactory(
            authentication_username,
            authentication_password,
            from_address,
            to_address,
            message_file,
            esmtp_deferred,
            contextFactory=context_factory,
            requireAuthentication=(authentication_username and authentication_password),
            requireTransportSecurity=requireTransportSecurity,
            retries=notif_retries,
            timeout=notif_timeout)

        factory.protocol.sendError = esmtp_sendError
        factory.protocol.connectionLost = esmtp_connectionLost

        if security == "SSL":
            factory = tls.TLSMemoryBIOFactory(context_factory, True, factory)

    except Exception as excep:
        log.err("Error in factory init - unexpected exception in sendmail: %s" % str(excep))
        return fail()

    try:
        if not GLSettings.disable_mail_torification and GLSettings.memory_copy.notif_uses_tor:
            socksProxy = TCP4ClientEndpoint(reactor, GLSettings.socks_host, GLSettings.socks_port, timeout=notif_timeout)
            endpoint = SOCKS5ClientEndpoint(smtp_host.encode('utf-8'), smtp_port, socksProxy)
            d = endpoint.connect(factory)
            d.addErrback(socks_errback, event)
        else:
            endpoint = TCP4ClientEndpoint(reactor, smtp_host, smtp_port, timeout=notif_timeout)
            d = endpoint.connect(factory)
            d.addErrback(tcp4_errback, event)
    except Exception as excep:
        # we strongly need to avoid raising exception inside email logic to avoid chained errors
        log.err("unexpected exception in sendmail: %s" % str(excep))
        return fail()

    return result_deferred
Пример #39
0
def sendmail(authentication_username, authentication_password, from_address,
             to_address, message_file, smtp_host, smtp_port, security, event=None):
    """
    Sends an email using SSLv3 over SMTP

    @param authentication_username: account username
    @param authentication_secret: account password
    @param from_address: the from address field of the email
    @param to_address: the to address field of the email
    @param message_file: the message content its a StringIO
    @param smtp_host: the smtp host
    @param smtp_port: the smtp port
    @param event: the event description, needed to keep track of failure/success
    @param security: may need to be STRING, here is converted at start
    """
    def printError(reason, event):
        if isinstance(reason, Failure):
            reason = reason.type

        # XXX is catch a wrong TCP port, but not wrong SSL protocol, here
        if event:
            log.err("** failed notification within event %s" % event.type)
        # TODO Enhance with retry
        # TODO specify a ticket - make event an Obj instead of a namedtuple
        # TODO It's defined in plugin/base.py

        log.err("Failed to contact %s:%d (Sock Error %s)" %
                (smtp_host, smtp_port, reason))
        log.err(reason)

    def handle_error(reason, *args, **kwargs):
        printError(reason, event)
        return result_deferred.errback(reason)

    def protocolConnectionLost(self, reason=protocol.connectionDone):
        """We are no longer connected"""
        if isinstance(reason, Failure):
            if not isinstance(reason.value, error.ConnectionDone):
                log.err("Failed to contact %s:%d (ConnectionLost Error %s)"
                        % (smtp_host, smtp_port, reason.type))
                log.err(reason)

        self.setTimeout(None)
        self.mailFile = None

    def sendError(self, exc):
        if exc.code and exc.resp:
            log.err("Failed to contact %s:%d (STMP Error: %.3d %s)"
                    % (smtp_host, smtp_port, exc.code, exc.resp))
        SMTPClient.sendError(self, exc)

    try:
        security = str(security)
        result_deferred = Deferred()
        context_factory = ClientContextFactory()
        context_factory.method = SSL.SSLv3_METHOD

        if security != "SSL":
            requireTransportSecurity = True
        else:
            requireTransportSecurity = False

        esmtp_deferred = Deferred()
        esmtp_deferred.addErrback(handle_error, event)
        esmtp_deferred.addCallback(result_deferred.callback)

        factory = ESMTPSenderFactory(
            authentication_username,
            authentication_password,
            from_address,
            to_address,
            message_file,
            esmtp_deferred,
            contextFactory=context_factory,
            requireAuthentication=(authentication_username and authentication_password),
            requireTransportSecurity=requireTransportSecurity)

        factory.protocol.sendError = sendError
        factory.protocol.connectionLost = protocolConnectionLost

        if security == "SSL":
            factory = tls.TLSMemoryBIOFactory(context_factory, True, factory)

        if GLSetting.tor_socks_enable:
            socksProxy = TCP4ClientEndpoint(reactor, GLSetting.socks_host, GLSetting.socks_port)
            endpoint = SOCKS5ClientEndpoint(smtp_host, smtp_port, socksProxy)
        else:
            endpoint = TCP4ClientEndpoint(reactor, smtp_host, smtp_port)

        d = endpoint.connect(factory)
        d.addErrback(handle_error, event)

    except Exception as excep:
        # we strongly need to avoid raising exception inside email logic to avoid chained errors
        log.err("unexpected exception in sendmail: %s" % str(excep))
        return fail()

    return result_deferred