Ejemplo n.º 1
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.º 2
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.º 3
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
Ejemplo n.º 4
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.º 5
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.º 6
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.º 7
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.º 8
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.º 9
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
 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.º 11
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.º 12
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.º 13
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.º 14
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.º 15
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.º 16
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.º 17
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.º 18
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.º 19
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.º 20
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.º 21
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.º 22
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.º 23
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.º 24
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
Ejemplo n.º 25
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.º 26
0
def sendMessageFile(
    fromAddress,
    toAddress,
    messageFile,
    smtpHost=None,
    smtpPort=None,
    smtpUsername=None,
    smtpPassword=None,
):
    """
    @param smtpUsername: The username with which to authenticate.
    @param smtpPassword: 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.
    """

    resultDeferred = defer.Deferred()

    smtpPort = smtpPort or settings.EMAIL_PORT
    smtpHost = smtpHost or settings.EMAIL_HOST
    smtpUsername = smtpUsername or settings.EMAIL_USER
    smtpPassword = smtpPassword or settings.EMAIL_PASSWORD

    if smtpUsername or smtpPassword:
        senderFactory = ESMTPSenderFactory(
            smtpUsername,
            smtpPassword,
            fromAddress,
            toAddress,
            messageFile,
            resultDeferred,
        )
    else:
        senderFactory = SMTPSenderFactory(
            fromAddress,
            toAddress,
            messageFile,
            resultDeferred,
        )
    reactor.connectTCP(smtpHost, smtpPort, senderFactory)
    return resultDeferred
Ejemplo n.º 27
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.º 28
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.º 29
0
    def sendEmail(self, mEntity, subject, content):
        #self.dst_phone = self.getProp(self.__class__.PROP_DST_PHONE)

        timestamp = mEntity.getTimestamp()
        srcShort = mEntity.getFrom(full=False)

        formattedDate = datetime.datetime.fromtimestamp(timestamp) \
                                         .strftime('%d/%m/%Y %H:%M')
        content2 = "%s\n\nAt %s by %s (%s) isBroadCast=%s" \
                % (content, formattedDate, srcShort, mEntity.getParticipant(),
                    mEntity.isBroadcast())

        smtp_user = self.getProp(self.__class__.PROP_USER)
        dst_mail = self.getProp(self.__class__.PROP_DST_MAIL)
        reply_mail = self.getProp(self.__class__.PROP_REPLY_MAIL, None)
        msg = MIMEText(content2, 'plain', 'utf-8')
        msg['To'] = "WhatsApp <%s>" % (dst_mail)
        msg['From'] = "%s <%s>" % (srcShort, mEntity.getParticipant())
        msg['Reply-To'] = "%s <%s>" % (mEntity.getParticipant(), reply_mail)
        msg['Subject'] = subject
        msg['Date'] = formatdate(timestamp)
        msg_file = StringIO(msg.as_string())

        def success(r):
            print("Mail sent")

        def error(err):
            err.printTraceback()
            print("Smtp error ", err)

        dfr = defer.Deferred()
        dfr.addCallback(success)
        dfr.addErrback(error)
        if smtp_user:
            smtp_pass = self.getProp(self.__class__.PROP_PASS)
            factory = ESMTPSenderFactory(smtp_user, smtp_pass, reply_mail,
                                         dst_mail, msg_file, dfr)
        else:
            factory = SMTPSenderFactory(reply_mail, dst_mail, msg_file, dfr)

        endpoint = self.getProp(self.__class__.PROP_ENDPOINT)
        smtp_endpoint = endpoints.clientFromString(reactor, endpoint)
        smtp_endpoint.connect(factory)

        #s.sendmail(dst, [dst], msg.as_string())
        print("=> Mail: %s -> %s" % (reply_mail, dst_mail))
Ejemplo n.º 30
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