Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9201639
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T23:03:47+00:00 2026-06-17T23:03:47+00:00

I have the following code # logging from twisted.python import log import sys #

  • 0

I have the following code

# logging
from twisted.python import log

import sys

# MIME Multipart handling
import email
import email.mime.application
import uuid

# IMAP Connection
from twisted.mail import imap4
from twisted.internet import protocol


#SMTP Sending
import os.path
from OpenSSL.SSL import SSLv3_METHOD
from twisted.internet import ssl
from twisted.mail.smtp import ESMTPSenderFactory
from twisted.internet.ssl import ClientContextFactory
from twisted.internet.defer import Deferred
from twisted.internet import reactor

#class AccountsManager(object):


def connectToIMAPServer(imap_server, username, password):
    factory = IMAP4ClientFactory(username, password, login_insecure = True)

    host, port = imap_server.split(":")

    # connect to reactor
    if port == '993':
        reactor.connectSSL(host, int(port), factory, ssl.ClientContextFactory())
    else:
        if not port:
            port = 143
        reactor.connectTCP(host, int(port), factory)

    d = factory.deferred
    d.addCallback(lambda r: factory.proto)

    return d

class IMAP4Client(imap4.IMAP4Client):
    """
        A client with callbacks for greeting messages from an IMAP server.
        """
    greetDeferred = None

    def serverGreeting(self, caps):
        self.serverCapabilities = caps
        if self.greetDeferred is not None:
            d, self.greetDeferred = self.greetDeferred, None
            d.callback(self)

class IMAP4ClientFactory(protocol.ClientFactory):
    usedUp = False

    protocol = IMAP4Client


    def __init__(self, username, password, mailbox = "INBOX", login_insecure = False):
        self.ctx = ssl.ClientContextFactory()

        self.username = username
        self.password = password
        self.mailbox  = mailbox
        self.login_insecure = login_insecure

        self.deferred = Deferred()

    def buildProtocol(self, addr):
        """
            Initiate the protocol instance. Since we are building a simple IMAP
            client, we don't bother checking what capabilities the server has. We
            just add all the authenticators twisted.mail has.  Note: Gmail no
            longer uses any of the methods below, it's been using XOAUTH since
            2010.
            """
        assert not self.usedUp
        self.usedUp = True

        p = self.protocol(self.ctx)
        p.factory = self

        p.greetDeferred = self.deferred

        p.registerAuthenticator(imap4.PLAINAuthenticator(self.username))
        p.registerAuthenticator(imap4.LOGINAuthenticator(self.username))
        p.registerAuthenticator(imap4.CramMD5ClientAuthenticator(self.username))

        self.deferred.addCallback(self.GreetingCallback)
        self.deferred.addErrback(self.GreetingErrback)

        self.proto = p

        return p

    def GreetingCallback(self, result):
        print "Secure Login"
        auth_d = self.proto.authenticate(self.password)
        auth_d.addCallback(self.AuthenticationCallback)
        auth_d.addErrback(self.AuthenticationErrback)

        return auth_d # attach it to the main deferred

    def GreetingErrback(self, error):
        log.err(error)
        self.CloseConnection()
        return error

    def AuthenticationCallback(self, result):
        print "Selecting Mailbox"
        d = self.proto.examine(self.mailbox)
        return d

    def AuthenticationErrback(self, failure):
        if self.login_insecure:
            failure.trap(imap4.NoSupportedAuthentication)
            return self.InsecureLogin()
        else:
            return error

    def InsecureLogin(self):
        print "Insecure Login"
        d = self.proto.login(self.username, self.password)
        d.addCallback(self.AuthenticationCallback)
        return d

    def CloseConnection(self):
        self.proto.transport.loseConnection()

    def clientConnectionFailed(self, connector, reason):
        d, self.deferred = self.deferred, None
        d.errback(reason)


class MailServer(object):
    "Manages a server"

    size = 0
    used_space = 0


    def __init__(self, smtp_server, imap_server, username, password):
        self.smtp_server, self.smtp_port = smtp_server.split(":")
        self.imap_server, self.imap_port = imap_server.split(":")
        self.username = username
        self.password = password

        self.imap_connection = IMAP4ClientFactory(username, password)


    def upload_data(self, data):
        """
        Uploads data to email server returns deferred that will return with the imap uid
        """

        # Create a text/plain message
        id = str(uuid.uuid4()).upper()

        msg = email.mime.Multipart.MIMEMultipart()
        msg['Subject'] = 'GMA ID: %s' % id
        msg['From'] = self.email_address
        msg['To'] = self.email_address

        # The main body is just another attachment
        body = email.mime.Text.MIMEText("GMA ID: %s" % (self.uuid_id))
        msg.attach(body)
        att = email.mime.application.MIMEApplication(data,_subtype="raw")
        att.add_header('Content-Disposition','attachment',filename = os.path.basename(self.filename))
        msg.attach(att)

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

        d = Deferred()

        mime_obj = StringIO(str(msg))

        senderFactory = ESMTPSenderFactory(
                                           self.username,
                                           self.password,
                                           self.email_address,
                                           self.email_address,
                                           mime_obj,
                                           d,
                                           contextFactory=contextFactory)

        d.addCallback(lambda r: self.email_sent(id, int(self.parts)) )
        d.addErrback(self.email_error)

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

        d.addCallback(self.upload_success, *args, **kw)
        d.addErrback(self.upload_error, 1)

        return d


    def upload_success(self, result):
        print "upload was succesful!"

    def upload_error(self, result):
        print "upload error"

    def download_data(self, uid):
        """
        Downloads data from the email server returns a deferred that will return with the data
        """
        print "uid"


if __name__ == "__main__":
    log.startLogging(sys.stdout)
    d = connectToIMAPServer("imap.gmail.com:993", "username", "password")
    def f(s):
        print s


    d.addCallback(lambda r: f("These are fired before the auth and examine callbacks, why?"))
    d.addCallback(lambda r: f("These are fired before the auth and examine callbacks, why?"))
    reactor.run()

The class is suppose to handle logging in and selecting a mailbox and nicely return a IMAP proto ready to use however the two callbacks at the bottom are fired before the other ones, I get why, the callbacks are added before the other ones because buildProtocol hasn’t been called yet so what is the best way to handle this, just have a dummy callback added in init that “holds” the first spot?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T23:03:48+00:00Added an answer on June 17, 2026 at 11:03 pm
    from twisted.internet.endpoints import TCP4ClientEndpoint
    d = TCP4ClientEndpoint(reactor, host, int(port)).connect(factory)
    

    and

    d.addCallback(lambda r: factory.deferred)    
    

    instead of

    d = factory.deferred
    

    in connectToIMAPServer should do it – your factory.deferred will be returned only after protocol is ready. (Twisted Documentation on writing clients)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following code, copied from the Python manual: import logging LOG_FILENAME =
I have the following code inside my MainAcitivity for logging to the application using
I have following code for loading image from url in xml parsing endElement method
I have the following simple code from an exercise in Modern Javascript used to
I have the following code to retrieve the password of a user from the
I have following piece of code, which should be able to log to console
I have just noticed that when i call the following code from a console
I have the following code snippet. SqlCommand cmd = new SqlCommand(SELECT FName,LName FROM EMPLOYEE_TABLE
I have a simple NDB model: from google.appengine.ext import ndb import logging from libs
I have following code in initialization im = imread('Image02.tif'); figure(); imagesc(im); colormap(gray); [hImage hfig

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.