Ejemplo n.º 1
0
    def _sendmail(self, to_addrs, msg):
        # Import twisted.mail here because it is not available in python3
        from twisted.internet import reactor
        from twisted.mail.smtp import ESMTPSenderFactory

        msg = BytesIO(msg)
        d = defer.Deferred()
        factory = ESMTPSenderFactory(
            self.smtpuser,
            self.smtppass,
            self.mailfrom,
            to_addrs,
            msg,
            d,
            heloFallback=True,
            requireAuthentication=False,
            requireTransportSecurity=self.smtptls,
        )
        factory.noisy = False

        if self.smtpssl:
            reactor.connectSSL(self.smtphost, self.smtpport, factory,
                               ssl.ClientContextFactory())
        else:
            reactor.connectTCP(self.smtphost, self.smtpport, factory)

        return d
Ejemplo n.º 2
0
def send_plain_email(smtphost, username, password, fromEmail, toEmail, content, headers,
                     senderDomainName=None, port=25, requireSSL=True):
    requireAuth = bool(password)
    msg = MIMEText(content)

    # Setup the mail headers
    for (header, value) in headers.items():
        msg[header] = value

    headkeys = [k.lower() for k in headers.keys()]

    # Add required headers if not present
    if "message-id" not in headkeys:
        msg["Message-ID"] = messageid()
    if "date" not in headkeys:
        msg["Date"] = rfc822date()
    if "from" not in headkeys and "sender" not in headkeys:
        msg["From"] = fromEmail
    if "to" not in headkeys and "cc" not in headkeys and "bcc" not in headkeys:
        msg["To"] = toEmail

    # send message
    f = StringIO(msg.as_string())
    d = defer.Deferred()
    factory = ESMTPSenderFactory(username, password, fromEmail, toEmail, f, d,
                                 requireAuthentication=requireAuth,
                                 requireTransportSecurity=requireSSL)
    if senderDomainName is not None:
        factory.domain = senderDomainName
    connectTCP(smtphost, port, factory)

    return d
Ejemplo n.º 3
0
 def _sendmail(self, to_addrs, msg):
     msg = StringIO(msg)
     d = defer.Deferred()
     factory = ESMTPSenderFactory(self.smtpuser, self.smtppass, self.mailfrom, \
         to_addrs, msg, d, heloFallback=True, requireAuthentication=False, \
         requireTransportSecurity=False)
     factory.noisy = False
     reactor.connectTCP(self.smtphost, self.smtpport, factory)
     return d
Ejemplo n.º 4
0
 def _sendmail(self, to_addrs, msg):
     msg = StringIO(msg)
     d = defer.Deferred()
     factory = ESMTPSenderFactory(self.smtpuser, self.smtppass, self.mailfrom, \
         to_addrs, msg, d, heloFallback=True, requireAuthentication=False, \
         requireTransportSecurity=True)
     factory.noisy = False
     reactor.connectTCP(self.smtphost, self.smtpport, factory)
     return d
Ejemplo n.º 5
0
def sendMessage(config):
    # Make a message
    msg = Message.Message()
    msgid = Utils.make_msgid()
    # remember the msgid so we can find it later
    config.msgid = msgid
    msg['To'] = config.toAddress
    msg['From'] = config.fromAddress
    msg['Message-ID'] = msgid
    msg['X-Zenoss-Time-Sent'] = str(config.sent)
    msg['Subject'] = 'Zenoss Round-Trip Mail Message'
    msg.set_payload(config.messageBody)
    log.debug("Message id %s's length is %s bytes" %
              (msgid, len(msg.as_string())))
    msgIO = StringIO(msg.as_string())
    result = defer.Deferred()

    # figure out how we should connect
    connect = reactor.connectTCP
    port = 25
    kwargs = {}
    args = ()
    if ssl and config.smtpAuth == 'SSL':
        port = 465
        connect = reactor.connectSSL
        kwargs.update(dict(requireTransportSecurity=False))
        args = (ssl.ClientContextFactory(), )
    elif ssl and config.smtpAuth == 'TLS':
        pass
    else:
        kwargs.update(dict(requireTransportSecurity=False))

    if config.smtpUsername:
        log.debug("ESMTP login as %s/%s" %
                  (config.smtpUsername, "*" * len(config.smtpPassword)))
        factory = ESMTPSenderFactory(config.smtpUsername, config.smtpPassword,
                                     config.fromAddress, (config.toAddress, ),
                                     msgIO, result, **kwargs)
    else:
        factory = SMTPSenderFactory(config.fromAddress, (config.toAddress, ),
                                    msgIO, result)

    def clientConnectionFailed(self, why):
        result.errback(why)

    factory.clientConnectionFailed = clientConnectionFailed

    # initiate the message send
    log.debug("Sending message to %s:%s with args: %s" %
              (config.smtpHost, config.smtpPort or port, args))
    connect(config.smtpHost, config.smtpPort or port, factory, *args)
    return result
Ejemplo n.º 6
0
    def _sendmail(self, to_addrs, msg):
        msg = StringIO(msg)
        d = defer.Deferred()
        factory = ESMTPSenderFactory(self.smtpuser, self.smtppass, self.mailfrom,
                                     to_addrs, msg, d, heloFallback=True, requireAuthentication=False,
                                     requireTransportSecurity=self.smtptls)
        factory.noisy = False

        if self.smtpssl:
            reactor.connectSSL(self.smtphost, self.smtpport, factory, ssl.ClientContextFactory())
        else:
            reactor.connectTCP(self.smtphost, self.smtpport, factory)

        return d
Ejemplo n.º 7
0
    def _sendmail(self, to_addrs, msg):
        msg = StringIO(msg)
        d = defer.Deferred()
        factory = ESMTPSenderFactory(self.smtpuser, self.smtppass, self.mailfrom, to_addrs, msg, d, heloFallback=True,
                                     requireAuthentication=False,
                                     requireTransportSecurity=self.smtptls)
        factory.noisy = False

        if self.smtpssl:
            reactor.connectSSL(self.smtphost, self.smtpport, factory, ssl.ClientContextFactory())
        else:
            reactor.connectTCP(self.smtphost, self.smtpport, factory)

        return d
Ejemplo n.º 8
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
Ejemplo n.º 9
0
    def send(self, mail):
        # mail is of email module
        d = defer.Deferred()
        senderArgs = {
            'username': self.username,
            'password': self.password,
            'fromEmail': self.address,
            'toEmail': self._getRawAddress(mail['To']),
            'file': StringIO(str(mail)),
            'deferred': d,
            'retries': 5,
        }
        if self.ssl:
            senderArgs['contextFactory'] = ClientContextFactory()

        sender = ESMTPSenderFactory(**senderArgs)

        if self.ssl:
            port = self.port or 465
            reactor.connectSSL(self.server, port, sender,
                               ClientContextFactory())
        else:
            port = self.port or 25
            reactor.connectTCP(self.server, port, sender)

        d.addCallback(self.sent)
        d.addErrback(self.fail)
Ejemplo n.º 10
0
    def _get_factory(self, to, message, deferred):
        """
        """
        sender_factory = ESMTPSenderFactory(
            self._user,
            self._passwd,
            self._from_email,
            to,
            message,
            deferred,
            heloFallback=True,
            requireAuthentication=False,
            requireTransportSecurity=self._starttls)
        sender_factory.noisy = self._noisy

        return sender_factory
Ejemplo n.º 11
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
Ejemplo n.º 12
0
    def do_connect():
        """Connect and authenticate."""
        result_deferred = Deferred()
        context_factory = None
        if use_tls:
            from twisted.internet import ssl as twisted_ssl
            context_factory = twisted_ssl.ClientContextFactory()

        body = MIMEText(message)
        body['Subject'] = subject
        factory = ESMTPSenderFactory(username,
                                     password,
                                     from_address,
                                     to_address,
                                     StringIO(body.as_string()),
                                     result_deferred,
                                     contextFactory=context_factory,
                                     requireTransportSecurity=use_tls,
                                     requireAuthentication=True,
                                     heloFallback=helo_fallback)

        if use_tls:
            reactor.connectSSL(host, port, factory, context_factory)
        else:
            reactor.connectTCP(host, port, factory)
        result = yield result_deferred

        if result[0] == 0:
            raise RuntimeError("failed to send email via smtp")
Ejemplo n.º 13
0
    def _sendmail(self, to_addrs, msg):
        # Import twisted.mail here because it is not available in python3
        from twisted.mail.smtp import ESMTPSenderFactory
        msg = StringIO(msg)
        d = defer.Deferred()
        factory = ESMTPSenderFactory(self.smtpuser, self.smtppass, self.mailfrom, \
            to_addrs, msg, d, heloFallback=True, requireAuthentication=False, \
            requireTransportSecurity=self.smtptls)
        factory.noisy = False

        if self.smtpssl:
            reactor.connectSSL(self.smtphost, self.smtpport, factory, ssl.ClientContextFactory())
        else:
            reactor.connectTCP(self.smtphost, self.smtpport, factory)

        return d
Ejemplo n.º 14
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
Ejemplo n.º 15
0
    def sendMail(self, m, recipients):
        s = m.as_string()
        twlog.msg("sending mail (%d bytes) to" % len(s), recipients)

        result = defer.Deferred()

        useAuth = self.smtpUser and self.smtpPassword

        s = unicode2bytes(s)
        sender_factory = ESMTPSenderFactory(
            self.smtpUser,
            self.smtpPassword,
            self.fromaddr,
            recipients,
            BytesIO(s),
            result,
            requireTransportSecurity=self.useTls,
            requireAuthentication=useAuth)

        if self.useSmtps:
            reactor.connectSSL(self.relayhost, self.smtpPort, sender_factory,
                               ssl.ClientContextFactory())
        else:
            reactor.connectTCP(self.relayhost, self.smtpPort, sender_factory)

        return result
Ejemplo n.º 16
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
Ejemplo n.º 17
0
    def sendmail(self, s, recipients):
        result = defer.Deferred()

        if self.smtpUser and self.smtpPassword:
            useAuth = True
        else:
            useAuth = False

        sender_factory = ESMTPSenderFactory(
            self.smtpUser,
            self.smtpPassword,
            self.fromaddr,
            recipients,
            StringIO(s),
            result,
            requireTransportSecurity=self.useTls,
            requireAuthentication=useAuth)

        if self.useSmtps:
            reactor.connectSSL(self.relayhost, self.smtpPort, sender_factory,
                               ssl.ClientContextFactory())
        else:
            reactor.connectTCP(self.relayhost, self.smtpPort, sender_factory)

        return result
Ejemplo n.º 18
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
Ejemplo n.º 19
0
    def sendmail(self, s, recipients):
        result = defer.Deferred()

        if have_ssl and self.useTls:
            client_factory = ssl.ClientContextFactory()
            client_factory.method = SSLv3_METHOD
        else:
            client_factory = None

        if self.smtpUser and self.smtpPassword:
            useAuth = True
        else:
            useAuth = False

        sender_factory = ESMTPSenderFactory(
            self.smtpUser,
            self.smtpPassword,
            self.fromaddr,
            recipients,
            StringIO(s),
            result,
            contextFactory=client_factory,
            requireTransportSecurity=self.useTls,
            requireAuthentication=useAuth)

        reactor.connectTCP(self.relayhost, self.smtpPort, sender_factory)

        return result
Ejemplo n.º 20
0
    def send_html(cls, to, topic, message):
        config = ApplicationConfig.get_current_config()

        email = MIMEMultipart('alternative')
        email['Subject'] = topic
        email['From'] = config.google_user_email
        email['To'] = to
        email.attach(MIMEText(message,'html', 'utf-8'))

        formatted_mail = email.as_string()

        messageFile = StringIO(formatted_mail)

        resultDeferred = Deferred()

        senderFactory = ESMTPSenderFactory(
            config.google_user_email, # user
            config.google_user_password, # secret
            config.google_user_email, # from
            to, # to
            messageFile, # message
            resultDeferred, # deferred
            contextFactory=cls.contextFactory)

        reactor.connectTCP(cls.SMTP_SERVER, cls.SMTP_PORT, senderFactory)
        return resultDeferred
Ejemplo n.º 21
0
    def send_with_file(cls, to, topic, message, file_path):
        config = ApplicationConfig.get_current_config()

        email = MIMEMultipart()
        email['Subject'] = topic
        email['From'] = config.google_user_email
        email['To'] = to

        part = MIMEBase('application', "octet-stream")
        part.set_payload(open(file_path, "rb").read())
        Encoders.encode_base64(part)

        part.add_header('Content-Disposition', 'attachment; filename="%s"' % file_path.split('/')[-1])

        email.attach(part)
        email.attach(MIMEText(message))

        formatted_mail = email.as_string()

        messageFile = StringIO(formatted_mail)

        resultDeferred = Deferred()

        senderFactory = ESMTPSenderFactory(
            config.google_user_email, # user
            config.google_user_password, # secret
            config.google_user_email, # from
            to, # to
            messageFile, # message
            resultDeferred, # deferred
            contextFactory=cls.contextFactory)

        reactor.connectTCP(cls.SMTP_SERVER, cls.SMTP_PORT, senderFactory)
        return resultDeferred
Ejemplo n.º 22
0
def send_plain_email(fromEmail, toEmail, content, headers):
    if REQUIRE_AUTH:
        password = FilePath(SMTP_PASSWORD_PATH).getContent().strip()
    else:
        password = None

    msgstr = compose_plain_email(fromEmail, toEmail, content, headers)
    f = StringIO(msgstr)
    d = defer.Deferred()
    factory = ESMTPSenderFactory(SMTP_USERNAME, password, fromEmail, toEmail, f, d,
                                 requireAuthentication=REQUIRE_AUTH,
                                 requireTransportSecurity=REQUIRE_TRANSPORT_SECURITY)
    factory.domain = SENDER_DOMAIN
    connectTCP(SMTP_HOST, SMTP_PORT, factory)

    return d
Ejemplo n.º 23
0
    def sendMail(self, m, recipients):
        s = m.as_string()
        twlog.msg("sending mail ({} bytes) to".format(len(s)), recipients)
        if self.dumpMailsToLog:  # pragma: no cover
            twlog.msg("mail data:\n{0}".format(s))

        result = defer.Deferred()

        useAuth = self.smtpUser and self.smtpPassword

        s = unicode2bytes(s)
        recipients = [parseaddr(r)[1] for r in recipients]
        sender_factory = ESMTPSenderFactory(
            unicode2bytes(self.smtpUser),
            unicode2bytes(self.smtpPassword),
            parseaddr(self.fromaddr)[1],
            recipients,
            BytesIO(s),
            result,
            requireTransportSecurity=self.useTls,
            requireAuthentication=useAuth)

        if self.useSmtps:
            reactor.connectSSL(self.relayhost, self.smtpPort, sender_factory,
                               ssl.ClientContextFactory())
        else:
            reactor.connectTCP(self.relayhost, self.smtpPort, sender_factory)

        return result
 def sendMail(self, res):
     log.debug("In sendMail function")
     print res
     self.agi.email = res[0]['email']
     self.agi.indcn = res[0]['indcn']
     self.agi.infib = res[0]['infib']
     self.agi.emdcn = res[0]['emdcn']
     self.agi.emfib = res[0]['emfib']
     self.agi.attendance = res[0]['attendance']
     txt = "Hello ,\n\nInternal Marks:\n    Data Communication Network :%(indc)s\n    Fundamental Of Image Processing :%(infp)s\n\nExternal Marks:\n    Data Communication Network :%(emdc)s\n    Fundamental Of Image Processing :%(emfp)s\n\nAttendance :%(att)s\n\nThank you.\n- STUDENT INFORMATION SYSTEM"
     data = {
         "indc": self.agi.indcn,
         "infp": self.agi.infib,
         "emdc": self.agi.emdcn,
         "emfp": self.agi.emfib,
         "att": self.agi.attendance
     }
     msg = MIMEMultipart()
     msg['Subject'] = "University Student Information"
     msg['To'] = self.agi.email
     msg['From'] = "GIT <*****@*****.**>"
     textmsg = MIMEText(txt % data)
     msg.attach(textmsg)
     msg = StringIO(msg.as_string())
     df = defer.Deferred()
     df.addCallback(self.hangup)
     f = ESMTPSenderFactory(mailuser,
                            mailpasswd,
                            frommail,
                            self.agi.email,
                            msg,
                            df,
                            requireTransportSecurity=False,
                            requireAuthentication=True)
     reactor.connectTCP(mailhost, mailport, f)
Ejemplo n.º 25
0
def send_plain_email(fromEmail, toEmail, content, headers):
    if REQUIRE_AUTH:
        password = FilePath(SMTP_PASSWORD_PATH).getContent().strip()
    else:
        password = None

    msg = MIMEText(content)

    # Setup the mail headers
    for (header, value) in headers.items():
        msg[header] = value

    headkeys = [k.lower() for k in headers.keys()]

    # Add required headers if not present
    if "message-id" not in headkeys:
        msg["Message-ID"] = messageid()
    if "date" not in headkeys:
        msg["Date"] = rfc822date()
    if "from" not in headkeys and "sender" not in headkeys:
        msg["From"] = fromEmail
    if "to" not in headkeys and "cc" not in headkeys and "bcc" not in headkeys:
        msg["To"] = toEmail
    if "reply-to" not in headkeys:
        msg["Reply-To"] = SUPPORT_ADDRESS
    if "user-agent" not in headkeys:
        msg["User-Agent"] = USER_AGENT
    if "content-type" not in headkeys:
        msg["Content-Type"] = CONTENT_TYPE

    # send message
    f = StringIO(msg.as_string())
    d = defer.Deferred()
    factory = ESMTPSenderFactory(
        SMTP_USERNAME,
        password,
        fromEmail,
        toEmail,
        f,
        d,
        requireAuthentication=REQUIRE_AUTH,
        requireTransportSecurity=REQUIRE_TRANSPORT_SECURITY)
    factory.domain = SENDER_DOMAIN
    connectTCP(SMTP_HOST, SMTP_PORT, factory)

    return d
Ejemplo n.º 26
0
    def _get_factory(self, to, message, deferred):
        """
        """
        sender_factory = ESMTPSenderFactory(
            self._user,
            self._passwd,
            self._from_email,
            to,
            message,
            deferred,
            heloFallback=True,
            requireAuthentication=False,
            requireTransportSecurity=self._starttls
        )
        sender_factory.noisy = self._noisy

        return sender_factory
Ejemplo n.º 27
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
Ejemplo n.º 28
0
    def send_email(self, to_addr, subject, content):
        msg = self.message(to_addr, subject, content)

        d = defer.Deferred()
        factory = ESMTPSenderFactory(self.username,
                                     self.password,
                                     self.from_addr,
                                     to_addr,
                                     msg,
                                     d,
                                     requireTransportSecurity=False)

        if self.senderDomainName is not None:
            factory.domain = self.senderDomainName

        reactor.connectTCP(self.smtphost, self.port, factory)

        return d
Ejemplo n.º 29
0
    def sendMail(self, view, message):

        account = view[self.account].smtp

        authRequired = account.useAuth
        heloFallback = not authRequired
        securityRequired = account.connectionSecurity == 'TLS'

        if authRequired:
            username = account.username
            password = account.password
        else:
            username = None
            password = None

        retries = account.numRetries
        timeout = account.timeout

        deferred = Deferred()
        deferred.addCallback(self._sendSuccess)
        deferred.addErrback(self._sendFailure)

        class _protocol(_TwistedESMTPSender):
            def connectionMade(_self):
                self.output("smtp: connected to %s" % (account.host))
                _TwistedESMTPSender.connectionMade(_self)

        # the code below comes from osaf.mail.smtp
        factory = ESMTPSenderFactory(username, password,
                                     message['From'], message['To'],
                                     StringIO(str(message)), deferred, retries,
                                     timeout, 1, heloFallback, authRequired,
                                     securityRequired)
        factory.protocol = _protocol
        factory.testing = False

        if account.connectionSecurity == 'SSL':
            reactor.callFromThread(ssl.connectSSL, account.host, account.port,
                                   factory, view)
        else:
            reactor.callFromThread(ssl.connectTCP, account.host, account.port,
                                   factory, view)
Ejemplo n.º 30
0
    def sendMail(self, view, message):

        account = view[self.account].smtp

        authRequired = account.useAuth
        heloFallback = not authRequired
        securityRequired = account.connectionSecurity == 'TLS'

        if authRequired:
            username = account.username
            password = account.password
        else:
            username = None
            password = None

        retries = account.numRetries
        timeout = account.timeout

        deferred = Deferred()
        deferred.addCallback(self._sendSuccess)
        deferred.addErrback(self._sendFailure)

        class _protocol(_TwistedESMTPSender):
            def connectionMade(_self):
                self.output("smtp: connected to %s" %(account.host))
                _TwistedESMTPSender.connectionMade(_self)

        # the code below comes from osaf.mail.smtp
        factory = ESMTPSenderFactory(username, password, message['From'],
                                     message['To'], StringIO(str(message)),
                                     deferred, retries, timeout,
                                     1, heloFallback, authRequired,
                                     securityRequired)
        factory.protocol = _protocol
        factory.testing = False

        if account.connectionSecurity == 'SSL':
            reactor.callFromThread(ssl.connectSSL, account.host, account.port,
                                   factory, view)
        else:
            reactor.callFromThread(ssl.connectTCP, account.host, account.port,
                                   factory, view)
Ejemplo n.º 31
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,
        )
Ejemplo n.º 32
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
Ejemplo n.º 33
0
def send_plain_email(fromEmail, toEmail, content, headers):
    if REQUIRE_AUTH:
        password = FilePath(SMTP_PASSWORD_PATH).getContent().strip()
    else:
        password = None

    msg = MIMEText(content)

    # Setup the mail headers
    for (header, value) in headers.items():
        msg[header] = value

    headkeys = [k.lower() for k in headers.keys()]

    # Add required headers if not present
    if "message-id" not in headkeys:
        msg["Message-ID"] = messageid()
    if "date" not in headkeys:
        msg["Date"] = rfc822date()
    if "from" not in headkeys and "sender" not in headkeys:
        msg["From"] = fromEmail
    if "to" not in headkeys and "cc" not in headkeys and "bcc" not in headkeys:
        msg["To"] = toEmail
    if "reply-to" not in headkeys:
        msg["Reply-To"] = SUPPORT_ADDRESS
    if "user-agent" not in headkeys:
        msg["User-Agent"] = USER_AGENT
    if "content-type" not in headkeys:
        msg["Content-Type"] = CONTENT_TYPE

    # send message
    f = StringIO(msg.as_string())
    d = defer.Deferred()
    factory = ESMTPSenderFactory(SMTP_USERNAME, password, fromEmail, toEmail, f, d,
                                 requireAuthentication=REQUIRE_AUTH,
                                 requireTransportSecurity=REQUIRE_TRANSPORT_SECURITY)
    factory.domain = SENDER_DOMAIN
    connectTCP(SMTP_HOST, SMTP_PORT, factory)

    return d
Ejemplo n.º 34
0
def send_plain_email(fromEmail, toEmail, content, headers):
    if REQUIRE_AUTH:
        password = FilePath(SMTP_PASSWORD_PATH).getContent().strip()
    else:
        password = None

    msgstr = compose_plain_email(fromEmail, toEmail, content, headers)
    f = StringIO(msgstr)
    d = defer.Deferred()
    factory = ESMTPSenderFactory(
        SMTP_USERNAME,
        password,
        fromEmail,
        toEmail,
        f,
        d,
        requireAuthentication=REQUIRE_AUTH,
        requireTransportSecurity=REQUIRE_TRANSPORT_SECURITY)
    factory.domain = SENDER_DOMAIN
    connectTCP(SMTP_HOST, SMTP_PORT, factory)

    return d
Ejemplo n.º 35
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,
        )
Ejemplo n.º 36
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
Ejemplo n.º 37
0
 def build_sender_factory(**kwargs: Any) -> ESMTPSenderFactory:
     return ESMTPSenderFactory(
         username,
         password,
         from_addr,
         to_addr,
         msg,
         d,
         heloFallback=True,
         requireAuthentication=require_auth,
         requireTransportSecurity=require_tls,
         **kwargs,
     )
Ejemplo n.º 38
0
    def sendMessage(self, fromAddr, toAddr, msgId, message):

        log.debug("Sending: {msg}", msg=message)

        def _success(result, msgId, fromAddr, toAddr):
            log.info(
                "Sent IMIP message {id} from {fr} to {to}",
                id=msgId,
                fr=fromAddr,
                to=toAddr,
            )
            return True

        def _failure(failure, msgId, fromAddr, toAddr):
            log.error(
                "Failed to send IMIP message {id} from {fr} to {to} (Reason: {err})",
                id=msgId,
                fr=fromAddr,
                to=toAddr,
                err=failure.getErrorMessage(),
            )
            from OpenSSL.SSL import Error as TLSError
            if failure.type is TLSError:
                from calendarserver.tap.util import AlertPoster
                AlertPoster.postAlert("MailCertificateAlert", 7 * 24 * 60 * 60,
                                      [])
            return False

        deferred = defer.Deferred()

        if self.useSSL:
            contextFactory = simpleClientContextFactory(self.server)
        else:
            contextFactory = None

        factory = ESMTPSenderFactory(
            self.username,
            self.password,
            fromAddr,
            toAddr,
            # per http://trac.calendarserver.org/ticket/416 ...
            StringIO(message.replace("\r\n", "\n")),
            deferred,
            contextFactory=contextFactory,
            requireAuthentication=False,
            requireTransportSecurity=self.useSSL)

        connect(GAIEndpoint(_reactor, self.server, self.port), factory)
        deferred.addCallback(_success, msgId, fromAddr, toAddr)
        deferred.addErrback(_failure, msgId, fromAddr, toAddr)
        return deferred
Ejemplo n.º 39
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)
Ejemplo n.º 40
0
    def tls_sendmail(self, s, recipients):
        client_factory = ssl.ClientContextFactory()
        client_factory.method = SSLv3_METHOD

        result = defer.Deferred()

        
        sender_factory = ESMTPSenderFactory(
            self.smtpUser, self.smtpPassword,
            self.fromaddr, recipients, StringIO(s),
            result, contextFactory=client_factory)

        reactor.connectTCP(self.relayhost, self.smtpPort, sender_factory)
        
        return result
Ejemplo n.º 41
0
 def buildProtocol(self, addr):
     p = pdroid.connections[self.id] = ESMTPSenderFactory.buildProtocol(self, addr)
     p.factory = self
     return p